src/auth/user.repository.ts
Repository
Methods |
|
| Private Async hashPassword |
hashPassword(password: string, salt: string)
|
|
Defined in src/auth/user.repository.ts:39
|
|
Returns :
Promise<string>
|
| Async signUp | ||||||
signUp(authCredentialsDto: AuthCredentialDto)
|
||||||
|
Defined in src/auth/user.repository.ts:9
|
||||||
|
Parameters :
Returns :
Promise<void>
|
| Async validateUserPassword | ||||||
validateUserPassword(authCredentialsDto: AuthCredentialDto)
|
||||||
|
Defined in src/auth/user.repository.ts:28
|
||||||
|
Parameters :
Returns :
Promise<string>
|
import { Repository, EntityRepository } from 'typeorm';
import { User } from './user.entity';
import * as bcrypt from 'bcryptjs';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { InternalServerErrorException, ConflictException } from '@nestjs/common';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
async signUp(authCredentialsDto: AuthCredentialDto): Promise<void> {
const { username, password } = authCredentialsDto;
const user = new User();
user.username = username;
user.salt = await bcrypt.genSalt();
user.password = await this.hashPassword(password, user.salt);
try {
await user.save();
} catch (error) {
if (error.code === '23505') { // duplicate username
throw new ConflictException('Username already exists');
} else {
throw new InternalServerErrorException();
}
}
}
async validateUserPassword(authCredentialsDto: AuthCredentialDto): Promise<string> {
const { username, password } = authCredentialsDto;
const user = await this.findOne({ username });
if (user && await user.validatePassword(password)) {
return user.username;
} else {
return null;
}
}
private async hashPassword(password: string, salt: string): Promise<string> {
return bcrypt.hash(password, salt);
}
}