39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
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;
|
|
}
|