-
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.
[backend] Implement POST /auth/login (#30)
* [backend] Add auth module and passport to backend - `docker compose exec backend yarn run nest generate resource` - `docker compose exec backend yarn add @nestjs/passport passport @nestjs/jwt passport-jwt` - `docker compose exec backend yarn add -D @types/passport-jwt` * [backend] Implement auth.module * [backend] Implement auth.service - Create a new file `backend/src/auth/dto/login.dto.ts` - Create a new file `backend/src/auth/entity/auth.entity.ts` * [backend] Implement POST /auth/login * [backend] Add JwtStrategy as a provider - Export the UserService from the UserModule * [backend] Implement JwtAuthGuard * [backend] Add bcrypt and @types/bcrypt - `docker compose exec backend yarn add bcrypt` - `docker compose exec backend yarn add -d @types/bcrypt` * [backend] Use bcrypt to compare the password in the AuthService * [backend] Add seed script * [ci] Add BACKEND_JWT_SECRET to .env file
- Loading branch information
Showing
23 changed files
with
880 additions
and
8 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
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
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 |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { PrismaClient } from '@prisma/client'; | ||
import * as bcrypt from 'bcrypt'; | ||
|
||
// Initialize Prisma client | ||
const prisma = new PrismaClient(); | ||
|
||
const roundsOfHashing = 10; | ||
|
||
async function main() { | ||
const passwordSusami = await bcrypt.hash('password-susami', roundsOfHashing); | ||
const passwordThara = await bcrypt.hash('password-thara', roundsOfHashing); | ||
const passwordKakiba = await bcrypt.hash('password-kakiba', roundsOfHashing); | ||
const passwordShongou = await bcrypt.hash( | ||
'password-shongou', | ||
roundsOfHashing, | ||
); | ||
|
||
const user1 = await prisma.user.upsert({ | ||
where: { email: '[email protected]' }, | ||
update: {}, | ||
create: { | ||
email: '[email protected]', | ||
name: 'Susami', | ||
password: passwordSusami, | ||
}, | ||
}); | ||
|
||
const user2 = await prisma.user.upsert({ | ||
where: { email: '[email protected]' }, | ||
update: {}, | ||
create: { | ||
email: '[email protected]', | ||
name: 'Thara', | ||
password: passwordThara, | ||
}, | ||
}); | ||
|
||
const user3 = await prisma.user.upsert({ | ||
where: { email: '[email protected]' }, | ||
update: {}, | ||
create: { | ||
email: '[email protected]', | ||
name: 'Kakiba', | ||
password: passwordKakiba, | ||
}, | ||
}); | ||
|
||
const user4 = await prisma.user.upsert({ | ||
where: { email: '[email protected]' }, | ||
update: {}, | ||
create: { | ||
email: '[email protected]', | ||
name: 'Shongou', | ||
password: passwordShongou, | ||
}, | ||
}); | ||
|
||
console.log({ user1, user2, user3, user4 }); | ||
} | ||
|
||
main() | ||
.catch((e) => { | ||
console.error(e); | ||
process.exit(1); | ||
}) | ||
.finally(async () => { | ||
// close Prisma Client at the end | ||
await prisma.$disconnect(); | ||
}); |
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 |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { Test, TestingModule } from '@nestjs/testing'; | ||
import { AuthController } from './auth.controller'; | ||
import { AuthService } from './auth.service'; | ||
import { PrismaService } from 'src/prisma/prisma.service'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
|
||
describe('AuthController', () => { | ||
let controller: AuthController; | ||
|
||
beforeEach(async () => { | ||
const module: TestingModule = await Test.createTestingModule({ | ||
controllers: [AuthController], | ||
providers: [AuthService, PrismaService, JwtService], | ||
}).compile(); | ||
|
||
controller = module.get<AuthController>(AuthController); | ||
}); | ||
|
||
it('should be defined', () => { | ||
expect(controller).toBeDefined(); | ||
}); | ||
}); |
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,17 @@ | ||
import { Body, Controller, Post } from '@nestjs/common'; | ||
import { AuthService } from './auth.service'; | ||
import { ApiOkResponse, ApiTags } from '@nestjs/swagger'; | ||
import { AuthEntity } from './entity/auth.entity'; | ||
import { LoginDto } from './dto/login.dto'; | ||
|
||
@Controller('auth') | ||
@ApiTags('auth') | ||
export class AuthController { | ||
constructor(private readonly authService: AuthService) {} | ||
|
||
@Post('login') | ||
@ApiOkResponse({ type: AuthEntity }) | ||
login(@Body() { email, password }: LoginDto): Promise<AuthEntity> { | ||
return this.authService.login(email, password); | ||
} | ||
} |
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,27 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { AuthService } from './auth.service'; | ||
import { AuthController } from './auth.controller'; | ||
import { PassportModule } from '@nestjs/passport'; | ||
import { JwtModule } from '@nestjs/jwt'; | ||
import { PrismaModule } from 'src/prisma/prisma.module'; | ||
import { UserModule } from 'src/user/user.module'; | ||
import { JwtStrategy } from './jwt.strategy'; | ||
|
||
export const jwtConstants = { | ||
secret: process.env.JWT_SECRET, | ||
}; | ||
|
||
@Module({ | ||
imports: [ | ||
PrismaModule, | ||
PassportModule, | ||
JwtModule.register({ | ||
secret: jwtConstants.secret, | ||
signOptions: { expiresIn: '30m' }, // 30 minutes | ||
}), | ||
UserModule, | ||
], | ||
controllers: [AuthController], | ||
providers: [AuthService, JwtStrategy], | ||
}) | ||
export class AuthModule {} |
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,20 @@ | ||
import { Test, TestingModule } from '@nestjs/testing'; | ||
import { AuthService } from './auth.service'; | ||
import { PrismaService } from 'src/prisma/prisma.service'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
|
||
describe('AuthService', () => { | ||
let service: AuthService; | ||
|
||
beforeEach(async () => { | ||
const module: TestingModule = await Test.createTestingModule({ | ||
providers: [AuthService, PrismaService, JwtService], | ||
}).compile(); | ||
|
||
service = module.get<AuthService>(AuthService); | ||
}); | ||
|
||
it('should be defined', () => { | ||
expect(service).toBeDefined(); | ||
}); | ||
}); |
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,35 @@ | ||
import { | ||
Injectable, | ||
NotFoundException, | ||
UnauthorizedException, | ||
} from '@nestjs/common'; | ||
import { PrismaService } from 'src/prisma/prisma.service'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
import { AuthEntity } from './entity/auth.entity'; | ||
import * as bcrypt from 'bcrypt'; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor( | ||
private prisma: PrismaService, | ||
private jwtService: JwtService, | ||
) {} | ||
|
||
async login(email: string, password: string): Promise<AuthEntity> { | ||
const user = await this.prisma.user.findUnique({ where: { email } }); | ||
|
||
if (!user) { | ||
throw new NotFoundException(`No user found for email: ${email}`); | ||
} | ||
|
||
const isPasswordValid = await bcrypt.compare(password, user.password); | ||
|
||
if (!isPasswordValid) { | ||
throw new UnauthorizedException('Invalid password'); | ||
} | ||
|
||
return { | ||
accessToken: this.jwtService.sign({ userId: user.id }), | ||
}; | ||
} | ||
} |
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,15 @@ | ||
import { ApiProperty } from '@nestjs/swagger'; | ||
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator'; | ||
|
||
export class LoginDto { | ||
@IsEmail() | ||
@IsNotEmpty() | ||
@ApiProperty() | ||
email: string; | ||
|
||
@IsString() | ||
@IsNotEmpty() | ||
@MinLength(6) | ||
@ApiProperty() | ||
password: string; | ||
} |
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,6 @@ | ||
import { ApiProperty } from '@nestjs/swagger'; | ||
|
||
export class AuthEntity { | ||
@ApiProperty() | ||
accessToken: string; | ||
} |
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,5 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
import { AuthGuard } from '@nestjs/passport'; | ||
|
||
@Injectable() | ||
export class JwtAuthGuard extends AuthGuard('jwt') {} |
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,25 @@ | ||
import { Injectable, UnauthorizedException } from '@nestjs/common'; | ||
import { PassportStrategy } from '@nestjs/passport'; | ||
import { Strategy, ExtractJwt } from 'passport-jwt'; | ||
import { jwtConstants } from './auth.module'; | ||
import { UserService } from 'src/user/user.service'; | ||
|
||
@Injectable() | ||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { | ||
constructor(private userService: UserService) { | ||
super({ | ||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
secretOrKey: jwtConstants.secret, | ||
}); | ||
} | ||
|
||
async validate(payload: { userId: number }) { | ||
const user = await this.userService.findOne(payload.userId); | ||
|
||
if (!user) { | ||
throw new UnauthorizedException(); | ||
} | ||
|
||
return user; | ||
} | ||
} |
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.