-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnode_scim_server.js
387 lines (344 loc) · 12.4 KB
/
node_scim_server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/** Copyright © 2016, Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Dependencies
var express = require('express');
var app = express();
var sqlite3 = require('sqlite3').verbose();
var url = require('url');
var uuid = require('uuid');
var bodyParser = require('body-parser');
var db = new sqlite3.Database('test.db');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
/**
* Constructor for creating SCIM Resource
*/
function GetSCIMList(rows, startIndex, count, req_url) {
var scim_resource = {
"Resources": [],
"itemsPerPage": 0,
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"startIndex": 0,
"totalResults": 0
}
var resources = [];
var location = ""
for (var i = (startIndex-1); i < count; i++) {
location = req_url + "/" + rows[i]["id"];
var userResource = GetSCIMUserResource(
rows[i]["id"],
rows[i]["active"],
rows[i]["userName"],
rows[i]["givenName"],
rows[i]["middleName"],
rows[i]["familyName"],
location);
resources.push(userResource);
location = "";
}
scim_resource["Resources"] = resources;
scim_resource["startIndex"] = startIndex;
scim_resource["itemsPerPage"] = count;
scim_resource["totalResults"] = count
return scim_resource;
}
/**
* Returns JSON dictionary of SCIM response
*/
function GetSCIMUserResource(userId, active, userName,
givenName, middleName, familyName, req_url) {
var scim_user = {
"schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ],
"id": null,
"userName": null,
"name": {
"givenName": null,
"middleName": null,
"familyName": null,
},
"active": false,
"meta": {
"resourceType": "User",
"location": null,
}
};
scim_user["meta"]["location"] = req_url;
scim_user["id"] = userId;
scim_user["active"] = active;
scim_user["userName"] = userName;
scim_user["name"]["givenName"] = givenName;
scim_user["name"]["middleName"] = middleName;
scim_user["name"]["familyName"] = familyName;
return scim_user;
}
/**
* Returns an error message and status code
*/
function SCIMError(errorMessage, statusCode) {
var scim_error = {
"schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],
"detail": null,
"status": null
}
scim_error["detail"] = errorMessage;
scim_error["status"] = statusCode;
return scim_error;
}
/**
* Creates a new User with given attributes
*/
app.post('/scim/v2/Users', function (req, res) {
var url_parts = url.parse(req.url, true);
var req_url = url_parts.pathname;
var requestBody = "";
req.on('data', function (data) {
requestBody += data;
var userJsonData = JSON.parse(requestBody);
var active = userJsonData['active'];
var userName = userJsonData['userName'];
var givenName = userJsonData["name"]["givenName"];
var middleName = userJsonData["name"]["middleName"];
var familyName = userJsonData["name"]["familyName"];
var usernameQuery = "SELECT * FROM Users WHERE userName='" + userName + "'";
db.get(usernameQuery, function(err, rows) {
if (err == null) {
if (rows === undefined) {
var userId = String(uuid.v1());
var runQuery = "INSERT INTO 'Users' (id, active, userName, givenName,\
middleName, familyName) VALUES ('" + userId + "','"
+ active + "','" + userName + "','" + givenName + "','"
+ familyName + "')";
db.run(runQuery, function(err) {
if(err !== null) {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
} else {
var scimUserResource = GetSCIMUserResource(userId, active, userName,
givenName, middleName, familyName, req_url);
res.writeHead(201, {'Content-Type': 'text/json'});
res.end(JSON.stringify(scimUserResource));
}
});
} else {
var scim_error = SCIMError( "Conflict - Resource Already Exists", "409");
res.writeHead(409, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
}
} else {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
}
});
});
});
/**
* Return filtered Users stored in database
*
* Pagination supported
*/
app.get("/scim/v2/Users", function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
startIndex = query["startIndex"];
count = query["count"];
filter = query["filter"];
var req_url = url_parts.pathname;
var selectQuery = "SELECT * FROM Users";
var queryAtrribute = "";
var queryValue = "";
if (filter != undefined) {
queryAtrribute = String(filter.split("eq")[0]).trim();
queryValue = String(filter.split("eq")[1]).trim();
selectQuery = "SELECT * FROM Users WHERE " + queryAtrribute + " = " + queryValue;
}
db.all(selectQuery , function(err, rows) {
if (err == null) {
if (rows === undefined) {
var scim_error = SCIMError( "User Not Found", "404");
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
} else {
// If requested no. of users is less than all users
if (rows.length < count) {
count = rows.length
}
var scimResource = GetSCIMList(rows,startIndex,count,req_url);
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(JSON.stringify(scimResource))
}
} else {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
}
});
});
/**
* Queries database for User with identifier
*
* Updates response code with '404' if unable to locate User
*/
app.get("/scim/v2/Users/:userId", function (req, res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var userId = req.params.userId;
startIndex = query["startIndex"]
count = query["count"]
var req_url = req.url;
var queryById = "SELECT * FROM Users WHERE id='" + userId + "'";
db.get(queryById, function(err, rows) {
if (err == null) {
if (rows === undefined){
var scim_error = SCIMError( "User Not Found", "404");
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
} else {
var scimUserResource = GetSCIMUserResource(userId, rows.active, rows.userName,
rows.givenName, rows.middleName, rows.familyName, req_url);
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(JSON.stringify(scimUserResource));
}
} else {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
}
});
});
/**
* Update User attributes via Patch
*/
app.patch("/scim/v2/Users/:userId", function (req, res) {
var userId = req.params.userId;
var url_parts = url.parse(req.url, true);
var req_url = url_parts.pathname;
var op = "";
var value = "";
var requestBody = "";
req.on('data', function (data) {
requestBody += data;
var jsonReqBody = JSON.parse(requestBody);
op = jsonReqBody["Operations"][0]["op"];
value = jsonReqBody["Operations"][0]["value"];
var attribute = Object.keys(value)[0];
var attrValue = value[attribute];
if (op == "replace") {
var updateUsersQuery = "UPDATE 'Users' SET "+ attribute + " = '"
+ attrValue + "'WHERE id = '" + String(userId) + "'";
db.run(updateUsersQuery, function(err) {
if (err == null) {
var queryById = "SELECT * FROM Users WHERE id='"+userId+"'";
db.get(queryById, function(err, rows) {
if (err == null) {
var scimUserResource = GetSCIMUserResource(userId, rows.active, rows.userName,
rows.givenName, rows.middleName, rows.familyName, req_url);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(scimUserResource));
} else {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'application/text' });
res.end(JSON.stringify(scim_error));
}
});
} else {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, { 'Content-Type': 'application/text' });
res.end(JSON.stringify(scim_error));
}
});
} else {
var scim_error = SCIMError( "Operation Not Supported", "403");
res.writeHead(403, {'Content-Type': 'application/text' });
res.end(JSON.stringify(scim_error));
}
});
});
/**
* Update User attributes via Patch
*/
app.put("/scim/v2/Users/:userId", function (req, res) {
var userId = req.params.userId;
var url_parts = url.parse(req.url, true);
var req_url = url_parts.pathname;
var requestBody = "";
req.on('data', function (data) {
requestBody += data;
var userJsonData = JSON.parse(requestBody);
var active = userJsonData['active'];
var userName = userJsonData['userName'];
var givenName = userJsonData["name"]["givenName"];
var middleName = userJsonData["name"]["middleName"];
var familyName = userJsonData["name"]["familyName"];
var queryById = "SELECT * FROM Users WHERE id='" + userId + "'";
db.get(queryById, function(err, rows) {
if (err == null) {
if (rows != undefined){
var updateUsersQuery = "UPDATE 'Users' SET userName = '" + String(userName)
+ "', givenName = '" + String(givenName) + "', middleName ='"
+ String(middleName) + "', familyName= '" + String(familyName)
+ "' WHERE id = '" + userId + "'";
db.run(updateUsersQuery, function(err) {
if(err !== null) {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
} else {
var scimUserResource = GetSCIMUserResource(userId, active, userName,
givenName, middleName, familyName, req_url);
res.writeHead(201, {'Content-Type': 'text/json'});
res.end(JSON.stringify(scimUserResource));
}
});
} else {
var scim_error = SCIMError( "User Does Not Exist", "404");
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
}
} else {
var scim_error = SCIMError( String(err), "400");
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(scim_error));
}
});
});
});
/**
* Default URL
*/
app.get('/scim/v2', function (req, res) { res.send('SCIM'); });
/**
* Instantiates or connects to DB
*/
var server = app.listen(8081, function () {
var databaseQuery = "SELECT name FROM sqlite_master WHERE type='table' \
AND name='Users'";
db.get(databaseQuery, function(err, rows) {
if(err !== null) { console.log(err); }
else if(rows === undefined) {
var createTable = 'CREATE TABLE Users ("id" primary key, \
"active" INTEGER,"userName" VARCHAR(255), \
"givenName" VARCHAR(255), "middleName" VARCHAR(255), \
"familyName" VARCHAR(255))';
db.run(createTable, function(err) {
if(err !== null) { console.log(err); }
});
}
});
});