authentication

This commit is contained in:
Bastian Wagner
2024-09-13 21:14:09 +02:00
parent c00aad559d
commit b4a5f04505
65 changed files with 1140 additions and 77 deletions

View 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;
}
}