Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add user check in validate method rtStrategy and atStrategy #8

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ export class AuthController {
@HttpCode(HttpStatus.OK)
refreshTokens(
@GetCurrentUserId() userId: number,
@GetCurrentUser('refreshToken') refreshToken: string,
@GetCurrentUser('email') email: string,
): Promise<Tokens> {
return this.authService.refreshTokens(userId, refreshToken);
return this.authService.refreshTokens(userId, email);
}
}
3 changes: 2 additions & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { AtStrategy, RtStrategy } from './strategies';
import { PrismaModule } from '../prisma/prisma.module';

@Module({
imports: [JwtModule.register({})],
imports: [JwtModule.register({}), PrismaModule],
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PrismaModule is Global, you don't need to add it here

controllers: [AuthController],
providers: [AuthService, AtStrategy, RtStrategy],
})
Expand Down
18 changes: 4 additions & 14 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
import * as argon from 'argon2';
import { PrismaService } from '../prisma/prisma.service';

import { PrismaService } from '../prisma/prisma.service';
import { AuthDto } from './dto';
import { JwtPayload, Tokens } from './types';

Expand Down Expand Up @@ -74,19 +74,9 @@ export class AuthService {
return true;
}

async refreshTokens(userId: number, rt: string): Promise<Tokens> {
const user = await this.prisma.user.findUnique({
where: {
id: userId,
},
});
if (!user || !user.hashedRt) throw new ForbiddenException('Access Denied');

const rtMatches = await argon.verify(user.hashedRt, rt);
if (!rtMatches) throw new ForbiddenException('Access Denied');

const tokens = await this.getTokens(user.id, user.email);
await this.updateRtHash(user.id, tokens.refresh_token);
async refreshTokens(userId: number, email:string): Promise<Tokens> {
const tokens = await this.getTokens(userId, email);
await this.updateRtHash(userId, tokens.refresh_token);

return tokens;
}
Expand Down
14 changes: 11 additions & 3 deletions src/auth/strategies/at.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
import { Injectable } from '@nestjs/common';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PrismaService } from '../../prisma/prisma.service';
import { JwtPayload } from '../types';

@Injectable()
export class AtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(config: ConfigService) {
constructor(config: ConfigService, private prisma: PrismaService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get<string>('AT_SECRET'),
});
}

validate(payload: JwtPayload) {
async validate(payload: JwtPayload) {
const user = await this.prisma.user.findUnique({
where: {
id: payload.sub,
},
});
if (!user || !user.hashedRt) throw new ForbiddenException('Access Denied');

return payload;
}
}
16 changes: 14 additions & 2 deletions src/auth/strategies/rt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,40 @@
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Request } from 'express';
import * as argon from 'argon2';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtPayload, JwtPayloadWithRt } from '../types';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class RtStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
constructor(config: ConfigService) {
constructor(config: ConfigService, private prisma: PrismaService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get<string>('RT_SECRET'),
passReqToCallback: true,
});
}

validate(req: Request, payload: JwtPayload): JwtPayloadWithRt {
async validate(req: Request, payload: JwtPayload): Promise<JwtPayloadWithRt> {
const refreshToken = req
?.get('authorization')
?.replace('Bearer', '')
.trim();

if (!refreshToken) throw new ForbiddenException('Refresh token malformed');

const user = await this.prisma.user.findUnique({
where: {
id: payload.sub,
},
});
if (!user || !user.hashedRt) throw new ForbiddenException('Access Denied');

const rtMatches = await argon.verify(user.hashedRt, refreshToken);
if (!rtMatches) throw new ForbiddenException('Access Denied');

return {
...payload,
refreshToken,
Expand Down