11import path from "path" ;
22import { readFile } from "fs-extra" ;
33import invariant from "invariant" ;
4+ import { Op } from "sequelize" ;
45import { CollectionPermission , UserRole } from "@shared/types" ;
56import WelcomeEmail from "@server/emails/templates/WelcomeEmail" ;
67import env from "@server/env" ;
@@ -13,6 +14,8 @@ import {
1314 AuthenticationProvider ,
1415 Collection ,
1516 Document ,
17+ Group ,
18+ GroupUser ,
1619 Team ,
1720 User ,
1821} from "@server/models" ;
@@ -51,6 +54,8 @@ type Props = {
5154 /** The public url of an image representing the team */
5255 avatarUrl ?: string | null ;
5356 } ;
57+ /** Groups the user should be member of */
58+ groups ?: string [ ] ;
5459 /** Details of the authentication provider being used */
5560 authenticationProvider : {
5661 /** The name of the authentication provider, eg "google" */
@@ -85,6 +90,7 @@ async function accountProvisioner(
8590 {
8691 user : userParams ,
8792 team : teamParams ,
93+ groups : groupNames ,
8894 authenticationProvider : authenticationProviderParams ,
8995 authentication : authenticationParams ,
9096 } : Props
@@ -191,6 +197,10 @@ async function accountProvisioner(
191197 }
192198 }
193199
200+ if ( groupNames !== undefined ) {
201+ await reconciliateUserGroups ( groupNames , user , team ) ;
202+ }
203+
194204 return {
195205 user,
196206 team,
@@ -257,3 +267,47 @@ async function provisionFirstCollection(team: Team, user: User) {
257267export default traceFunction ( {
258268 spanName : "accountProvisioner" ,
259269} ) ( accountProvisioner ) ;
270+
271+ async function reconciliateUserGroups (
272+ groupNames : string [ ] ,
273+ user : User ,
274+ team : Team
275+ ) {
276+ const groups = await Promise . all (
277+ groupNames . map ( async ( groupName ) => {
278+ // Get existing group
279+ let group = await Group . findOne ( {
280+ where : {
281+ name : { [ Op . iLike ] : groupName } ,
282+ teamId : team . id ,
283+ } ,
284+ } ) ;
285+ // Create group if it doesn't exist
286+ group ??= await Group . create ( {
287+ name : groupName ,
288+ teamId : user . teamId ,
289+ createdById : user . id ,
290+ } ) ;
291+ // Add user to group
292+ await GroupUser . findOrCreate ( {
293+ where : {
294+ groupId : group . id ,
295+ userId : user . id ,
296+ } ,
297+ defaults : {
298+ createdById : user . id ,
299+ } ,
300+ } ) ;
301+ return group ;
302+ } )
303+ ) ;
304+ // Remove user from groups they are no longer a member of
305+ await GroupUser . destroy ( {
306+ where : {
307+ userId : user . id ,
308+ groupId : {
309+ [ Op . notIn ] : groups . map ( ( group ) => group . id ) ,
310+ } ,
311+ } ,
312+ } ) ;
313+ }
0 commit comments