feat(api): add auth guards
This commit is contained in:
1 parent
3a86676a12
commit
d4b790fd86
16 files changed
+592
No files matched your search
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { IdentityService } from './identity.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class IdentityResolverGuard implements CanActivate {
|
||||
constructor(private readonly identityService: IdentityService) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
if (request.identity || !request.tokenPayload) return true;
|
||||
|
||||
const entraOid = stringClaim(request.tokenPayload.oid);
|
||||
if (!entraOid) {
|
||||
throw new UnauthorizedException('Token is missing oid claim.');
|
||||
}
|
||||
|
||||
request.identity = await this.identityService.findOrCreateByOid({
|
||||
entraOid,
|
||||
tenantId: stringClaim(request.tokenPayload.tid),
|
||||
email:
|
||||
stringClaim(request.tokenPayload.preferred_username) ??
|
||||
stringClaim(request.tokenPayload.email),
|
||||
displayName: stringClaim(request.tokenPayload.name),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function stringClaim(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
Reference in new issue
Block a user