From db700241a82202301506228a8b637c9fdcb08e1f Mon Sep 17 00:00:00 2001 From: Mathis Date: Fri, 4 Oct 2024 11:35:12 +0200 Subject: [PATCH] Add InsertAdminState guard to check admin status Introduces a new InsertAdminState guard to verify if the user is an admin by checking their authentication token and updating a custom header 'is_admin' accordingly. This guard fetches user details from the database and sets the 'is_admin' header to true or false based on the user's admin status. --- apps/backend/src/app/auth/auth.guard.ts | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/apps/backend/src/app/auth/auth.guard.ts b/apps/backend/src/app/auth/auth.guard.ts index 2cffdb3..3b61135 100644 --- a/apps/backend/src/app/auth/auth.guard.ts +++ b/apps/backend/src/app/auth/auth.guard.ts @@ -87,3 +87,41 @@ export class AdminGuard implements CanActivate { return true; } } + +@Injectable() +export class InsertAdminState implements CanActivate { + constructor( + @Inject(CredentialsService) + private readonly credentialService: CredentialsService, + @Inject(DbService) private readonly databaseService: DbService, + ) {} + async canActivate(context: ExecutionContext): Promise { + const request : Request = context.switchToHttp().getRequest(); + + const authHeader = request.headers.authorization; + if (!authHeader) { + request.headers.is_admin = false; + return true; + } + const token = authHeader.split(" ")[1]; + const vToken = await this.credentialService.verifyAuthToken(token); + + const user = await this.databaseService + .use() + .select() + .from(UsersTable) + .where(eq(UsersTable.uuid, vToken.payload.sub)); + + if (user.length !== 1) + throw new UnauthorizedException("No such user found."); + + if (!user[0].isAdmin) { + request.headers.is_admin = false; + return true; + } + + request.headers.is_admin = true + + return true; + } +} \ No newline at end of file