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.
This commit is contained in:
parent
221410dfb0
commit
db700241a8
@ -87,3 +87,41 @@ export class AdminGuard implements CanActivate {
|
|||||||
return true;
|
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<boolean> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user