|
| 1 | +package idpsync |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/golang-jwt/jwt/v4" |
| 7 | + "github.com/google/uuid" |
| 8 | + "golang.org/x/xerrors" |
| 9 | + |
| 10 | + "github.com/coder/coder/v2/coderd/database" |
| 11 | + "github.com/coder/coder/v2/coderd/database/dbauthz" |
| 12 | +) |
| 13 | + |
| 14 | +type GroupParams struct { |
| 15 | + // SyncEnabled if false will skip syncing the user's groups |
| 16 | + SyncEnabled bool |
| 17 | + MergedClaims jwt.MapClaims |
| 18 | +} |
| 19 | + |
| 20 | +func (AGPLIDPSync) GroupSyncEnabled() bool { |
| 21 | + // AGPL does not support syncing groups. |
| 22 | + return false |
| 23 | +} |
| 24 | + |
| 25 | +func (s AGPLIDPSync) ParseGroupClaims(_ context.Context, _ jwt.MapClaims) (GroupParams, *HTTPError) { |
| 26 | + return GroupParams{ |
| 27 | + SyncEnabled: s.GroupSyncEnabled(), |
| 28 | + }, nil |
| 29 | +} |
| 30 | + |
| 31 | +// TODO: Group allowlist behavior should probably happen at this step. |
| 32 | +func (s AGPLIDPSync) SyncGroups(ctx context.Context, db database.Store, user database.User, params GroupParams) error { |
| 33 | + // Nothing happens if sync is not enabled |
| 34 | + if !params.SyncEnabled { |
| 35 | + return nil |
| 36 | + } |
| 37 | + |
| 38 | + // nolint:gocritic // all syncing is done as a system user |
| 39 | + ctx = dbauthz.AsSystemRestricted(ctx) |
| 40 | + |
| 41 | + db.InTx(func(tx database.Store) error { |
| 42 | + userGroups, err := db.GetGroups(ctx, database.GetGroupsParams{ |
| 43 | + HasMemberID: user.ID, |
| 44 | + }) |
| 45 | + if err != nil { |
| 46 | + return xerrors.Errorf("get user groups: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + // Figure out which organizations the user is a member of. |
| 50 | + userOrgs := make(map[uuid.UUID][]database.GetGroupsRow) |
| 51 | + for _, g := range userGroups { |
| 52 | + g := g |
| 53 | + userOrgs[g.Group.OrganizationID] = append(userOrgs[g.Group.OrganizationID], g) |
| 54 | + } |
| 55 | + |
| 56 | + // Force each organization, we sync the groups. |
| 57 | + db.RemoveUserFromAllGroups(ctx, user.ID) |
| 58 | + |
| 59 | + return nil |
| 60 | + }, nil) |
| 61 | + |
| 62 | + // |
| 63 | + //tx.InTx(func(tx database.Store) error { |
| 64 | + // // When setting the user's groups, it's easier to just clear their groups and re-add them. |
| 65 | + // // This ensures that the user's groups are always in sync with the auth provider. |
| 66 | + // err := tx.RemoveUserFromAllGroups(ctx, user.ID) |
| 67 | + // if err != nil { |
| 68 | + // return err |
| 69 | + // } |
| 70 | + // |
| 71 | + // for _, org := range userOrgs { |
| 72 | + // |
| 73 | + // } |
| 74 | + // |
| 75 | + // return nil |
| 76 | + //}, nil) |
| 77 | + |
| 78 | + return nil |
| 79 | +} |
0 commit comments