From 753ef08cacaca52658f5478797e337fa290de31a Mon Sep 17 00:00:00 2001 From: shreddedbacon Date: Wed, 5 Apr 2023 07:44:11 +1000 Subject: [PATCH] chore: fall back to get groups and roles for project if highest role not found initially --- services/api/src/util/auth.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/services/api/src/util/auth.ts b/services/api/src/util/auth.ts index 387656e4f3..52ee36c141 100644 --- a/services/api/src/util/auth.ts +++ b/services/api/src/util/auth.ts @@ -6,6 +6,8 @@ import { isNotNil } from './func'; import { keycloakGrantManager } from '../clients/keycloakClient'; const { userActivityLogger } = require('../loggers/userActivityLogger'); import { Group } from '../models/group'; +import { User } from '../models/user'; +import { saveRedisKeycloakCache } from '../clients/redisClient'; interface ILegacyToken { iat: string; @@ -147,6 +149,7 @@ export class KeycloakUnauthorizedError extends Error { export const keycloakHasPermission = (grant, requestCache, modelClients, serviceAccount, currentUser, groupRoleProjectIds) => { const GroupModel = Group(modelClients); + const UserModel = User(modelClients); return async (resource, scope, attributes: IKeycloakAuthAttributes = {}) => { @@ -187,7 +190,18 @@ export const keycloakHasPermission = (grant, requestCache, modelClients, service projectQuery: [`${projectId}`] }; - const [highestRoleForProject, upids] = getUserRoleForProjectFromRoleProjectIds(groupRoleProjectIds, projectId) + let [highestRoleForProject, upids] = getUserRoleForProjectFromRoleProjectIds(groupRoleProjectIds, projectId) + + if (!highestRoleForProject) { + // if no role is detected, fall back to checking the slow way. this is usually only going to be on project creation + // but could happen elsewhere + const keycloakUsersGroups = await UserModel.getAllGroupsForUser(currentUser.id); + // grab the users project ids and roles in the first request + groupRoleProjectIds = await UserModel.getAllProjectsIdsForUser(currentUser, keycloakUsersGroups); + + [highestRoleForProject, upids] = getUserRoleForProjectFromRoleProjectIds(groupRoleProjectIds, projectId) + } + if (upids.length) { claims = { ...claims,