-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathaccessControl.js
988 lines (930 loc) · 32.5 KB
/
accessControl.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
/* eslint-disable max-len */
/* eslint-disable no-underscore-dangle */
const DispatchRequest = require('./dispatchRequest');
const ErrorMessage = require('./errorMessage');
const CONST = require('./const');
const UTILS = require('./utils');
// eslint-disable-next-line no-unused-vars
const typedef = require('./typedef');
/**
* @license Apache Version 2
* @module AccessControl
* @constructor AccessControl
* @description The AccessControl is a driver to work with
* TerminusDB and TerminusX access control api
* for the credential you can use the JWT token, the API token or
* the basic authentication with username and password
* @example
* //connect with the API token
* //(to request a token create an account in https://terminusdb.com/)
* const accessContol = new AccessControl("https://servername.com",
* {organization:"my_team_name",
* token:"dGVybWludXNkYjovLy9kYXRhL2tleXNfYXB........"})
* accessControl.getOrgUsers().then(result=>{
* console.log(result)
* })
*
* //connect with the jwt token this type of connection is only for the dashboard
* //or for application integrate with our login workflow
* const accessContol = new AccessControl("https://servername.com",
* {organization:"my_team_name",
* jwt:"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkpXUjBIOXYyeTFORUd........"})
* accessControl.getOrgUsers().then(result=>{
* console.log(result)
* })
*
* //if the jwt is expired you can change it with
* accessControl.setJwtToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkpXUjBIOXYy
* eTFORUd.......")
*
* //connect with the base authentication this type of connection is only for the local installation
* const accessContol = new AccessControl("http://localhost:6363",
* {organization:"my_team_name", user:"admin"
* key:"mykey"})
* accessControl.getOrgUsers().then(result=>{
* console.log(result)
* })
*
*/
function AccessControl(cloudAPIUrl, params) {
this.baseURL = this.getAPIUrl(cloudAPIUrl);
if (!params) return;
if (params.jwt) {
this.setJwtToken(params.jwt);
} else if (params.token) {
this.setApiToken(params.token);
} else if (params.key) {
this.setApiKey(params.key);
this.user = params.user;
}
this.defaultOrganization = this.getDefaultOrganization(params);
}
/**
* Get a organization from parameters.
* @param {object} params - The parameters
* @return {string|undefined} - organization
*/
AccessControl.prototype.getDefaultOrganization = function (params) {
if (params && params.organization && typeof params.organization === 'string') {
return params.organization;
}
return undefined;
};
/**
* Sets the Jwt token for the object
* @param {string} jwt - The jwt api token to use
*/
AccessControl.prototype.setJwtToken = function (jwt) {
if (!jwt) {
throw new Error('TerminusX Access token required');
}
this.apiKey = jwt;
this.apiType = 'jwt';
};
/**
* Sets the API token for the object, to request a token create an account in https://terminusdb.com/
* @param {string} atokenpi - The API token to use to connect with TerminusX
*/
AccessControl.prototype.setApiToken = function (token) {
if (!token) {
throw new Error('TerminusX Access token required');
}
this.apiKey = token;
this.apiType = 'apikey';
};
/**
* Sets the API token for the object, to request a token create an account in https://terminusdb.com/
* @param {string} atokenpi - The API token to use to connect with TerminusX
*/
AccessControl.prototype.setApiKey = function (key) {
if (!key) {
throw new Error('TerminusDB bacis authentication key required');
}
this.apiKey = key;
this.apiType = 'basic';
};
/**
* Get a API url from cloudAPIUrl
* @param {string} cloudAPIUrl - The base url for cloud
* @return {string} apiUrl
*/
AccessControl.prototype.getAPIUrl = function (cloudAPIUrl) {
if (!cloudAPIUrl || typeof cloudAPIUrl !== 'string') {
throw new Error('TerminusX api url required!');
}
if (cloudAPIUrl.lastIndexOf('/') !== cloudAPIUrl.length - 1) {
// eslint-disable-next-line no-param-reassign
cloudAPIUrl += '/'; // always append slash to ensure regularity
}
return `${cloudAPIUrl}api`;
};
AccessControl.prototype.dispatch = function (requestUrl, action, payload) {
if (!requestUrl) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
action,
'Invalid request URL',
),
),
);
}
return DispatchRequest(
requestUrl,
action,
payload,
{ type: this.apiType, key: this.apiKey, user: this.user },
null,
this.customHeaders(),
);
};
/**
* add extra headers to your request
* @param {object} customHeaders
* @returns {object}
*/
// eslint-disable-next-line consistent-return
AccessControl.prototype.customHeaders = function (customHeaders) {
if (customHeaders) this._customHeaders = customHeaders;
else return this._customHeaders;
};
/**
* -- TerminusDB API ---
* Get an organization from the TerminusDB API.
* @param {string} organization - The organization
* @return {object} - organization
*/
AccessControl.prototype.getOrganization = function (org) {
return this.dispatch(`${this.baseURL}/organizations/${org}`, CONST.GET);
};
/**
* -- TerminusDB API ---
* This end point works in basic authentication, admin user
* Get list of organizations
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
*/
AccessControl.prototype.getAllOrganizations = function () {
return this.dispatch(`${this.baseURL}/organizations`, CONST.GET);
};
/**
* -- TerminusDB API ---
* This end point works in basic authentication, admin user
* Create an organization
* @param {string} orgName - The organization name to create
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.createOrganization("my_org_name").then(result=>{
* console.log(result)
* })
*/
AccessControl.prototype.createOrganization = function (orgName) {
// maybe we have to review this
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(orgName)}`, CONST.POST, {});
};
/**
* -- TerminusDB API ---
* Delete an Organization
* @param {string} orgName - The organization name to delete
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.deleteOrganization("my_org_name").then(result=>{
* console.log(result)
* })
*/
AccessControl.prototype.deleteOrganization = function (orgName) {
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(orgName)}`, CONST.DELETE);
};
/**
* --TerminusDB API ---
* basic authentication, admin user.
* Create a new role in the system database.
* @param {string} [name] - The role name.
* @param {typedef.RolesActions} [actions] - A list of actions
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.createRole("Reader",[ACTIONS.INSTANCE_READ_ACCESS]).then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.createRole = function (name, actions) {
const payload = { name, action: actions };
return this.dispatch(`${this.baseURL}/roles`, CONST.POST, payload);
};
/**
* -- TerminusdDB API ---
* basic Authentication, admin user.
* Delete role in the system database, (this api is enabled only in the local installation)
* @param {string} [name] - The role name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.deleteRole("Reader").then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.deleteRole = function (name) {
return this.dispatch(`${this.baseURL}/roles/${UTILS.encodeURISegment(name)}`, CONST.DELETE);
};
/**
* -- TerminusdDB API ---
* basic Authentication, admin user.
* Return the list of all the users (this api is enabled only in the local installation)
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.getAllUsers().then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.getAllUsers = function () {
return this.dispatch(`${this.baseURL}/users`, CONST.GET);
};
/**
* -- TerminusdDB API ---
* basic Authentication, admin user.
* Add the user into the system database
* @param {string} name - the user name
* @param {string} [password] - you need the password for basic authentication
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.deleteUser(userId).then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.createUser = function (name, password) {
const payload = { name, password };
return this.dispatch(`${this.baseURL}/users`, CONST.POST, payload);
};
/**
* -- TerminusdDB API ---
* basic Authentication, admin user.
* Remove the user from the system database.
* @param {string} userId - the document user id
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.deleteUser(userId).then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.deleteUser = function (userId) {
return this.dispatch(`${this.baseURL}/users/${UTILS.encodeURISegment(userId)}`, CONST.DELETE);
};
/**
* -- TerminusdDB API ---
* Grant/Revoke Capability
* @param {string} userName - the document user id
* @param {string} resourceName - the name of a (database or team)
* @param {array} rolesArr - the roles name list
* @param {typedef.CapabilityCommand} operation - grant/revoke operation
* @param {typedef.ScopeType} [scopeType] - the resource type (database or organization)
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* //we add an user to an organization and manage users' access
* //the user myUser can access the Organization and all the database under the organization with "reader" Role
* client.manageCapability(myUser,myteam,[reader],"grant","organization").then(result=>{
* consol.log(result)
* })
*
* //the user myUser can access the database db__001 under the organization myteam
* //with "writer" Role
* client.manageCapability(myUser,myteam/db__001,[writer],"grant","database").then(result=>{
* consol.log(result)
* })
*/
AccessControl.prototype.manageCapability = function (userName, resourceName, rolesArr, operation, scopeType) {
const payload = {
operation,
user: userName,
roles: rolesArr,
scope: resourceName,
scope_type: scopeType,
};
return this.dispatch(`${this.baseURL}/capabilities`, CONST.POST, payload);
};
/**
* --TerminusX and TerminusDB API ---
* Get all the system database roles types.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
*/
AccessControl.prototype.getAccessRoles = function () {
return this.dispatch(`${this.baseURL}/roles`, CONST.GET);
};
/**
* -- TerminusX and TerminusDB API --
* Get all the organization's users and roles,
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.getOrgUsers().then(result=>{
* console.log(result)
* })
*
* //this function will return an array of capabilities with users and roles
* //-- TerminusX -- response array example
* //[{capability: "Capability/3ea26e1d698821c570afe9cb4fe81a3......"
* // email: {@type: "xsd:string", @value: "[email protected]"}
* // picture: {@type: "xsd:string",…}
* // role: "Role/dataReader"
* // scope: "Organization/my_org_name"
* // user: "User/auth0%7C613f5dnndjdjkTTT"}]
* //
* //
* // -- Local Installation -- response array example
* //[{ "@id":"User/auth0%7C615462f8ab33f4006a6bee0c",
* // "capability": [{
* // "@id":"Capability/c52af34b71f6f8916ac0115ecb5fe0e31248ead8b1e3d100852015...",
* // "@type":"Capability",
* // "role": [{
* // "@id":"Role/admin",
* // "@type":"Role",
* // "action": ["instance_read_access"],
* // "name":"Admin Role"
* // }],
* // "scope":"Organization/@team"}]]
*/
AccessControl.prototype.getOrgUsers = function (orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'GET',
'Please provide a organization name',
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/users`, CONST.GET);
};
/**
* -- TerminusX and TerminusDB API --
* Get the user roles for a given organization or the default organization,
* @param {string} [userName] - The organization name.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.getTeamUserRole("myUser").then(result=>{
* console.log(result)
* })
*
* //response object example
* {
* "@id": "User/myUser",
* "capability": [
* {
* "@id":"Capability/server_access",
* "@type":"Capability",
* "role": [{
* "@id":"Role/reader",
* "@type":"Role",
* "action": [
* "instance_read_access",
* ],
* "name":"reader"
* }],
* "scope":"Organization/myteam"
* }
* ],
* "name": "myUser"
*}
*/
AccessControl.prototype.getTeamUserRoles = function (userName, orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'GET',
'Please provide a organization name',
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/users/${UTILS.encodeURISegment(userName)}`, CONST.GET);
};
/**
* -- TerminusX API ---
* Check if the organization exists. it is a Head call .
* IMPORTANT This does not work with the API-TOKEN.
* @param {string} orgName - The organization name to check if exists.
* @return {Promise} A promise that returns the call status object, 200: if the organization
* exists and 404: if the organization does not exist
*/
AccessControl.prototype.ifOrganizationExists = function (orgName) {
if (!orgName) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'HEAD',
'Please provide a organization name',
),
),
);
}
return this.dispatch(`${this.baseURL}/private/organizations/${UTILS.encodeURISegment(orgName)}`, CONST.HEAD);
};
/**
* -- TerminusX API ---
* IMPORTANT This does not work with the API-TOKEN.
* Create an organization
* @param {string} orgName - The organization name to create
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.createOrganization("my_org_name").then(result=>{
* console.log(result)
* })
*/
AccessControl.prototype.createOrganizationRemote = function (orgName) {
const payload = { organization: orgName };
return this.dispatch(`${this.baseURL}/private/organizations`, CONST.POST, payload);
};
/**
* -- TerminusX API ---
* Get the pending invitations list.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* const invitationList = accessControl.getPendingOrgInvites().then(result=>{
* console.log(invitationList)
*
* })
* //this will return an array of invitations object like this
* //[{@id: "Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9c0dfc2ac51161ef5ba
* cb0988d992c4bce82b3fa5d25"
* // @type: "Invitation"
* // creation_date: "2021-10-22T11:13:28.762Z"
* // email_to: "[email protected]"
* // invited_by: "User/auth0%7C6162f8ab33567406a6bee0c"
* // role: "Role/dataReader"
* // status: "needs_invite"}]
*
*/
AccessControl.prototype.getPendingOrgInvites = function (orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'GET',
'Please provide a organization name',
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/invites`, CONST.GET);
};
/**
* -- TerminusX API ---
* Send a new invitation
* @param {string} userEmail - The email of user.
* @param {string} role - The role for user. (the document @id role like Role/collaborator)
* @param {string} [note] - The note to send with the invitation.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.sendOrgInvite("[email protected]","Role/admin",
* "please join myteam").then(result=>{
* console.log(result)
* })
*/
// eslint-disable-next-line default-param-last
AccessControl.prototype.sendOrgInvite = function (userEmail, role, note = '', orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!userEmail) {
errorMessage = 'Please provide a user email';
} else if (!role) {
errorMessage = 'Please provide a role';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'POST',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/invites`, CONST.POST, {
email_to: userEmail,
role,
note,
});
};
/**
* -- TerminusX API ---
* Get the invitation info
* @param {string} inviteId - The invite id to retrieve.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* const fullInviteId="Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9c0dfc
* 2ac51161ef5ba7cb0988d992c4bce82b3fa5d25"
* accessControl.getOrgInvite(fullInviteId).then(result=>{
* console.log(result)
* })
*/
AccessControl.prototype.getOrgInvite = function (inviteId, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!inviteId) {
errorMessage = 'Please provide a invite id';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'POST',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const inviteHash = UTILS.removeDocType(inviteId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/invites/${inviteHash}`, CONST.GET);
};
/**
* -- TerminusX API ---
* Delete an invitation
* @param {string} inviteId - The invite id to delete.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* const fullInviteId="Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9
* c0dfc2ac51161ef5ba7cb0988d992c4bce82b3fa5d25"
* accessControl.deleteOrgInvite(fullInviteId).then(result=>{
* console.log(result)
* })
*/
AccessControl.prototype.deleteOrgInvite = function (inviteId, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!inviteId) {
errorMessage = 'Please provide a invite id';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'POST',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const inviteHash = UTILS.removeDocType(inviteId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/invites/${inviteHash}`, CONST.DELETE);
};
/**
* -- TerminusX API ---
* Accept /Reject invitation. if the invitation has been accepted we add the current user
* to the organization.
*
* the only user that can accept this invitation is the user registered with the invitation email,
* we indentify the user with the jwt token
* @param {string} inviteId - The invite id to updated.
* @param {boolean} accepted - The status of the invitation.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* const fullInviteId="Organization/my_team_name/invitations/Invitation/7ad0c9eb82b6175bcda9
* c0dfc2ac51161ef5ba7cb0988d992c4bce82b3fa5d25"
* accessControl.updateOrgInviteStatus(fullInviteId,true).then(result=>{
* console.log(result)
* })
*/
AccessControl.prototype.updateOrgInviteStatus = function (inviteId, accepted, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!inviteId) {
errorMessage = 'Please provide a invite id';
} else if (typeof accepted === 'undefined') {
errorMessage = 'Please provide a accepted status';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'PUT',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const inviteHash = UTILS.removeDocType(inviteId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/invites/${inviteHash}`, CONST.PUT, {
accepted,
});
};
/**
* -- TerminusX API ---
* Get the user role for a given organization or the default organization
* The user is identified by the jwt or the access token
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.getTeamUserRole().then(result=>{
* console.log(result)
* })
*
* //response object example
* {"userRole":"Role/admin"}
*/
AccessControl.prototype.getTeamUserRole = function (orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'GET',
'Please provide a organization name',
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/role`, CONST.GET);
};
/**
* -- TerminusX API --
* Remove an user from an organization, only an admin user can remove an user from an organization
* @param {string} userId - The id of the user to be removed. (this is the document user's @id)
* @param {string} [orgName] - The organization name in which the user is to be removed.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.removeUserFromOrg("User/auth0%7C613f5dnndjdjkTTT","my_org_name").then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.removeUserFromOrg = function (userId, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!userId) {
errorMessage = 'Please provide a userId';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'DELETE',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const user = UTILS.removeDocType(userId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/users/${user}`, CONST.DELETE);
};
/**
* -- TerminusX API --
* Get the user's role for every databases under the organization
* @param {string} userId - The user's id.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.getDatabaseRolesOfUser('User/auth0%7C61790e366377Yu6596a').then(result=>{
* console.log(result)
* })
*
* //this is a capabilities list of databases and roles
* //[ {capability: "Capability/b395e8523d509dec6b33aefc9baed3b2e2bfadbd4c79d4ff9b20dce2b14e2edc"
* //if there is an id we have a user specific capabality for this database
* // name: {@type: "xsd:string", @value: "profiles_test"}
* // role: "Role/dataUpdater"
* // scope: "UserDatabase/7ebdfae5a02bc7e8f6d79sjjjsa4e179b1df9d4576a3b1d2e5ff3b4859"
* // user: "User/auth0%7C61790e11a3966d006906596a"},
*
* //{ capability: null
* // if the capability id is null the user level of access for this database is the
* same of the team
* //name: {@type: "xsd:string", @value: "Collab002"}
* //role: "Role/dataReader"
* // scope: "UserDatabase/acfcc2db02b83792sssb15239ccdf586fc5b176846ffe4878b1aea6a36c8f"
* //user: "User/auth0%7C61790e11a3966d006906596a"}]
*/
AccessControl.prototype.getDatabaseRolesOfUser = function (userId, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!userId) {
errorMessage = 'Please provide a user id';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'GET',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const user = UTILS.removeDocType(userId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/users/${user}/databases`, CONST.GET);
};
/**
* -- TerminusX API --
* Create a user's a role for a resource (organization/database)
* @param {string} userId - The user's id.
* @param {string} scope - The resource name/id.
* @param {string} role - The user role to be assigned.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* const dbId = "UserDatabase/acfcc2db02b83792sssb15239ccdf586fc5b176846ffe4878b1aea6a36c8f"
* accessControl.assignUserRole('User/auth0%7C61790e11a3966d006906596a',dbId,
* "Role/collaborator").then(result=>{
* console.log(result)
*
* })
*/
AccessControl.prototype.createUserRole = function (userId, scope, role, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!userId) {
errorMessage = 'Please provide a user id';
} else if (!scope) {
errorMessage = 'Please provide a scope';
} else if (!role) {
errorMessage = 'Please provide a role';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'POST',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const user = UTILS.removeDocType(userId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/users/${user}/capabilities`, CONST.POST, {
scope,
role,
});
};
/**
* -- TerminusX API --
* Update user's a role for a resource (organization/database), (this api works only in terminusX)
* @param {string} userId - The user's id.
* @param {string} capabilityId - The capability id.
* @param {string} scope - The resource name/id.
* @param {string} role - The user role to be updated.
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* const dbId = "UserDatabase/acfcc2db02b83792sssb15239ccdf586fc5b176846ffe4878b1aea6a36c8f"
* const capId= "Capability/b395e8523d509dec6b33aefc9baed3b2e2bfadbd4c79d4ff9b20dce2b14e2edc"
* accessControl.updateUserRole('User/auth0%7C61790e11a3966d006906596a',capId,dbId,
* "Role/dataUpdater").then(result=>{
* console.log(result)
*
* })
*/
AccessControl.prototype.updateUserRole = function (userId, capabilityId, scope, role, orgName) {
let errorMessage;
if (!orgName && !this.defaultOrganization) {
errorMessage = 'Please provide a organization name';
} else if (!userId) {
errorMessage = 'Please provide a user id';
} else if (!capabilityId) {
errorMessage = 'Please provide a capabilityId';
} else if (!scope) {
errorMessage = 'Please provide a scope';
} else if (!role) {
errorMessage = 'Please provide a role';
}
if (errorMessage) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'PUT',
errorMessage,
),
),
);
}
const org = orgName || this.defaultOrganization;
const user = UTILS.removeDocType(userId);
const capHash = UTILS.removeDocType(capabilityId);
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/users/${user}/capabilities/${capHash}`, CONST.PUT, {
scope,
role,
});
};
/**
* -- TerminusX API --
* Get all the access request list for a specify organization
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.accessRequestsList().then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.accessRequestsList = function (orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'GET',
'Please provide a organization name',
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/access_requests`, CONST.GET);
};
/**
* -- TerminusX API --
* Get all the access request list for a specify organization
* @param {string} [email] - the user email.
* @param {string} [affiliation] - the user affiliation, company, university etc..
* @param {string} [note] - the message for the team admin
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.sendAccessRequest("[email protected]",
* "my_company",
* "please add me to your team"
* ).then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.sendAccessRequest = function (email, affiliation, note, orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'POST',
'Please provide a organization name',
),
),
);
}
const payload = { email, affiliation, note };
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/access_requests`, CONST.POST, payload);
};
/**
* -- TerminusX API --
* Delete an access request to join your team, only an admin user can delete it
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.deleteAccessRequest("djjdshhsuuwewueueuiHYHYYW.......").then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.deleteAccessRequest = function (acceId, orgName) {
if (!orgName && !this.defaultOrganization) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
'POST',
'Please provide a organization name',
),
),
);
}
const org = orgName || this.defaultOrganization;
return this.dispatch(`${this.baseURL}/organizations/${UTILS.encodeURISegment(org)}/access_requests/${acceId}`, CONST.DELETE);
};
/**
* -- TerminusX API --
* Get the userinfo teams ownership and subscription
* @param {string} [orgName] - The organization name.
* @return {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* accessControl.getUserInfo().then(result=>{
* console.log(result)
* })
*
*/
AccessControl.prototype.getUserInfo = function (userName) {
const userNameUrl = userName || 'info';
return this.dispatch(`${this.baseURL}/users/${UTILS.encodeURISegment(userNameUrl)}`, CONST.GET);
};
module.exports = AccessControl;