feat(api): add auth and users
This commit is contained in:
1 parent
afc1355221
commit
49035f3501
20 files changed
+756
No files matched your search
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { decodeJwt } from 'jose';
|
||||
import type { Request } from 'express';
|
||||
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
|
||||
import { AuthService } from './auth.service';
|
||||
import { IdentityProviderName, JwtService } from './jwt.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(
|
||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
const authz = request.headers?.authorization;
|
||||
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
|
||||
|
||||
if (!authzHeader) {
|
||||
const fallback =
|
||||
await this.authService.resolveDevFallbackFromRequest(request);
|
||||
if (fallback) {
|
||||
request.user = fallback.user;
|
||||
request.identity = fallback.identity;
|
||||
return true;
|
||||
}
|
||||
if (isPublicAccessAllowed) return true;
|
||||
throw new UnauthorizedException(
|
||||
'Missing or invalid Authorization header',
|
||||
);
|
||||
}
|
||||
|
||||
if (!authzHeader.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException(
|
||||
'Missing or invalid Authorization header',
|
||||
);
|
||||
}
|
||||
|
||||
const token = authzHeader.slice('Bearer '.length).trim();
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Empty bearer token');
|
||||
}
|
||||
|
||||
const identityProvider = this.pickIdPFromToken(token);
|
||||
|
||||
try {
|
||||
const verifyResult = await this.jwtService.verify(
|
||||
token,
|
||||
identityProvider,
|
||||
);
|
||||
request.tokenPayload = verifyResult.payload;
|
||||
request.tokenHeader = verifyResult.protectedHeader;
|
||||
request.identityProvider = identityProvider;
|
||||
return true;
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : 'JWT verification failed';
|
||||
throw new UnauthorizedException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private pickIdPFromToken(token: string): IdentityProviderName {
|
||||
try {
|
||||
const { iss } = decodeJwt(token) as { iss?: string };
|
||||
if (!iss) {
|
||||
throw new Error('Token has no issuer (iss) claim');
|
||||
}
|
||||
const lower = iss.toLowerCase();
|
||||
if (lower.includes('login.microsoftonline.com')) {
|
||||
return 'MICROSOFT_ENTRAID';
|
||||
}
|
||||
throw new Error(`Unknown issuer: ${iss}`);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Unable to decode token';
|
||||
throw new UnauthorizedException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user