-
Notifications
You must be signed in to change notification settings - Fork 150
/
resolvers.ts
1294 lines (1146 loc) · 41.6 KB
/
resolvers.ts
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
989
990
991
992
993
994
995
996
997
998
999
1000
import * as R from 'ramda';
import { ResolverFn } from '../';
import { logger } from '../../loggers/logger';
import { query, isPatchEmpty, knex } from '../../util/db';
import { Helpers as projectHelpers } from '../project/helpers';
import { Helpers} from './helpers';
import { Sql } from './sql';
import { arrayDiff } from '../../util/func';
import { Helpers as openshiftHelpers } from '../openshift/helpers';
import { Helpers as notificationHelpers } from '../notification/helpers';
import { Helpers as groupHelpers } from '../group/helpers';
import validator from 'validator';
const isValidName = value => {
if (validator.matches(value, /[^0-9a-z-]/)) {
throw new Error(
'Only lowercase characters, numbers and dashes allowed for name!'
);
}
if (validator.matches(value, /--/)) {
throw new Error('Multiple consecutive dashes are not allowed for name!');
}
}
export const addOrganization: ResolverFn = async (
args,
{ input },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
// check if the name is valid
isValidName(input.name)
try {
await hasPermission('organization', 'add');
const org = await query(sqlClientPool, Sql.selectOrganizationByName(input.name));
// if no organization found, create it
if (R.length(org) == 0) {
const { insertId } = await query(sqlClientPool, Sql.insertOrganization(input));
const rows = await query(sqlClientPool, Sql.selectOrganization(insertId));
userActivityLogger(`User added an organization ${R.prop(0, rows).name}`, {
project: '',
organization: input.organization,
event: 'api:addOrganization',
payload: {
data: {
input
}
}
});
return R.prop(0, rows);
} else {
throw new Error(`There was an error creating the organization, ${input.name} already exists`);
}
} catch (err) {
throw new Error(`There was an error creating the organization ${input.name} ${err}`);
}
};
export const addDeployTargetToOrganization: ResolverFn = async (
args,
{ input },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
await hasPermission('organization', 'add');
const org = await query(sqlClientPool, Sql.selectOrganization(input.organization));
if (R.length(org) == 0) {
throw new Error(
`Organization doesn't exist`
);
}
try {
await openshiftHelpers(sqlClientPool).getOpenshiftByOpenshiftInput({id: input.deployTarget})
} catch (err) {
throw new Error(`There was an error adding the deployTarget: ${err}`);
}
const result = await query(sqlClientPool, Sql.selectDeployTargetsByOrganizationAndDeployTarget(input.organization, input.deployTarget))
if (R.length(result) >= 1) {
throw new Error(
`Already added to organization`
);
}
try {
await query(sqlClientPool, Sql.addDeployTarget({dtid: input.deployTarget, orgid: input.organization}));
} catch (err) {
throw new Error(`There was an error adding the deployTarget: ${err}`);
}
userActivityLogger(`User added a deploytarget to organization ${R.prop(0, org).name}`, {
project: '',
organization: input.organization,
event: 'api:addDeployTargetToOrganization',
payload: {
data: {
input
}
}
});
return org[0];
};
export const removeDeployTargetFromOrganization: ResolverFn = async (
args,
{ input },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
await hasPermission('organization', 'add');
const org = await query(sqlClientPool, Sql.selectOrganization(input.organization));
if (R.length(org) == 0) {
throw new Error(
`Organization doesn't exist`
);
}
try {
await query(sqlClientPool, Sql.removeDeployTarget(input.organization, input.deployTarget));
} catch (err) {
throw new Error(`There was an error removing the deployTarget: ${err}`);
}
userActivityLogger(`User removed a deploytarget from organization ${R.prop(0, org).name}`, {
project: '',
organization: input.organization,
event: 'api:removeDeployTargetFromOrganization',
payload: {
data: {
input
}
}
});
return org[0];
};
export const getDeployTargetsByOrganizationId: ResolverFn = async (
{ id: oid },
args,
{ sqlClientPool, hasPermission }
) => {
// let oid = args.organization;
if (args.organization) {
oid = args.organization;
}
await hasPermission('organization', 'view', {
organization: oid,
});
const rows = await query(sqlClientPool, Sql.selectDeployTargetsByOrganization(oid));
if (!rows) {
return null;
}
return rows;
};
export const getEnvironmentsByOrganizationId: ResolverFn = async (
{ id: oid },
args,
{ sqlClientPool, hasPermission }
) => {
// let oid = args.organization;
if (args.organization) {
oid = args.organization;
}
await hasPermission('organization', 'view', {
organization: oid,
});
const rows = await query(sqlClientPool, Sql.selectOrganizationEnvironments(oid));
if (!rows) {
return null;
}
return rows;
};
export const updateOrganization: ResolverFn = async (
root,
{ input },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
if (input.patch.quotaProject || input.patch.quotaGroup || input.patch.quotaNotification || input.patch.quotaEnvironment || input.patch.quotaRoute) {
await hasPermission('organization', 'update');
} else {
await hasPermission('organization', 'updateOrganization', input.id);
}
if (input.patch.name) {
// check if the name is valid
isValidName(input.patch.name)
}
const oid = input.id.toString();
if (isPatchEmpty(input)) {
throw new Error('input.patch requires at least 1 attribute');
}
await query(sqlClientPool, Sql.updateOrganization(input));
const rows = await query(sqlClientPool, Sql.selectOrganization(oid));
userActivityLogger(`User updated organization ${R.prop(0, rows).name}`, {
project: '',
organization: input.organization,
event: 'api:updateOrganization',
payload: {
data: {
input
}
}
});
return R.prop(0, rows);
};
export const getOrganizationById: ResolverFn = async (
id,
args,
{ sqlClientPool, hasPermission }
) => {
let oid = args.id;
if (id) {
oid = id;
}
await hasPermission('organization', 'view', {
organization: oid,
});
const rows = await query(sqlClientPool, Sql.selectOrganization(oid));
const orgResult = rows[0];
if (!orgResult) {
return null;
}
return orgResult;
};
export const getOrganizationByName: ResolverFn = async (
name,
args,
{ sqlClientPool, hasPermission }
) => {
let orgName = args.name;
if (name) {
orgName = name;
}
const rows = await query(sqlClientPool, Sql.selectOrganizationByName(orgName));
const orgResult = rows[0];
if (!orgResult) {
return null;
}
await hasPermission('organization', 'view', {
organization: orgResult.id,
});
return orgResult;
};
export const getAllOrganizations: ResolverFn = async (
root,
args,
{ sqlClientPool, models, hasPermission, keycloakGrant }
) => {
let userOrganizationIds: number[];
try {
await hasPermission('organization', 'viewAll');
} catch (err) {
if (!keycloakGrant) {
logger.warn('No grant available for getAllProjects');
return [];
}
userOrganizationIds = await models.UserModel.getAllOrganizationIdsForUser({
id: keycloakGrant.access_token.content.sub
});
}
let queryBuilder = knex('organization');
if (userOrganizationIds) {
queryBuilder = queryBuilder.whereIn('id', userOrganizationIds);
}
const rows = await query(sqlClientPool, queryBuilder.toString());
return rows;
};
// get projects by organization id, used by organization resolver to list projects
// this resolver is only ever called by an organization top resolver for projects, so the permission has already been checked at the organization level
// no need to performpermission checks for this sub resolver
export const getProjectsByOrganizationId: ResolverFn = async (
{ id: oid },
args,
{ sqlClientPool, hasPermission }
) => {
const rows = await query(
sqlClientPool,
Sql.selectOrganizationProjects(oid)
);
return rows;
};
// get notifications by organization id and project id, used by organization resolver to list projects notifications
// this resolver is only ever called by an organization top resolver for notifications, so the permission has already been checked at the organization level
// no need to performpermission checks for this sub resolver
export const getNotificationsForOrganizationProjectId: ResolverFn = async (
organization,
args,
{ sqlClientPool, hasPermission }
) => {
let oid = args.organization;
if (organization) {
oid = organization.organization;
}
let pid = args.organization;
if (organization) {
pid = organization.id;
}
return await notificationHelpers(sqlClientPool).selectNotificationsByProjectId({project: pid})
};
// gets owners of an organization by id
export const getOwnersByOrganizationId: ResolverFn = async (
{ id: oid },
_input,
{ hasPermission, models }
) => {
await hasPermission('organization', 'view', {
organization: oid,
});
const orgUsers = await models.UserModel.loadUsersByOrganizationId(oid);
return orgUsers;
};
// list all groups by organization id
export const getGroupsByOrganizationId: ResolverFn = async (
{ id: oid },
_input,
{ hasPermission, models, sqlClientPool }
) => {
await hasPermission('organization', 'viewGroup', {
organization: oid,
});
const orgGroups = await groupHelpers(sqlClientPool).selectGroupsByOrganizationId(models, oid)
return orgGroups;
};
// list all users in all groups within an organization
export const getUsersByOrganizationId: ResolverFn = async (
_,
args,
{ hasPermission, models, sqlClientPool }
) => {
await hasPermission('organization', 'viewUsers', {
organization: args.organization,
});
const orgGroups = await groupHelpers(sqlClientPool).selectGroupsByOrganizationId(models, args.organization)
let members = []
for (const group in orgGroups) {
const groupMembers = await models.GroupModel.getGroupMembership(orgGroups[group]);
// there is probably a better way to do this to only add unique members in the organization in the response
let exists = false;
for (const member in groupMembers) {
for (const m in members) {
if (groupMembers[member].user.id == members[m].id) {
exists = true
}
}
if (!exists) {
// quick check to set the owner flag or not
groupMembers[member].user.owner = false
groupMembers[member].user.comment = null
if (groupMembers[member].user.attributes["comment"]) {
groupMembers[member].user.comment = groupMembers[member].user.attributes["comment"][0]
}
if (groupMembers[member].user.attributes["lagoon-organizations"]) {
for (const a in groupMembers[member].user.attributes["lagoon-organizations"]) {
if (parseInt(groupMembers[member].user.attributes["lagoon-organizations"][a]) == args.organization) {
groupMembers[member].user.owner = true
}
}
}
members.push(groupMembers[member].user)
}
exists = false
}
}
return members.map(row => ({ ...row, organization: args.organization }));
};
// get a users information for a user in the organization
export const getUserByEmailAndOrganizationId: ResolverFn = async (
_root,
{ email, organization},
{ sqlClientPool, models, hasPermission },
) => {
await hasPermission('organization', 'viewUser', {
organization: organization
});
try {
const user = await models.UserModel.loadUserByUsername(email);
const queryUserGroups = await models.UserModel.getAllGroupsForUser(user.id, organization);
user.owner = false
user.comment = null
if (user.attributes["comment"]) {
user.comment = user.attributes["comment"][0]
}
if (user.attributes["lagoon-organizations"]) {
for (const a in user.attributes["lagoon-organizations"]) {
if (parseInt(user.attributes["lagoon-organizations"][a]) == organization) {
user.owner = true
}
}
}
if (queryUserGroups.length == 0) {
// if this user has no groups in this organization, then return nothing about this user at all
return null
}
return { ...user, organization: organization };
} catch (err) {
return null
}
return null
};
// list the group roles for this user that have the organization id
export const getGroupRolesByUserIdAndOrganization: ResolverFn =async (
{ id: uid, organization },
_input,
{ hasPermission, models, adminScopes }
) => {
if (organization) {
const queryUserGroups = await models.UserModel.getAllGroupsForUser(uid, organization);
let groups = []
for (const g in queryUserGroups) {
let group = {id: queryUserGroups[g].id, name: queryUserGroups[g].name, role: queryUserGroups[g].subGroups[0].realmRoles[0], groupType: null, organization: null}
if (queryUserGroups[g].attributes["type"]) {
group.groupType = queryUserGroups[g].attributes["type"][0]
}
if (queryUserGroups[g].attributes["lagoon-organization"]) {
group.organization = queryUserGroups[g].attributes["lagoon-organization"][0]
}
groups.push(group)
}
return groups;
}
return null
}
// list all groups by organization id
export const getGroupsByNameAndOrganizationId: ResolverFn = async (
root,
{ name, organization },
{ hasPermission, models, keycloakGrant }
) => {
try {
await hasPermission('organization', 'viewGroup', {
organization: organization,
});
const group = await models.GroupModel.loadGroupByName(name);
if (R.prop('lagoon-organization', group.attributes)) {
if (R.prop('lagoon-organization', group.attributes).toString() == organization) {
return group
}
}
} catch (err) {
return [];
}
return [];
};
export const getGroupCountByOrganizationProject: ResolverFn = async (
{ id: pid },
_input,
{ sqlClientPool, models }
) => {
const orgProjectGroups = await groupHelpers(sqlClientPool).selectGroupsByProjectId(models, pid)
return orgProjectGroups.length
}
// get the groups of a project in an organization
// this is only accessible as a resolver of organizations
// skip permissions checks as they are already
// performed in the main resolver function for organizations
export const getGroupsByOrganizationsProject: ResolverFn = async (
{ id: pid },
_input,
{ sqlClientPool, models, keycloakGrant, keycloakUsersGroups, adminScopes }
) => {
const orgProjectGroups = await groupHelpers(sqlClientPool).selectGroupsByProjectId(models, pid)
if (adminScopes.projectViewAll) {
// if platform owner, this will show ALL groups on a project (those that aren't in the organization too, yes its possible with outside intervention :| )
return orgProjectGroups;
}
const user = await models.UserModel.loadUserById(
keycloakGrant.access_token.content.sub
);
// if this user is an owner of an organization, then also display org based groups to this user
// when listing project groups
const userGroups = keycloakUsersGroups;
const usersOrgs = R.defaultTo('', R.prop('lagoon-organizations', user.attributes)).toString()
const usersOrgsViewer = R.defaultTo('', R.prop('lagoon-organizations-viewer', user.attributes)).toString()
if (usersOrgs != "" ) {
const usersOrgsArr = usersOrgs.split(',');
for (const userOrg of usersOrgsArr) {
const project = await projectHelpers(sqlClientPool).getProjectById(pid);
if (project.organization == userOrg) {
const orgGroups = await groupHelpers(sqlClientPool).selectGroupsByOrganizationId(models, project.organization)
for (const pGroup of orgGroups) {
userGroups.push(pGroup)
}
}
}
}
if (usersOrgsViewer != "" ) {
const usersOrgsArr = usersOrgsViewer.split(',');
for (const userOrg of usersOrgsArr) {
const project = await projectHelpers(sqlClientPool).getProjectById(pid);
if (project.organization == userOrg) {
const orgGroups = await groupHelpers(sqlClientPool).selectGroupsByOrganizationId(models, project.organization)
for (const pGroup of orgGroups) {
userGroups.push(pGroup)
}
}
}
}
let userProjectGroups = []
for (const ug of userGroups) {
const pg = orgProjectGroups.find(i => i.id === ug.id)
if (pg) {
userProjectGroups.push(pg)
}
}
return userProjectGroups;
};
// check an existing project and the associated groups can be added to an organization
// this will return errors if there are projects or groups that are part of different organizations
// this is a helper function that is a WIP, not fully flushed out
const checkProjectGroupAssociation = async (oid, projectGroups, projectGroupNames, otherOrgs, groupProjectIds,projectInOtherOrgs, sqlClientPool) => {
// get all the groups the requested project is in
for (const group of projectGroups) {
// for each group the project is in, check if it has an organization
if (R.prop('lagoon-organization', group.attributes)) {
// if it has an organization that is not the requested organization, add it to a list
if (R.prop('lagoon-organization', group.attributes) != oid) {
projectGroupNames.push({group: group.name, organization: R.prop('lagoon-organization', group.attributes).toString()})
otherOrgs.push(R.prop('lagoon-organization', group.attributes).toString())
}
}
// for each group the project is in, get the list of projects that are also in this group
if (R.prop('lagoon-projects', group.attributes)) {
const groupProjects = R.prop('lagoon-projects', group.attributes).toString().split(',')
for (const project of groupProjects) {
groupProjectIds.push({group: group.name, project: project})
}
}
}
if (groupProjectIds.length > 0) {
// for all the groups->projects associations
for (const pGroup of groupProjectIds) {
const project = await projectHelpers(sqlClientPool).getProjectById(pGroup.project)
// check if the projects are in an organization, and if so, add it to a list if it is in one not in the requested organization
if (project.organization != oid && project.organization != null) {
projectInOtherOrgs.push({group: pGroup.group, project: project.name, organization: project.organization})
otherOrgs.push(project.organization.toString())
}
}
}
// report errors here
const uniqOtherOrgs = new Set(otherOrgs)
if (projectInOtherOrgs.length > 0) {
if (uniqOtherOrgs.size > 1) {
throw new Error(`This project has groups that have projects in other organizations: [${JSON.stringify(projectInOtherOrgs)}]`)
} else {
// if there is only 1 organization across all the associated projects/groups, then its possible to modify all of these to change them
// to the new organization
// throw new Error(`This project has groups that have projects in 1 other organizations: [${[...uniqOtherOrgs]}]`)
}
}
if (projectGroupNames.length > 0) {
if (uniqOtherOrgs.size > 1) {
throw new Error(`This project has groups that are in other organizations: [${JSON.stringify(projectGroupNames)}]`)
} else {
// if there is only 1 organization across all the associated projects/groups, then its possible to modify all of these to change them
// to the new organization
// throw new Error(`This project has groups that are in 1 other organizations: [${[...uniqOtherOrgs]}]`)
}
}
}
export const getProjectGroupOrganizationAssociation: ResolverFn = async (
_root,
{ input },
{ sqlClientPool, models, hasPermission }
) => {
let pid = input.project;
let oid = input.organization;
// platform admin only as it potentially reveals information about projects/orgs/groups
await hasPermission('organization', 'add');
const groupProjectIds = []
const projectInOtherOrgs = []
const projectGroupNames = []
const otherOrgs = []
// get all the groups the requested project is in
const projectGroups = await groupHelpers(sqlClientPool).selectGroupsByProjectId(models, pid)
await checkProjectGroupAssociation(oid, projectGroups, projectGroupNames, otherOrgs, groupProjectIds, projectInOtherOrgs, sqlClientPool)
return "success";
};
// remove project from an organization
// this removes all notifications and groups from the project and resets all the access to the project to only
// the default project group and the default-user of the project
export const removeProjectFromOrganization: ResolverFn = async (
root,
{ input },
{ sqlClientPool, hasPermission, models, userActivityLogger }
) => {
// platform admin only
await hasPermission('organization', 'add');
let pid = input.project;
const project = await projectHelpers(sqlClientPool).getProjectById(pid)
if (project.organization != input.organization) {
throw new Error(
`Project is not in organization`
);
}
try {
const projectGroups = await groupHelpers(sqlClientPool).selectGroupsByProjectId(models, pid)
let removeGroups = []
for (const g in projectGroups) {
if (projectGroups[g].attributes["type"] == "project-default-group") {
// remove all users from the project default group except the `default-user@project`
await models.GroupModel.removeNonProjectDefaultUsersFromGroup(projectGroups[g], project.name)
// update group
await models.GroupModel.updateGroup({
id: projectGroups[g].id,
name: projectGroups[g].name,
attributes: {
...projectGroups[g].attributes,
"lagoon-organization": [""]
}
});
} else {
removeGroups.push(projectGroups[g])
}
}
// remove groups from project
await models.GroupModel.removeProjectFromGroups(pid, removeGroups);
} catch (err) {
throw new Error(
`Unable to remove all groups from the project`
)
}
try {
// remove all notifications from project
await notificationHelpers(sqlClientPool).removeAllNotificationsFromProject({project: pid})
} catch (err) {
throw new Error(
`Unable to remove all notifications from the project`
)
}
try {
// remove the project from the organization
await query(
sqlClientPool,
Sql.updateProjectOrganization({
pid,
patch:{
organization: null,
}
})
);
} catch (err) {
throw new Error(
`Unable to remove project from organization`
)
}
const org = await query(sqlClientPool, Sql.selectOrganization(input.organization));
userActivityLogger(`User removed project ${project.name} from an organization ${R.prop(0, org).name}`, {
project: '',
organization: input.organization,
event: 'api:removeProjectFromOrganization',
payload: {
data: {
input
}
}
});
return projectHelpers(sqlClientPool).getProjectById(pid);
}
// add existing project to an organization
export const addExistingProjectToOrganization: ResolverFn = async (
root,
{ input },
{ sqlClientPool, hasPermission, userActivityLogger, models }
) => {
let pid = input.project;
let oid = input.organization;
// platform admin only as it potentially reveals information about projects/orgs/groups
await hasPermission('organization', 'add');
const groupProjectIds = []
const projectInOtherOrgs = []
const projectGroupNames = []
const otherOrgs = []
// get all the groups the requested project is in
const projectGroups = await groupHelpers(sqlClientPool).selectGroupsByProjectId(models, pid)
await checkProjectGroupAssociation(oid, projectGroups, projectGroupNames, otherOrgs, groupProjectIds, projectInOtherOrgs, sqlClientPool)
// check if project.organization is already set?
// get all groups the project is in
for (const group of projectGroups) {
// update the groups to be in the organization
const updatedGroup = await models.GroupModel.updateGroup({
id: group.id,
name: group.name,
attributes: {
...group.attributes,
"lagoon-organization": [input.organization]
}
});
// log this activity
userActivityLogger(`User added a group to organization`, {
project: '',
organization: input.organization,
event: 'api:updateOrganizationGroup',
payload: {
data: {
updatedGroup
}
}
});
}
// check all the groups for associations
// update all groups to be in the organization
// set project.organization
await query(
sqlClientPool,
Sql.updateProjectOrganization({
pid,
patch:{
organization: oid,
}
})
);
// log this activity
userActivityLogger(`User added a project to organization`, {
project: '',
organization: input.organization,
event: 'api:addExistingProjectToOrganization',
payload: {
data: {
project: pid,
patch:{
organization: oid,
}
}
}
});
return projectHelpers(sqlClientPool).getProjectById(pid);
}
const checkOrgProjectGroup = async (sqlClientPool, input, models) => {
// check the organization exists
const organizationData = await Helpers(sqlClientPool).getOrganizationById(input.organization);
if (organizationData === undefined) {
throw new Error(`Organization does not exist`)
}
// check the requested group exists
const group = await models.GroupModel.loadGroupByIdOrName(input);
if (group === undefined) {
throw new Error(`Group does not exist`)
}
// check the organization for projects currently attached to it
const projectsByOrg = await projectHelpers(sqlClientPool).getProjectByOrganizationId(input.organization);
const projectIdsByOrg = []
for (const project of projectsByOrg) {
projectIdsByOrg.push(parseInt(project.id))
}
// get the project ids
const groupProjectIds = []
if (R.prop('lagoon-projects', group.attributes)) {
const groupProjects = R.prop('lagoon-projects', group.attributes).toString().split(',')
if (groupProjects.length > 0) {
for (const project of groupProjects) {
groupProjectIds.push(parseInt(project))
}
}
}
if (projectIdsByOrg.length > 0 && groupProjectIds.length > 0) {
if (projectIdsByOrg.length == 0) {
let filters = arrayDiff(groupProjectIds, projectIdsByOrg)
throw new Error(`This organization has no projects associated to it, the following projects that are not part of the requested organization: [${filters}]`)
} else {
if (groupProjectIds.length > 0) {
let filters = arrayDiff(groupProjectIds, projectIdsByOrg)
if (filters.length > 0) {
throw new Error(`This group has the following projects that are not part of the requested organization: [${filters}]`)
}
}
}
}
return group
}
// check an existing group to see if it can be added to an organization
// this function will return errors if there are projects in the group that are not in the organization
// if there are no projects in the organization, and no projects in the group then it will succeed
// this is a helper function that is a WIP, not fully flushed out
export const getGroupProjectOrganizationAssociation: ResolverFn = async (
_root,
{ input },
{ models, sqlClientPool, hasPermission }
) => {
// platform admin only as it potentially reveals information about projects/orgs/groups
await hasPermission('organization', 'add');
await checkOrgProjectGroup(sqlClientPool, input, models)
return "success"
};
// add an existing group to an organization
// this function will return errors if there are projects in the group that are not in the organization
// if there are no projects in the organization, and no projects in the group then it will succeed
export const addExistingGroupToOrganization: ResolverFn = async (
_root,
{ input },
{ models, sqlClientPool, hasPermission, userActivityLogger }
) => {
// platform admin only as it potentially reveals information about projects/orgs/groups
await hasPermission('organization', 'add');
// check the organization exists
const organizationData = await Helpers(sqlClientPool).getOrganizationById(input.organization);
if (organizationData === undefined) {
throw new Error(`Organization does not exist`)
}
const group = await checkOrgProjectGroup(sqlClientPool, input, models)
// update the group to be in the organization
const updatedGroup = await models.GroupModel.updateGroup({
id: group.id,
name: group.name,
attributes: {
...group.attributes,
"lagoon-organization": [input.organization]
}
});
// log this activity
userActivityLogger(`User added a group to organization`, {
project: '',
organization: input.organization,
event: 'api:updateOrganizationGroup',
payload: {
data: {
updatedGroup
}
}
});
return updatedGroup
};
// removes a user from all groups in an organisation
export const removeUserFromOrganizationGroups: ResolverFn = async (
_root,
{ input: { user: userInput, organization: organizationInput } },
{ models, sqlClientPool, hasPermission, userActivityLogger }
) => {
if (R.isEmpty(userInput)) {
throw new Error('You must provide a user id or email');
}
const user = await models.UserModel.loadUserByIdOrUsername({
id: R.prop('id', userInput),
email: R.prop('email', userInput)
});
// check the organization exists
const organizationData = await Helpers(sqlClientPool).getOrganizationById(organizationInput);
if (organizationData === undefined) {
throw new Error(`Organization does not exist`)
}
// check permissions and get groups
await hasPermission('organization', 'removeGroup', {
organization: organizationInput,
});
const orgGroups = await groupHelpers(sqlClientPool).selectGroupsByOrganizationId(models, organizationInput)
// iterate through groups and remove the user
let groupsRemoved = []
for (const group in orgGroups) {
// if the groups organization is the one to remove from, push it to a new array
if (R.prop('lagoon-organization', orgGroups[group].attributes) == organizationInput) {
groupsRemoved.push(orgGroups[group]);
}
}
try {
await models.GroupModel.removeUserFromGroups(user, groupsRemoved);
} catch (error) {
throw new Error(`Unable to remove user from groups: ${error}`)
}
userActivityLogger(`User removed from these groups in organization: ${organizationData.name}`, {
project: '',
organization: organizationData.name,
event: 'api:removeUserFromOrganizationGroups',
payload: {
input: {
user: userInput, organization: organizationInput
},
data: groupsRemoved
}
});
return organizationData;
};
// delete an organization, only if it has no projects, notifications, or groups
export const deleteOrganization: ResolverFn = async (
_root,
{ input },
{ sqlClientPool, hasPermission, userActivityLogger, models }
) => {
await hasPermission('organization', 'delete', {
organization: input.id
});
const rows = await query(sqlClientPool, Sql.selectOrganization(input.id));
if (R.length(rows) == 0) {
throw new Error(
`Organization doesn't exist`
);
}
const orgResult = rows[0];
const projects = await query(
sqlClientPool, Sql.selectOrganizationProjects(orgResult.id)
);