From af2108992455472789434b3fb41e45a2c279fb8d Mon Sep 17 00:00:00 2001 From: wumibals Date: Sat, 21 Feb 2026 08:46:46 +0100 Subject: [PATCH] auth strategy --- .../auth/decorators/current-user.decorator.ts | 9 ++++++ backend/src/auth/strategies/jwt.strategy.ts | 31 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 backend/src/auth/decorators/current-user.decorator.ts create mode 100644 backend/src/auth/strategies/jwt.strategy.ts diff --git a/backend/src/auth/decorators/current-user.decorator.ts b/backend/src/auth/decorators/current-user.decorator.ts new file mode 100644 index 00000000..3c9ed389 --- /dev/null +++ b/backend/src/auth/decorators/current-user.decorator.ts @@ -0,0 +1,9 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import { User } from '../../users/user.entity'; + +export const CurrentUser = createParamDecorator( + (_data: unknown, ctx: ExecutionContext): User => { + const request = ctx.switchToHttp().getRequest(); + return request.user; + }, +); diff --git a/backend/src/auth/strategies/jwt.strategy.ts b/backend/src/auth/strategies/jwt.strategy.ts new file mode 100644 index 00000000..d0796fc0 --- /dev/null +++ b/backend/src/auth/strategies/jwt.strategy.ts @@ -0,0 +1,31 @@ +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { PassportStrategy } from '@nestjs/passport'; +import { ExtractJwt, Strategy } from 'passport-jwt'; +import { ConfigService } from '@nestjs/config'; +import { UsersService } from '../../users/users.service'; + +export interface JwtPayload { + sub: string; + email: string; + role: string; +} + +@Injectable() +export class JwtStrategy extends PassportStrategy(Strategy) { + constructor( + private readonly configService: ConfigService, + private readonly usersService: UsersService, + ) { + super({ + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + ignoreExpiration: false, + secretOrKey: configService.get('JWT_SECRET', 'change-me-in-env'), + }); + } + + async validate(payload: JwtPayload) { + const user = await this.usersService.findById(payload.sub); + if (!user) throw new UnauthorizedException(); + return user; + } +}