feat(auth): Add role-based access management from OpenID Connect (#535)

* feat(auth): Add role-based access management from OpenID Connect

Signed-off-by: Marvin A. Ruder <signed@mruder.dev>

* Apply suggestions from code review

Signed-off-by: Marvin A. Ruder <signed@mruder.dev>

---------

Signed-off-by: Marvin A. Ruder <signed@mruder.dev>
This commit is contained in:
Marvin A. Ruder
2024-07-17 23:25:42 +02:00
committed by GitHub
parent e5a0c649e3
commit 70fd2d94be
33 changed files with 160 additions and 38 deletions

View File

@@ -3,4 +3,5 @@ export interface OAuthSignInDto {
providerId: string;
providerUsername: string;
email: string;
isAdmin?: boolean;
}

View File

@@ -46,13 +46,16 @@ export class OAuthService {
provider: user.provider,
providerUserId: user.providerId,
},
include: {
user: true,
},
});
if (oauthUser) {
await this.updateIsAdmin(user);
const updatedUser = await this.prisma.user.findFirst({
where: {
email: user.email,
},
});
this.logger.log(`Successful login for user ${user.email} from IP ${ip}`);
return this.auth.generateToken(oauthUser.user, true);
return this.auth.generateToken(updatedUser, true);
}
return this.signUp(user, ip);
@@ -150,6 +153,7 @@ export class OAuthService {
userId: existingUser.id,
},
});
await this.updateIsAdmin(user);
return this.auth.generateToken(existingUser, true);
}
@@ -160,6 +164,7 @@ export class OAuthService {
password: null,
},
ip,
user.isAdmin,
);
await this.prisma.oAuthUser.create({
@@ -173,4 +178,16 @@ export class OAuthService {
return result;
}
private async updateIsAdmin(user: OAuthSignInDto) {
if ("isAdmin" in user)
await this.prisma.user.update({
where: {
email: user.email,
},
data: {
isAdmin: user.isAdmin,
},
});
}
}

View File

@@ -101,10 +101,10 @@ export class DiscordProvider implements OAuthProvider<DiscordToken> {
});
const guilds = (await res.json()) as DiscordPartialGuild[];
if (!guilds.some((guild) => guild.id === guildId)) {
throw new ErrorPageException("discord_guild_permission_denied");
throw new ErrorPageException("user_not_allowed");
}
} catch {
throw new ErrorPageException("discord_guild_permission_denied");
throw new ErrorPageException("user_not_allowed");
}
}
}

View File

@@ -2,6 +2,7 @@ import { Logger } from "@nestjs/common";
import { ConfigService } from "../../config/config.service";
import { JwtService } from "@nestjs/jwt";
import { Cache } from "cache-manager";
import * as jmespath from "jmespath";
import { nanoid } from "nanoid";
import { OAuthCallbackDto } from "../dto/oauthCallback.dto";
import { OAuthProvider, OAuthToken } from "./oauthProvider.interface";
@@ -108,6 +109,11 @@ export abstract class GenericOidcProvider implements OAuthProvider<OidcToken> {
token: OAuthToken<OidcToken>,
query: OAuthCallbackDto,
claim?: string,
roleConfig?: {
path?: string;
generalAccess?: string;
adminAccess?: string;
},
): Promise<OAuthSignInDto> {
const idTokenData = this.decodeIdToken(token.idToken);
// maybe it's not necessary to verify the id token since it's directly obtained from the provider
@@ -127,6 +133,39 @@ export abstract class GenericOidcProvider implements OAuthProvider<OidcToken> {
: idTokenData.preferred_username ||
idTokenData.name ||
idTokenData.nickname;
let isAdmin: boolean;
if (roleConfig?.path) {
// A path to read roles from the token is configured
let roles: string[] | null;
try {
roles = jmespath.search(idTokenData, roleConfig.path);
} catch (e) {
roles = null;
}
if (Array.isArray(roles)) {
// Roles are found in the token
if (roleConfig.generalAccess && !roles.includes(roleConfig.generalAccess)) {
// Role for general access is configured and the user does not have it
this.logger.error(`User roles ${roles} do not include ${roleConfig.generalAccess}`);
throw new ErrorPageException("user_not_allowed");
}
if (roleConfig.adminAccess) {
// Role for admin access is configured
isAdmin = roles.includes(roleConfig.adminAccess);
}
} else {
this.logger.error(
`Roles not found at path ${roleConfig.path} in ID Token ${JSON.stringify(
idTokenData,
undefined,
2,
)}`,
);
throw new ErrorPageException("user_not_allowed");
}
}
if (!username) {
this.logger.error(
@@ -146,6 +185,7 @@ export abstract class GenericOidcProvider implements OAuthProvider<OidcToken> {
email: idTokenData.email,
providerId: idTokenData.sub,
providerUsername: username,
...(isAdmin !== undefined && { isAdmin }),
};
}

View File

@@ -34,6 +34,13 @@ export class OidcProvider extends GenericOidcProvider {
_?: string,
): Promise<OAuthSignInDto> {
const claim = this.config.get("oauth.oidc-usernameClaim") || undefined;
return super.getUserInfo(token, query, claim);
const rolePath = this.config.get("oauth.oidc-rolePath") || undefined;
const roleGeneralAccess = this.config.get("oauth.oidc-roleGeneralAccess") || undefined;
const roleAdminAccess = this.config.get("oauth.oidc-roleAdminAccess") || undefined;
return super.getUserInfo(token, query, claim, {
path: rolePath,
generalAccess: roleGeneralAccess,
adminAccess: roleAdminAccess,
});
}
}