@cocreate/users 1.4.35 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ ## [1.5.2](https://github.com/CoCreate-app/CoCreate-users/compare/v1.5.1...v1.5.2) (2022-05-03)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * removed localstorage.setItem for admin_ui and builder_ui ([350f289](https://github.com/CoCreate-app/CoCreate-users/commit/350f289f731bf21f535d892b276708044eb662a3))
7
+ * user permission typo contained duplicate delete switch case. renamed one to update ([66f6fc7](https://github.com/CoCreate-app/CoCreate-users/commit/66f6fc72ce3b60facaaa41112246de22358062dd))
8
+
9
+ ## [1.5.1](https://github.com/CoCreate-app/CoCreate-users/compare/v1.5.0...v1.5.1) (2022-03-06)
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * update param roomInfo to socketInfo ([6784138](https://github.com/CoCreate-app/CoCreate-users/commit/6784138e71feb00866cb8159b1d3c95136b5f00d))
15
+
16
+ # [1.5.0](https://github.com/CoCreate-app/CoCreate-users/compare/v1.4.35...v1.5.0) (2022-03-03)
17
+
18
+
19
+ ### Features
20
+
21
+ * manage server and client scripts ([06a8797](https://github.com/CoCreate-app/CoCreate-users/commit/06a87978b99879a83a303dcbc078ebfb27191375))
22
+
1
23
  ## [1.4.35](https://github.com/CoCreate-app/CoCreate-users/compare/v1.4.34...v1.4.35) (2022-02-24)
2
24
 
3
25
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cocreate/users",
3
- "version": "1.4.35",
3
+ "version": "1.5.2",
4
4
  "description": "A simple users component in vanilla javascript. Easily configured using HTML5 attributes and/or JavaScript API.",
5
5
  "keywords": [
6
6
  "users",
@@ -65,6 +65,7 @@
65
65
  "@cocreate/crud-client": "^1.4.47",
66
66
  "@cocreate/docs": "^1.2.69",
67
67
  "@cocreate/elements": "^1.6.11",
68
- "@cocreate/render": "^1.5.7"
68
+ "@cocreate/render": "^1.5.7",
69
+ "mongodb": "^4.4.0"
69
70
  }
70
71
  }
package/src/client.js ADDED
@@ -0,0 +1,353 @@
1
+ /*globals CustomEvent, btoa*/
2
+ import crud from '@cocreate/crud-client';
3
+ // import input from '@cocreate/elements';
4
+ import action from '@cocreate/actions';
5
+ import render from '@cocreate/render';
6
+
7
+ const CONST_PERMISSION_CLASS = 'checkPermission';
8
+
9
+ const CoCreateUser = {
10
+ // masterDB: '5ae0cfac6fb8c4e656fdaf92', // '5ae0cfac6fb8c4e656fdaf92' /** masterDB **/,
11
+ init: function() {
12
+ this.updatedCurrentOrg = false;
13
+ this.initSocket();
14
+ this.initChangeOrg();
15
+ this.checkSession();
16
+ this.createUserSocket();
17
+ },
18
+
19
+ createUserSocket: function() {
20
+ var user_id = window.localStorage.getItem('user_id');
21
+ if (user_id) {
22
+ crud.socket.create({
23
+ namespace: 'users',
24
+ room: user_id,
25
+ host: window.config.host
26
+ })
27
+ }
28
+ },
29
+
30
+ initSocket: function() {
31
+ const self = this;
32
+ crud.listen('createUser', function(data) {
33
+ self.setDocumentId('users', data.document_id);
34
+ document.dispatchEvent(new CustomEvent('createUser', {
35
+ detail: data
36
+ }));
37
+ });
38
+ crud.listen('createUserNew', function(data) {
39
+ document.dispatchEvent(new CustomEvent('createUserNew', {
40
+ detail: data
41
+ }));
42
+ });
43
+ crud.listen('fetchedUser', this.checkPermissions);
44
+ crud.listen('login', (instance) => self.loginResult(instance));
45
+ crud.listen('changedUserStatus', this.changedUserStatus);
46
+ crud.listen('usersCurrentOrg', (instance) => self.setCurrentOrg(instance));
47
+ },
48
+
49
+ requestLogin: function(btn) {
50
+ let form = btn.closest('form');
51
+ let collection = form.getAttribute('collection');
52
+ let loginData = {};
53
+
54
+ // const inputs = form.querySelectorAll('input, textarea');
55
+ const inputs = form.querySelectorAll('input[name="email"], input[name="password"], input[name="username"]');
56
+
57
+ inputs.forEach((input) => {
58
+ const name = input.getAttribute('name');
59
+ let value = input.value;
60
+ if (input.type == 'password') {
61
+ value = btoa(value);
62
+ }
63
+ collection = input.getAttribute('collection') || collection;
64
+
65
+ if (name) {
66
+ loginData[name] = value;
67
+ }
68
+ });
69
+
70
+ crud.send('login', {
71
+ "apiKey": window.config.apiKey,
72
+ "organization_id": window.config.organization_Id,
73
+ "collection": collection,
74
+ "loginData": loginData
75
+ });
76
+ },
77
+
78
+ loginResult: function(data) {
79
+ let { success, status, message, token } = data;
80
+
81
+ if (success) {
82
+ window.localStorage.setItem('organization_id', window.config.organization_Id);
83
+ window.localStorage.setItem("apiKey", window.config.apiKey);
84
+ window.localStorage.setItem("host", window.config.host);
85
+ window.localStorage.setItem('user_id', data['id']);
86
+ window.localStorage.setItem("token", token);
87
+ document.cookie = `token=${token};path=/`;
88
+ this.getCurrentOrg(data['id'], data['collection']);
89
+ message = "Succesful Login";
90
+ document.dispatchEvent(new CustomEvent('login', {
91
+ detail: {}
92
+ }));
93
+ }
94
+ else
95
+ message = "The email or password you entered is incorrect";
96
+
97
+ render.data({
98
+ selector: "[template_id='login']",
99
+ data: {
100
+ type: 'login',
101
+ status,
102
+ message,
103
+ success
104
+ }
105
+ });
106
+ },
107
+
108
+ getCurrentOrg: function(user_id, collection) {
109
+ crud.send('usersCurrentOrg', {
110
+ "apiKey": window.config.apiKey,
111
+ "organization_id": window.config.organization_Id,
112
+ "collection": collection || 'users',
113
+ "user_id": user_id,
114
+ });
115
+ },
116
+
117
+ setCurrentOrg: function(data) {
118
+ this.updatedCurrentOrg = true;
119
+ window.localStorage.setItem('apiKey', data['apiKey']);
120
+ window.localStorage.setItem('organization_id', data['current_org']);
121
+ window.localStorage.setItem('host', window.config.host);
122
+
123
+ // window.localStorage.setItem('adminUI_id', data['adminUI_id']);
124
+ // window.localStorage.setItem('builderUI_id', data['builderUI_id']);
125
+
126
+ document.dispatchEvent(new CustomEvent('logIn'));
127
+ },
128
+
129
+ logout: (btn) => {
130
+ self = this;
131
+ window.localStorage.clear();
132
+
133
+ let allCookies = document.cookie.split(';');
134
+
135
+ for (var i = 0; i < allCookies.length; i++)
136
+ document.cookie = allCookies[i] + "=;expires=" +
137
+ new Date(0).toUTCString();
138
+
139
+ // Todo: replace with Custom event system
140
+ document.dispatchEvent(new CustomEvent('logout'));
141
+ },
142
+
143
+ initChangeOrg: () => {
144
+ const user_id = window.localStorage.getItem('user_id');
145
+
146
+ if (!user_id) return;
147
+
148
+ let orgChangers = document.querySelectorAll('.org-changer');
149
+
150
+ for (let i = 0; i < orgChangers.length; i++) {
151
+ let orgChanger = orgChangers[i];
152
+
153
+ const collection = orgChanger.getAttribute('collection') ? orgChanger.getAttribute('collection') : 'module_activity';
154
+ const id = orgChanger.getAttribute('document_id');
155
+
156
+ if (collection == 'users' && id == user_id) {
157
+ orgChanger.addEventListener('selectedValue', function(e) {
158
+
159
+ setTimeout(function() {
160
+ getCurrentOrg(user_id);
161
+
162
+ var timer = setInterval(function() {
163
+ if (updatedCurrentOrg) {
164
+ window.location.reload();
165
+
166
+ clearInterval(timer);
167
+ }
168
+ }, 100);
169
+ }, 300);
170
+ });
171
+ }
172
+ }
173
+ },
174
+
175
+ checkSession: () => {
176
+ let user_id = window.localStorage.getItem('user_id');
177
+ let token = window.localStorage.getItem('token');
178
+ if (user_id && token) {
179
+ let redirectTag = document.querySelector('[session="true"]');
180
+
181
+ if (redirectTag) {
182
+ let redirectLink = redirectTag.getAttribute('href');
183
+ if (redirectLink) {
184
+ document.location.href = redirectLink;
185
+ }
186
+ }
187
+ }
188
+ else {
189
+ let redirectTag = document.querySelector('[session="false"]');
190
+
191
+ if (redirectTag) {
192
+ let redirectLink = redirectTag.getAttribute('href');
193
+ if (redirectLink) {
194
+ window.localStorage.clear();
195
+ // this.deleteCookie();
196
+ document.location.href = redirectLink;
197
+ }
198
+ }
199
+ }
200
+ },
201
+
202
+ checkPermissions: (data) => {
203
+ const tags = document.querySelectorAll('.' + CONST_PERMISSION_CLASS);
204
+ tags.forEach((tag) => {
205
+ let module_id = tag.getAttribute('document_id') ? tag.getAttribute('document_id') : tag.getAttribute('pass-document_id');
206
+ let data_permission = tag.getAttribute('data-permission');
207
+ let userPermission = data['permission-' + module_id];
208
+
209
+ if (userPermission.indexOf(data_permission) == -1) {
210
+ switch (data_permission) {
211
+ case 'create':
212
+ tag.style.display = 'none';
213
+ break;
214
+ case 'read':
215
+ tag.style.display = 'none';
216
+ break;
217
+ case 'update':
218
+ tag.style.display = 'none';
219
+ break;
220
+ case 'delete':
221
+ tag.readOnly = true;
222
+ break;
223
+ default:
224
+ // code
225
+ }
226
+ }
227
+ else {
228
+ switch (data_permission) {
229
+
230
+ // code
231
+ }
232
+ }
233
+ });
234
+ },
235
+
236
+ changedUserStatus: (data) => {
237
+ if (!data.user_id) {
238
+ return;
239
+ }
240
+ let statusEls = document.querySelectorAll(`[user-status][document_id='${data['user_id']}']`);
241
+
242
+ statusEls.forEach((el) => {
243
+ el.setAttribute('user-status', data['status']);
244
+ });
245
+ },
246
+
247
+ setDocumentId: function(collection, id) {
248
+ let orgIdElements = document.querySelectorAll(`[collection='${collection}']`);
249
+ if (orgIdElements && orgIdElements.length > 0) {
250
+ orgIdElements.forEach((el) => {
251
+ if (!el.getAttribute('document_id')) {
252
+ el.setAttribute('document_id', id);
253
+ }
254
+ if (el.getAttribute('name') == "_id") {
255
+ el.value = id;
256
+ }
257
+ });
258
+ }
259
+ },
260
+
261
+ createUserNew: function(btn) {
262
+ let form = btn.closest("form");
263
+ if (!form) return;
264
+ let newOrg_id = form.querySelector("input[collection='organizations'][name='_id']");
265
+ let user_id = form.querySelector("input[collection='users'][name='_id']");
266
+
267
+ const room = config.organization_Id;
268
+
269
+ crud.send('createUserNew', {
270
+ apiKey: config.apiKey,
271
+ organization_id: config.organization_Id,
272
+ collection: 'users',
273
+ newOrg_id: org_id,
274
+ user_id: user_id,
275
+ }, room);
276
+
277
+ },
278
+
279
+ createUser: function(btn) {
280
+ let form = btn.closest("form");
281
+ if (!form) return;
282
+ let org_id = "";
283
+ let elements = form.querySelectorAll("[collection='users'][name]");
284
+ let orgIdElement = form.querySelector("input[collection='organizations'][name='_id']");
285
+
286
+ if (orgIdElement) {
287
+ org_id = orgIdElement.value;
288
+ }
289
+ let data = {};
290
+ //. get form data
291
+ elements.forEach(el => {
292
+ let name = el.getAttribute('name');
293
+ let value = el.getValue(el) || el.getAttribute('value');
294
+ if (!name || !value) return;
295
+
296
+ if (el.getAttribute('data-type') == 'array') {
297
+ value = [value];
298
+ }
299
+ data[name] = value;
300
+ });
301
+ data['current_org'] = org_id;
302
+ data['connected_orgs'] = [org_id];
303
+ data['organization_id'] = config.organization_Id;
304
+
305
+ const room = config.organization_Id;
306
+
307
+ crud.send('createUser', {
308
+ apiKey: config.apiKey,
309
+ organization_id: config.organization_Id,
310
+ // mdb: this.masterDB,
311
+ collection: 'users',
312
+ data: data,
313
+ orgDB: org_id
314
+ }, room);
315
+ },
316
+ };
317
+
318
+
319
+ action.init({
320
+ name: "createUserNew",
321
+ endEvent: "createUserNew",
322
+ callback: (btn, data) => {
323
+ CoCreateUser.createUser(btn);
324
+ },
325
+ });
326
+
327
+ action.init({
328
+ name: "createUser",
329
+ endEvent: "createUser",
330
+ callback: (btn, data) => {
331
+ CoCreateUser.createUser(btn);
332
+ },
333
+ });
334
+
335
+ action.init({
336
+ name: "login",
337
+ endEvent: "login",
338
+ callback: (btn, data) => {
339
+ CoCreateUser.requestLogin(btn, data);
340
+ },
341
+ });
342
+
343
+ action.init({
344
+ name: "logout",
345
+ endEvent: "logout",
346
+ callback: (btn, data) => {
347
+ CoCreateUser.logout(btn, data);
348
+ },
349
+ });
350
+
351
+ CoCreateUser.init();
352
+
353
+ export default CoCreateUser;
package/src/index.js CHANGED
@@ -1,353 +1,14 @@
1
- /*globals CustomEvent, btoa*/
2
- import crud from '@cocreate/crud-client';
3
- // import input from '@cocreate/elements';
4
- import action from '@cocreate/actions';
5
- import render from '@cocreate/render';
6
-
7
- const CONST_PERMISSION_CLASS = 'checkPermission';
8
-
9
- const CoCreateUser = {
10
- // masterDB: '5ae0cfac6fb8c4e656fdaf92', // '5ae0cfac6fb8c4e656fdaf92' /** masterDB **/,
11
- init: function() {
12
- this.updatedCurrentOrg = false;
13
- this.initSocket();
14
- this.initChangeOrg();
15
- this.checkSession();
16
- this.createUserSocket();
17
- },
18
-
19
- createUserSocket: function() {
20
- var user_id = window.localStorage.getItem('user_id');
21
- if (user_id) {
22
- crud.socket.create({
23
- namespace: 'users',
24
- room: user_id,
25
- host: window.config.host
26
- })
27
- }
28
- },
29
-
30
- initSocket: function() {
31
- const self = this;
32
- crud.listen('createUser', function(data) {
33
- self.setDocumentId('users', data.document_id);
34
- document.dispatchEvent(new CustomEvent('createUser', {
35
- detail: data
36
- }));
37
- });
38
- crud.listen('createUserNew', function(data) {
39
- document.dispatchEvent(new CustomEvent('createUserNew', {
40
- detail: data
41
- }));
42
- });
43
- crud.listen('fetchedUser', this.checkPermissions);
44
- crud.listen('login', (instance) => self.loginResult(instance));
45
- crud.listen('changedUserStatus', this.changedUserStatus);
46
- crud.listen('usersCurrentOrg', (instance) => self.setCurrentOrg(instance));
47
- },
48
-
49
- requestLogin: function(btn) {
50
- let form = btn.closest('form');
51
- let collection = form.getAttribute('collection');
52
- let loginData = {};
53
-
54
- // const inputs = form.querySelectorAll('input, textarea');
55
- const inputs = form.querySelectorAll('input[name="email"], input[name="password"], input[name="username"]');
56
-
57
- inputs.forEach((input) => {
58
- const name = input.getAttribute('name');
59
- let value = input.value;
60
- if (input.type == 'password') {
61
- value = btoa(value);
62
- }
63
- collection = input.getAttribute('collection') || collection;
64
-
65
- if (name) {
66
- loginData[name] = value;
67
- }
68
- });
69
-
70
- crud.send('login', {
71
- "apiKey": window.config.apiKey,
72
- "organization_id": window.config.organization_Id,
73
- "collection": collection,
74
- "loginData": loginData
75
- });
76
- },
77
-
78
- loginResult: function(data) {
79
- let { success, status, message, token } = data;
80
-
81
- if (success) {
82
- window.localStorage.setItem('organization_id', window.config.organization_Id);
83
- window.localStorage.setItem("apiKey", window.config.apiKey);
84
- window.localStorage.setItem("host", window.config.host);
85
- window.localStorage.setItem('user_id', data['id']);
86
- window.localStorage.setItem("token", token);
87
- document.cookie = `token=${token};path=/`;
88
- this.getCurrentOrg(data['id'], data['collection']);
89
- message = "Succesful Login";
90
- document.dispatchEvent(new CustomEvent('login', {
91
- detail: {}
92
- }));
93
- }
94
- else
95
- message = "The email or password you entered is incorrect";
96
-
97
- render.data({
98
- selector: "[template_id='login']",
99
- data: {
100
- type: 'login',
101
- status,
102
- message,
103
- success
104
- }
105
- });
106
- },
107
-
108
- getCurrentOrg: function(user_id, collection) {
109
- crud.send('usersCurrentOrg', {
110
- "apiKey": window.config.apiKey,
111
- "organization_id": window.config.organization_Id,
112
- "collection": collection || 'users',
113
- "user_id": user_id,
114
- });
115
- },
116
-
117
- setCurrentOrg: function(data) {
118
- this.updatedCurrentOrg = true;
119
- window.localStorage.setItem('apiKey', data['apiKey']);
120
- window.localStorage.setItem('organization_id', data['current_org']);
121
- window.localStorage.setItem('host', window.config.host);
122
-
123
- window.localStorage.setItem('adminUI_id', data['adminUI_id']);
124
- window.localStorage.setItem('builderUI_id', data['builderUI_id']);
125
-
126
- document.dispatchEvent(new CustomEvent('logIn'));
127
- },
128
-
129
- logout: (btn) => {
130
- self = this;
131
- window.localStorage.clear();
132
-
133
- let allCookies = document.cookie.split(';');
134
-
135
- for (var i = 0; i < allCookies.length; i++)
136
- document.cookie = allCookies[i] + "=;expires=" +
137
- new Date(0).toUTCString();
138
-
139
- // Todo: replace with Custom event system
140
- document.dispatchEvent(new CustomEvent('logout'));
141
- },
142
-
143
- initChangeOrg: () => {
144
- const user_id = window.localStorage.getItem('user_id');
145
-
146
- if (!user_id) return;
147
-
148
- let orgChangers = document.querySelectorAll('.org-changer');
149
-
150
- for (let i = 0; i < orgChangers.length; i++) {
151
- let orgChanger = orgChangers[i];
152
-
153
- const collection = orgChanger.getAttribute('collection') ? orgChanger.getAttribute('collection') : 'module_activity';
154
- const id = orgChanger.getAttribute('document_id');
155
-
156
- if (collection == 'users' && id == user_id) {
157
- orgChanger.addEventListener('selectedValue', function(e) {
158
-
159
- setTimeout(function() {
160
- getCurrentOrg(user_id);
161
-
162
- var timer = setInterval(function() {
163
- if (updatedCurrentOrg) {
164
- window.location.reload();
165
-
166
- clearInterval(timer);
167
- }
168
- }, 100);
169
- }, 300);
170
- });
171
- }
172
- }
173
- },
174
-
175
- checkSession: () => {
176
- let user_id = window.localStorage.getItem('user_id');
177
- let token = window.localStorage.getItem('token');
178
- if (user_id && token) {
179
- let redirectTag = document.querySelector('[session="true"]');
180
-
181
- if (redirectTag) {
182
- let redirectLink = redirectTag.getAttribute('href');
183
- if (redirectLink) {
184
- document.location.href = redirectLink;
185
- }
186
- }
187
- }
188
- else {
189
- let redirectTag = document.querySelector('[session="false"]');
190
-
191
- if (redirectTag) {
192
- let redirectLink = redirectTag.getAttribute('href');
193
- if (redirectLink) {
194
- window.localStorage.clear();
195
- // this.deleteCookie();
196
- document.location.href = redirectLink;
197
- }
198
- }
199
- }
200
- },
201
-
202
- checkPermissions: (data) => {
203
- const tags = document.querySelectorAll('.' + CONST_PERMISSION_CLASS);
204
- tags.forEach((tag) => {
205
- let module_id = tag.getAttribute('document_id') ? tag.getAttribute('document_id') : tag.getAttribute('pass-document_id');
206
- let data_permission = tag.getAttribute('data-permission');
207
- let userPermission = data['permission-' + module_id];
208
-
209
- if (userPermission.indexOf(data_permission) == -1) {
210
- switch (data_permission) {
211
- case 'create':
212
- tag.style.display = 'none';
213
- break;
214
- case 'read':
215
- tag.style.display = 'none';
216
- break;
217
- case 'delete':
218
- tag.style.display = 'none';
219
- break;
220
- case 'delete':
221
- tag.readOnly = true;
222
- break;
223
- default:
224
- // code
225
- }
226
- }
227
- else {
228
- switch (data_permission) {
229
-
230
- // code
231
- }
232
- }
233
- });
234
- },
235
-
236
- changedUserStatus: (data) => {
237
- if (!data.user_id) {
238
- return;
239
- }
240
- let statusEls = document.querySelectorAll(`[user-status][document_id='${data['user_id']}']`);
241
-
242
- statusEls.forEach((el) => {
243
- el.setAttribute('user-status', data['status']);
244
- });
245
- },
246
-
247
- setDocumentId: function(collection, id) {
248
- let orgIdElements = document.querySelectorAll(`[collection='${collection}']`);
249
- if (orgIdElements && orgIdElements.length > 0) {
250
- orgIdElements.forEach((el) => {
251
- if (!el.getAttribute('document_id')) {
252
- el.setAttribute('document_id', id);
253
- }
254
- if (el.getAttribute('name') == "_id") {
255
- el.value = id;
256
- }
257
- });
258
- }
259
- },
260
-
261
- createUserNew: function(btn) {
262
- let form = btn.closest("form");
263
- if (!form) return;
264
- let newOrg_id = form.querySelector("input[collection='organizations'][name='_id']");
265
- let user_id = form.querySelector("input[collection='users'][name='_id']");
266
-
267
- const room = config.organization_Id;
268
-
269
- crud.send('createUserNew', {
270
- apiKey: config.apiKey,
271
- organization_id: config.organization_Id,
272
- collection: 'users',
273
- newOrg_id: org_id,
274
- user_id: user_id,
275
- }, room);
276
-
277
- },
278
-
279
- createUser: function(btn) {
280
- let form = btn.closest("form");
281
- if (!form) return;
282
- let org_id = "";
283
- let elements = form.querySelectorAll("[collection='users'][name]");
284
- let orgIdElement = form.querySelector("input[collection='organizations'][name='_id']");
285
-
286
- if (orgIdElement) {
287
- org_id = orgIdElement.value;
288
- }
289
- let data = {};
290
- //. get form data
291
- elements.forEach(el => {
292
- let name = el.getAttribute('name');
293
- let value = el.getValue(el) || el.getAttribute('value');
294
- if (!name || !value) return;
295
-
296
- if (el.getAttribute('data-type') == 'array') {
297
- value = [value];
298
- }
299
- data[name] = value;
300
- });
301
- data['current_org'] = org_id;
302
- data['connected_orgs'] = [org_id];
303
- data['organization_id'] = config.organization_Id;
304
-
305
- const room = config.organization_Id;
306
-
307
- crud.send('createUser', {
308
- apiKey: config.apiKey,
309
- organization_id: config.organization_Id,
310
- // mdb: this.masterDB,
311
- collection: 'users',
312
- data: data,
313
- orgDB: org_id
314
- }, room);
315
- },
316
- };
317
-
318
-
319
- action.init({
320
- name: "createUserNew",
321
- endEvent: "createUserNew",
322
- callback: (btn, data) => {
323
- CoCreateUser.createUser(btn);
324
- },
325
- });
326
-
327
- action.init({
328
- name: "createUser",
329
- endEvent: "createUser",
330
- callback: (btn, data) => {
331
- CoCreateUser.createUser(btn);
332
- },
333
- });
334
-
335
- action.init({
336
- name: "login",
337
- endEvent: "login",
338
- callback: (btn, data) => {
339
- CoCreateUser.requestLogin(btn, data);
340
- },
341
- });
342
-
343
- action.init({
344
- name: "logout",
345
- endEvent: "logout",
346
- callback: (btn, data) => {
347
- CoCreateUser.logout(btn, data);
348
- },
349
- });
350
-
351
- CoCreateUser.init();
352
-
353
- export default CoCreateUser;
1
+ (function (root, factory) {
2
+ if (typeof define === 'function' && define.amd) {
3
+ define(["./client"], function(CoCreateUsers) {
4
+ return factory(CoCreateUsers)
5
+ });
6
+ } else if (typeof module === 'object' && module.exports) {
7
+ const CoCreateUsers = require("./server.js")
8
+ module.exports = factory(CoCreateUsers);
9
+ } else {
10
+ root.returnExports = factory(root["./client.js"]);
11
+ }
12
+ }(typeof self !== 'undefined' ? self : this, function (CoCreateUsers) {
13
+ return CoCreateUsers;
14
+ }));
package/src/server.js ADDED
@@ -0,0 +1,265 @@
1
+ const {ObjectID} = require("mongodb");
2
+
3
+ class CoCreateUser {
4
+ constructor(wsManager, dbClient) {
5
+ this.wsManager = wsManager
6
+ this.dbClient = dbClient
7
+ this.init()
8
+ }
9
+
10
+ init() {
11
+ if (this.wsManager) {
12
+ this.wsManager.on('createUserNew', (socket, data, socketInfo) => this.createUserNew(socket, data));
13
+ this.wsManager.on('createUser', (socket, data, socketInfo) => this.createUser(socket, data));
14
+ this.wsManager.on('login', (socket, data, socketInfo) => this.login(socket, data, socketInfo))
15
+ this.wsManager.on('usersCurrentOrg', (socket, data, socketInfo) => this.usersCurrentOrg(socket, data, socketInfo))
16
+ this.wsManager.on('fetchUser', (socket, data, socketInfo) => this.fetchUser(socket, data, socketInfo))
17
+ this.wsManager.on('userStatus', (socket, data, socketInfo) => this.setUserStatus(socket, data, socketInfo))
18
+ }
19
+ }
20
+
21
+
22
+ async createUserNew(socket, data) {
23
+ const self = this;
24
+ if(!data) return;
25
+ const newOrg_id = data.newOrg_id;
26
+ if (newOrg_id != data.organization_id) {
27
+ try{
28
+ const db = this.dbClient.db(req_data['organization_id']);
29
+ const collection = db.collection(req_data["collection"]);
30
+ const query = {
31
+ "_id": new ObjectID(data["user_id"])
32
+ };
33
+
34
+ collection.find(query).toArray(function(error, result) {
35
+ if(!error && result){
36
+ const newOrgDb = self.dbClient.db(newOrg_id).collection(data['collection']);
37
+ // Create new user in config db users collection
38
+ newOrgDb.insertOne({...result.ops[0], organization_id : newOrg_id}, function(error, result) {
39
+ if(!error && result){
40
+ const response = { ...data, document_id: result.ops[0]._id, data: result.ops[0]}
41
+ self.wsManager.send(socket, 'createUserNew', response, data['organization_id']);
42
+ }
43
+ });
44
+ }
45
+ });
46
+ }catch(error){
47
+ console.log('createDocument error', error);
48
+ }
49
+ }
50
+ }
51
+
52
+ async createUser(socket, data) {
53
+ const self = this;
54
+ if(!data.data) return;
55
+
56
+ try{
57
+ const collection = this.dbClient.db(data['organization_id']).collection(data['collection']);
58
+ // Create new user in config db users collection
59
+ collection.insertOne(data.data, function(error, result) {
60
+ if(!error && result){
61
+ const orgDB = data.orgDB;
62
+ // if new orgDb Create new user in new org db users collection
63
+ if (orgDB != data.organization_id) {
64
+ if (orgDB) {
65
+ const anotherCollection = self.dbClient.db(orgDB).collection(data['collection']);
66
+ anotherCollection.insertOne({...result.ops[0], organization_id : orgDB});
67
+ }
68
+ }
69
+ const response = { ...data, document_id: result.ops[0]._id, data: result.ops[0]}
70
+ self.wsManager.send(socket, 'createUser', response, data['organization_id']);
71
+ }
72
+ });
73
+ }catch(error){
74
+ console.log('createDocument error', error);
75
+ }
76
+ }
77
+
78
+
79
+ /**
80
+ data = {
81
+ namespace: string,
82
+ collection: string,
83
+ loginData: object,
84
+ eId: string,
85
+ form_id: string,
86
+
87
+ apiKey: string,
88
+ organization_id: string
89
+ }
90
+ **/
91
+ async login(socket, req_data) {
92
+ const self = this;
93
+ try {
94
+ const {organization_id} = req_data
95
+ const selectedDB = organization_id;
96
+ const collection = self.dbClient.db(selectedDB).collection(req_data["collection"]);
97
+ const query = new Object();
98
+
99
+ // query['connected_orgs'] = data['organization_id'];
100
+
101
+ for (var key in req_data['loginData']) {
102
+ query[key] = req_data['loginData'][key];
103
+ }
104
+
105
+ collection.find(query).toArray(async function(error, result) {
106
+ let response = {
107
+ eId: req_data['eId'],
108
+ uid: req_data['uid'],
109
+ form_id: req_data['form_id'],
110
+ success: false,
111
+ message: "Login failed",
112
+ status: "failed"
113
+ }
114
+ if (!error && result && result.length > 0) {
115
+ let token = null;
116
+ if (self.wsManager.authInstance) {
117
+ token = await self.wsManager.authInstance.generateToken({user_id: result[0]['_id']});
118
+ }
119
+
120
+ response = { ...response,
121
+ success: true,
122
+ id: result[0]['_id'],
123
+ // collection: collection,
124
+ document_id: result[0]['_id'],
125
+ current_org: result[0]['current_org'],
126
+ message: "Login successful",
127
+ status: "success",
128
+ token
129
+ };
130
+ }
131
+ console.log('before socket', response);
132
+ self.wsManager.send(socket, 'login', response, req_data['organization_id'])
133
+ console.log('success socket', req_data['organization_id']);
134
+ });
135
+ } catch (error) {
136
+ console.log('login failed', error);
137
+ }
138
+ }
139
+
140
+ /**
141
+ data = {
142
+ namespace: string,
143
+ collection: string,
144
+ user_id: string,
145
+ href: string
146
+ }
147
+ **/
148
+ async usersCurrentOrg(socket, req_data) {
149
+ try {
150
+ const self = this;
151
+ const {organization_id, db} = req_data
152
+ const selectedDB = db || organization_id;
153
+ const collection = this.dbClient.db(selectedDB).collection(req_data["collection"]);
154
+
155
+ let query = new Object();
156
+
157
+ query['_id'] = new ObjectID(req_data['user_id']);
158
+
159
+ collection.find(query).toArray(function(error, result) {
160
+
161
+ if (!error && result && result.length > 0) {
162
+
163
+ if (result.length > 0) {
164
+ let org_id = result[0]['current_org'];
165
+ const orgCollection = self.dbClient.db(selectedDB).collection('organizations');
166
+
167
+ orgCollection.find({"_id": new ObjectID(org_id),}).toArray(function(err, res) {
168
+ if (!err && res && res.length > 0) {
169
+ self.wsManager.send(socket, 'usersCurrentOrg', {
170
+ id: req_data['id'],
171
+ uid: req_data['uid'],
172
+ success: true,
173
+ user_id: result[0]['_id'],
174
+ current_org: result[0]['current_org'],
175
+ apiKey: res[0]['apiKey'],
176
+ adminUI_id: res[0]['adminUI_id'],
177
+ builderUI_id: res[0]['builderUI_id'],
178
+ href: req_data['href']
179
+ }, req_data['organization_id'])
180
+ }
181
+ });
182
+ }
183
+ } else {
184
+ // socket.emit('loginResult', {
185
+ // form_id: data['form_id'],
186
+ // success: false
187
+ // });
188
+ }
189
+ });
190
+ } catch (error) {
191
+
192
+ }
193
+ }
194
+
195
+ /**
196
+ data = {
197
+ namespace: string,
198
+ collection: string,
199
+ user_id: object,
200
+
201
+ apiKey: string,
202
+ organization_id: string
203
+ }
204
+ **/
205
+ async fetchUser(socket, req_data) {
206
+ const self = this;
207
+
208
+ try {
209
+ const {organization_id, db} = req_data
210
+ const selectedDB = db || organization_id;
211
+ const collection = self.dbClient.db(selectedDB).collection(req_data['collection']);
212
+ const user_id = req_data['user_id'];
213
+ const query = {
214
+ "_id": new ObjectID(user_id),
215
+ }
216
+
217
+ collection.findOne(query, function(error, result) {
218
+ if (!error) {
219
+ self.wsManager.send(socket, 'fetchedUser', result, req_data['organization_id']);
220
+ }
221
+ })
222
+ } catch (error) {
223
+ console.log('fetchUser error')
224
+ }
225
+ }
226
+
227
+ /**
228
+ * status: 'on/off/idle'
229
+ */
230
+ async setUserStatus(socket, req_data, socketInfo) {
231
+ const self = this;
232
+ const {info, status} = req_data;
233
+
234
+ const items = info.split('/');
235
+
236
+ if (items[0] !== 'users') {
237
+ return;
238
+ }
239
+
240
+ if (!items[1]) return;
241
+
242
+ try {
243
+ const {organization_id, db} = req_data
244
+ const selectedDB = db || organization_id;
245
+ const collection = self.dbClient.db(selectedDB).collection('users');
246
+ const user_id = items[1];
247
+ const query = {
248
+ "_id": new ObjectID(user_id),
249
+ }
250
+ collection.update(query, {$set: {status: status}}, function(err, res) {
251
+ if (!err) {
252
+ self.wsManager.broadcast(socket, '', null, 'changedUserStatus',
253
+ {
254
+ user_id,
255
+ status
256
+ })
257
+ }
258
+ })
259
+ } catch (error) {
260
+ console.log('fetchUser error')
261
+ }
262
+ }
263
+ }
264
+
265
+ module.exports = CoCreateUser;