initial
This commit is contained in:
34
apps/api/src/auth/jwt-auth.guard.ts
Normal file
34
apps/api/src/auth/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user