-
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.
Merge pull request #9 from huongnt-2545/part9_authentication
Part9 authentication
- Loading branch information
Showing
17 changed files
with
1,589 additions
and
38 deletions.
There are no files selected for viewing
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
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 } from '@nestjs/common'; | ||
import { AuthService } from './auth.service'; | ||
import { AuthCredentialsDto } from './dto/auth-credentials.dto'; | ||
import { GetUser } from './get-user.decorator'; | ||
import { User } from './user.entity'; | ||
|
||
@Controller('auth') | ||
export class AuthController { | ||
constructor(private authService: AuthService) {} | ||
|
||
@Post('/signup') | ||
signUp(@Body() authCredentialsDto: AuthCredentialsDto): Promise<void> { | ||
return this.authService.createUser(authCredentialsDto); | ||
} | ||
|
||
@Post('/signin') | ||
signIn( | ||
@Body() authCredentialsDto: AuthCredentialsDto, | ||
): Promise<{ accessToken: string }> { | ||
return this.authService.validateUserPassword(authCredentialsDto); | ||
} | ||
} |
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,30 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { JwtModule } from '@nestjs/jwt'; | ||
import { PassportModule } from '@nestjs/passport'; | ||
import { TypeOrmModule } from '@nestjs/typeorm'; | ||
import { DatabaseModule } from '../database.module'; | ||
import { AuthController } from './auth.controller'; | ||
import { AuthService } from './auth.service'; | ||
import { JwtStrategy } from './jwt.strategy'; | ||
import { userProviders } from './user.provider'; | ||
// import { UserRepository } from './user.repository'; | ||
|
||
@Module({ | ||
// imports: [TypeOrmModule.forFeature([UserRepository])], | ||
imports: [ | ||
DatabaseModule, | ||
PassportModule.register({ | ||
defaultStrategy: 'jwt', | ||
}), | ||
JwtModule.register({ | ||
secret: 'topSecret51', | ||
signOptions: { | ||
expiresIn: 3600, | ||
}, | ||
}), | ||
], | ||
controllers: [AuthController], | ||
providers: [...userProviders, AuthService, JwtStrategy], | ||
exports: [JwtStrategy, PassportModule], | ||
}) | ||
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,65 @@ | ||
import { | ||
ConflictException, | ||
Inject, | ||
Injectable, | ||
InternalServerErrorException, | ||
UnauthorizedException, | ||
} from '@nestjs/common'; | ||
import { Repository } from 'typeorm'; | ||
import * as bcrypt from 'bcrypt'; | ||
import { AuthCredentialsDto } from './dto/auth-credentials.dto'; | ||
import { User } from './user.entity'; | ||
import { hashPassword } from '../utils/common'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
import { JwtPayload } from './jwt-payload.interface'; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor( | ||
@Inject('USER_REPOSITORY') | ||
private userRepository: Repository<User>, | ||
private jwtService: JwtService, | ||
) {} | ||
|
||
async createUser(authCredentialsDto: AuthCredentialsDto): Promise<void> { | ||
try { | ||
const { username, password } = authCredentialsDto; | ||
const salt = await bcrypt.genSalt(); | ||
|
||
const user = new User(); | ||
user.username = username; | ||
user.salt = salt; | ||
user.password = await hashPassword(password, salt); | ||
|
||
await user.save(); | ||
} catch (err) { | ||
if (err.code === 23505) { | ||
//duplicate username | ||
throw new ConflictException('Username already exists'); | ||
} else { | ||
throw new InternalServerErrorException(); | ||
} | ||
} | ||
} | ||
|
||
async validateUserPassword( | ||
authCredentialsDto: AuthCredentialsDto, | ||
): Promise<{ accessToken: string }> { | ||
const { username, password } = authCredentialsDto; | ||
const user = await this.userRepository.findOne({ username }); | ||
let existUsername = null; | ||
|
||
if (user && (await user.validatePassword(password))) { | ||
existUsername = user.username; | ||
} | ||
|
||
if (!existUsername) { | ||
throw new UnauthorizedException('Invalid user credentials'); | ||
} | ||
|
||
const payload: JwtPayload = { username }; | ||
const accessToken = await this.jwtService.sign(payload); | ||
|
||
return { accessToken }; | ||
} | ||
} |
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 { IsString, Matches, MaxLength, MinLength } from 'class-validator'; | ||
import { PASSWORD_PATTERN } from '../../utils/constants'; | ||
|
||
export class AuthCredentialsDto { | ||
@IsString() | ||
@MinLength(6) | ||
@MaxLength(20) | ||
username: string; | ||
|
||
@IsString() | ||
@MinLength(6) | ||
@MaxLength(20) | ||
@Matches(PASSWORD_PATTERN, { message: 'Password too weak' }) | ||
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,9 @@ | ||
import { createParamDecorator, ExecutionContext } from '@nestjs/common'; | ||
import { User } from './user.entity'; | ||
|
||
export const GetUser = createParamDecorator( | ||
(data, ctx: ExecutionContext): User => { | ||
const req = ctx.switchToHttp().getRequest(); | ||
return req.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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export interface JwtPayload { | ||
username: 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,30 @@ | ||
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'; | ||
import { PassportStrategy } from '@nestjs/passport'; | ||
import { Strategy, ExtractJwt } from 'passport-jwt'; | ||
import { Repository } from 'typeorm'; | ||
import { JwtPayload } from './jwt-payload.interface'; | ||
import { User } from './user.entity'; | ||
|
||
@Injectable() | ||
export class JwtStrategy extends PassportStrategy(Strategy) { | ||
constructor( | ||
@Inject('USER_REPOSITORY') | ||
private userRepository: Repository<User>, | ||
) { | ||
super({ | ||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
secretOrKey: 'topSecret51', | ||
}); | ||
} | ||
|
||
async validate(payload: JwtPayload): Promise<User> { | ||
const { username } = payload; | ||
const user = await this.userRepository.findOne({ username }); | ||
|
||
if (!user) { | ||
throw new UnauthorizedException('Invalid user token'); | ||
} | ||
|
||
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { | ||
BaseEntity, | ||
Column, | ||
Entity, | ||
PrimaryGeneratedColumn, | ||
Unique, | ||
} from 'typeorm'; | ||
import * as bcrypt from 'bcrypt'; | ||
import { hashPassword } from '../utils/common'; | ||
|
||
@Entity() | ||
@Unique(['username']) | ||
export class User extends BaseEntity { | ||
@PrimaryGeneratedColumn() | ||
id: number; | ||
|
||
@Column() | ||
username: string; | ||
|
||
@Column() | ||
password: string; | ||
|
||
@Column() | ||
salt: string; | ||
|
||
async validatePassword(password: string): Promise<boolean> { | ||
const hash = await bcrypt.hash(password, this.salt); | ||
|
||
return hash === this.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,10 @@ | ||
import { Connection } from 'typeorm'; | ||
import { User } from './user.entity'; | ||
|
||
export const userProviders = [ | ||
{ | ||
provide: 'USER_REPOSITORY', | ||
useFactory: (connection: Connection) => connection.getRepository(User), | ||
inject: ['DATABASE_CONNECTION'], | ||
}, | ||
]; |
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,8 @@ | ||
import * as bcrypt from 'bcrypt'; | ||
|
||
export const hashPassword = async ( | ||
password: string, | ||
salt: string, | ||
): Promise<string> => { | ||
return bcrypt.hash(password, salt); | ||
}; |
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 @@ | ||
const PASSWORD_PATTERN: RegExp = | ||
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{6,}$/; | ||
|
||
export { PASSWORD_PATTERN }; |
Oops, something went wrong.