-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat(auth): adds auth * fix(auth): should fix build
- Loading branch information
1 parent
823acd5
commit 98cbca9
Showing
15 changed files
with
898 additions
and
814 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,9 @@ | ||
{ | ||
"tabWidth": 2, | ||
"useTabs": false, | ||
"singleQuote": true, | ||
"trailingComma": "all", | ||
"semi": true | ||
"printWidth": 120, | ||
"endOfLine": "auto", | ||
"arrowParens": "avoid" | ||
} |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,28 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { AuthModule } from './auth/auth.module'; | ||
import { ConfigModule } from '@nestjs/config'; | ||
import * as Joi from 'joi'; | ||
import { AuthModule } from './common/auth/auth.module'; | ||
import { UsersModule } from './user/users.module'; | ||
|
||
@Module({ | ||
imports: [UsersModule, AuthModule], | ||
imports: [ | ||
ConfigModule.forRoot({ | ||
isGlobal: true, | ||
envFilePath: '.env', | ||
validationSchema: Joi.object({ | ||
NODE_ENV: Joi.string().valid('development', 'production', 'test').default('development'), | ||
DATABASE_URL: Joi.string().required(), | ||
JWT_SECRET: Joi.string().required(), | ||
JWT_EXPIRATION_TIME: Joi.string().required(), | ||
COOKIE_SECRET: Joi.string().required(), | ||
}), | ||
validationOptions: { | ||
allowUnknown: true, | ||
}, | ||
cache: true, | ||
}), | ||
UsersModule, | ||
AuthModule, | ||
], | ||
}) | ||
export class AppModule {} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { Body, Controller, Post, Res } from '@nestjs/common'; | ||
import { Response } from 'express'; | ||
import { AuthService } from './auth.service'; | ||
import { Public } from './public.decorator'; | ||
|
||
@Controller('auth') | ||
export class AuthController { | ||
constructor(private authService: AuthService) {} | ||
|
||
@Public() | ||
@Post('login') | ||
async login( | ||
@Res({ passthrough: true }) response: Response, | ||
@Body() request: { email: string; password: string }, | ||
): Promise<void> { | ||
response.cookie('access_token', await this.authService.login(request.email, request.password), { | ||
sameSite: 'lax', | ||
path: '/', | ||
signed: true, | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; | ||
import { ConfigService } from '@nestjs/config'; | ||
import { Reflector } from '@nestjs/core'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
import { ErrorCodes } from 'enums/error-codes.enum'; | ||
import { Request } from 'express'; | ||
|
||
@Injectable() | ||
export class AuthGuard implements CanActivate { | ||
constructor( | ||
private jwtService: JwtService, | ||
private reflector: Reflector, | ||
private configService: ConfigService, | ||
) {} | ||
|
||
async canActivate(context: ExecutionContext): Promise<boolean> { | ||
const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [context.getHandler(), context.getClass()]); | ||
if (isPublic) { | ||
return true; | ||
} | ||
const request = context.switchToHttp().getRequest(); | ||
const token = this.extractTokenFromHeader(request); | ||
if (!token) { | ||
throw new UnauthorizedException({ error: ErrorCodes.NOT_ALLOWED }); | ||
} | ||
try { | ||
const payload = await this.jwtService.verifyAsync<{ id: string; email: string }>(token, { | ||
secret: this.configService.get('JWT_SECRET'), | ||
}); | ||
request['userId'] = payload.id; | ||
} catch { | ||
throw new UnauthorizedException({ error: ErrorCodes.NOT_ALLOWED }); | ||
} | ||
return true; | ||
} | ||
|
||
private extractTokenFromHeader(request: Request): string | undefined { | ||
return request.signedCookies.access_token; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,29 @@ | ||
import { Logger, Module } from '@nestjs/common'; | ||
import { JwtModule } from '@nestjs/jwt'; | ||
import { JWT_SECRET } from '../constants/constants'; | ||
import { UsersModule } from '../user/users.module'; | ||
import { UsersModule } from 'src/user/users.module'; | ||
import { AuthController } from './auth.controller'; | ||
import { AuthService } from './auth.service'; | ||
import { AuthGuard } from './auth.guard'; | ||
import { APP_GUARD } from '@nestjs/core'; | ||
|
||
@Module({ | ||
imports: [ | ||
UsersModule, | ||
JwtModule.register({ | ||
global: true, | ||
secret: JWT_SECRET, | ||
signOptions: { expiresIn: '8h' }, | ||
secret: process.env.JWT_SECRET, | ||
signOptions: { expiresIn: process.env.JWT_EXPIRATION_TIME }, | ||
}), | ||
], | ||
controllers: [AuthController], | ||
providers: [AuthService, Logger], | ||
providers: [ | ||
AuthService, | ||
Logger, | ||
{ | ||
provide: APP_GUARD, | ||
useClass: AuthGuard, | ||
}, | ||
], | ||
exports: [AuthService], | ||
}) | ||
export class AuthModule {} |
25 changes: 8 additions & 17 deletions
25
src/auth/auth.service.ts → src/common/auth/auth.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,34 @@ | ||
import { | ||
Injectable, | ||
InternalServerErrorException, | ||
Logger, | ||
} from '@nestjs/common'; | ||
import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
import * as bcrypt from 'bcrypt'; | ||
import { ErrorCodes } from 'enums/error-codes.enum'; | ||
import { UsersService } from '../user/users.service'; | ||
import { UsersService } from 'src/user/users.service'; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor( | ||
private usersService: UsersService, | ||
private jwtservice: JwtService, | ||
private jwtService: JwtService, | ||
) {} | ||
|
||
private readonly logger = new Logger(AuthService.name); | ||
|
||
async login(email: string, pass: string): Promise<{ accessToken: string }> { | ||
async login(email: string, pass: string): Promise<string> { | ||
this.logger.log(`Attempting login for user with email: ${email}`); | ||
const user = await this.usersService.findUserByEmail(email); | ||
if (!user) { | ||
this.logger.error( | ||
`Login for user with email: ${email} failed, not found in database`, | ||
); | ||
this.logger.error(`Login for user with email: ${email} failed, not found in database`); | ||
throw new InternalServerErrorException({ | ||
error: ErrorCodes.WRONG_CREDENTIALS, | ||
}); | ||
} | ||
if (!(await bcrypt.compare(pass, user.password))) { | ||
this.logger.error( | ||
`Login for user with email: ${email} failed, invalid password`, | ||
); | ||
this.logger.error(`Login for user with email: ${email} failed, invalid password`); | ||
throw new InternalServerErrorException({ | ||
error: ErrorCodes.WRONG_CREDENTIALS, | ||
}); | ||
} | ||
const payload = { sub: user.id, email: user.email }; | ||
const accessToken = await this.jwtservice.signAsync(payload); | ||
return { accessToken }; | ||
const payload = { id: user.id, email: user.email }; | ||
return this.jwtService.signAsync(payload); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { createParamDecorator, ExecutionContext } from '@nestjs/common'; | ||
import { Request } from 'express'; | ||
|
||
/** | ||
* Decorator to get the current user id from the request Only work on protected routes | ||
* @param jwtService has to be explicitly passed in because it is not injectable | ||
* @param ctx gets set by NestJS | ||
* @returns the user id of the user that made the request | ||
*/ | ||
export const CurrentUserId = createParamDecorator((data: string, ctx: ExecutionContext) => { | ||
const req: Request = ctx.switchToHttp().getRequest(); | ||
return req['userId']; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
import { CustomDecorator, SetMetadata } from '@nestjs/common'; | ||
|
||
export const IS_PUBLIC_KEY = 'isPublic'; | ||
export const Public = (): CustomDecorator<string> => SetMetadata(IS_PUBLIC_KEY, true); |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.