authentication
This commit is contained in:
61
api/src/core/guards/auth.guard.ts
Normal file
61
api/src/core/guards/auth.guard.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JsonWebTokenError, JwtService } from '@nestjs/jwt';
|
||||
import { Request } from 'express';
|
||||
import { IPayload } from 'src/model/interface';
|
||||
import { AuthService } from 'src/modules/auth/auth.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private config: ConfigService,
|
||||
private authService: AuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Token not provided');
|
||||
}
|
||||
|
||||
try {
|
||||
const secret = this.config.get('JWT_SECRET');
|
||||
// Überprüft das JWT und dekodiert es
|
||||
const payload: IPayload = this.jwtService.verify(token, { secret });
|
||||
if (payload.type != 'access') {
|
||||
throw new UnauthorizedException('wrong token');
|
||||
}
|
||||
const user = await this.authService.getUserById(payload.id);
|
||||
if (!user.isActive) {
|
||||
throw new HttpException('not active', HttpStatus.FORBIDDEN);
|
||||
}
|
||||
request['user'] = user;
|
||||
} catch (error) {
|
||||
const j = error as JsonWebTokenError;
|
||||
const m = j.message;
|
||||
|
||||
throw new UnauthorizedException(m);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: Request): string | null {
|
||||
const authHeader = request.headers['authorization'];
|
||||
if (!authHeader) {
|
||||
return null;
|
||||
}
|
||||
const [type, token] = authHeader.split(' ');
|
||||
return type === 'Bearer' && token ? token : null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user