35 lines
1.1 KiB
TypeScript
35 lines
1.1 KiB
TypeScript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { Request } from 'express';
|
|
import { RequestUser } from '../common/request-user';
|
|
|
|
@Injectable()
|
|
export class JwtAuthGuard implements CanActivate {
|
|
constructor(private readonly jwt: JwtService) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<Request & { user?: RequestUser }>();
|
|
const token = this.extractBearerToken(request);
|
|
if (!token) {
|
|
throw new UnauthorizedException('Nicht angemeldet.');
|
|
}
|
|
|
|
try {
|
|
request.user = await this.jwt.verifyAsync<RequestUser>(token);
|
|
return true;
|
|
} catch {
|
|
throw new UnauthorizedException('Session ist ungueltig oder abgelaufen.');
|
|
}
|
|
}
|
|
|
|
private extractBearerToken(request: Request): string | undefined {
|
|
const header = request.headers.authorization;
|
|
if (!header) {
|
|
return undefined;
|
|
}
|
|
|
|
const [type, token] = header.split(' ');
|
|
return type?.toLowerCase() === 'bearer' ? token : undefined;
|
|
}
|
|
}
|