Skip to content

Commit af21089

Browse files
committed
auth strategy
1 parent b1c678b commit af21089

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
2+
import { User } from '../../users/user.entity';
3+
4+
export const CurrentUser = createParamDecorator(
5+
(_data: unknown, ctx: ExecutionContext): User => {
6+
const request = ctx.switchToHttp().getRequest();
7+
return request.user;
8+
},
9+
);
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { Injectable, UnauthorizedException } from '@nestjs/common';
2+
import { PassportStrategy } from '@nestjs/passport';
3+
import { ExtractJwt, Strategy } from 'passport-jwt';
4+
import { ConfigService } from '@nestjs/config';
5+
import { UsersService } from '../../users/users.service';
6+
7+
export interface JwtPayload {
8+
sub: string;
9+
email: string;
10+
role: string;
11+
}
12+
13+
@Injectable()
14+
export class JwtStrategy extends PassportStrategy(Strategy) {
15+
constructor(
16+
private readonly configService: ConfigService,
17+
private readonly usersService: UsersService,
18+
) {
19+
super({
20+
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
21+
ignoreExpiration: false,
22+
secretOrKey: configService.get<string>('JWT_SECRET', 'change-me-in-env'),
23+
});
24+
}
25+
26+
async validate(payload: JwtPayload) {
27+
const user = await this.usersService.findById(payload.sub);
28+
if (!user) throw new UnauthorizedException();
29+
return user;
30+
}
31+
}

0 commit comments

Comments
 (0)