Skip to content

Commit

Permalink
fix(auth): process env reading in other module & refactored jwt guard
Browse files Browse the repository at this point in the history
  • Loading branch information
KostaD02 committed Aug 18, 2023
1 parent b32aa8d commit 3b57162
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 4 deletions.
3 changes: 3 additions & 0 deletions src/enums/exceptions.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,7 @@ export enum GlobalExceptionKeys {
export enum AuthExpectionKeys {
IncorrectEmailOrPassword = 'errors.incorrect_email_or_password',
EmailInUse = 'errors.email_in_use',
TokenInvalid = 'errors.token_invalid',
TokenExpired = 'errors.token_expired',
TokenNotFound = 'errors.token_not_found',
}
52 changes: 49 additions & 3 deletions src/modules/user/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,51 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ExceptionService } from './../../../../shared/exception.service';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { AuthExpectionKeys, ExceptionStatusKeys } from 'src/enums';

@Injectable()
export class JwtGuard extends AuthGuard('jwt') {}
export class JwtGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private exceptionService: ExceptionService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
this.exceptionService.throwError(
ExceptionStatusKeys.BadRequest,
'Token not found',
AuthExpectionKeys.TokenNotFound,
);
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: `${process.env.JWT_SECRET}`,
});
request['user'] = payload;
} catch (err) {
this.exceptionService.throwError(
ExceptionStatusKeys.BadRequest,
'Invalid token',
AuthExpectionKeys.TokenInvalid,
);
}
return true;
}

private extractTokenFromHeader(request: Request): string | undefined {
const authHeader = request.headers['authorization'];
const accessTokenCookie = request.cookies.access_token;
let accessToken: string;

if (authHeader && authHeader.startsWith('Bearer ')) {
accessToken = authHeader.substring(7);
} else if (accessTokenCookie) {
accessToken = accessTokenCookie;
}
return accessToken;
}
}
4 changes: 3 additions & 1 deletion src/modules/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { EncryptionService, ExceptionService } from 'src/shared';
import { AuthController, AuthService } from './auth';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from 'src/schemas';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy, LocalStrategy } from './auth/strategies';
import { RefreshJwtGuard } from './auth/guards';

@Module({
imports: [
ConfigModule.forRoot(),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
JwtModule.register({
secret: `${process.env.JWT_SECRET}`,
Expand Down

0 comments on commit 3b57162

Please sign in to comment.