File

src/auth/user.repository.ts

Extends

Repository

Index

Methods

Methods

Private Async hashPassword
hashPassword(password: string, salt: string)
Parameters :
Name Type Optional
password string No
salt string No
Returns : Promise<string>
Async signUp
signUp(authCredentialsDto: AuthCredentialDto)
Parameters :
Name Type Optional
authCredentialsDto AuthCredentialDto No
Returns : Promise<void>
Async validateUserPassword
validateUserPassword(authCredentialsDto: AuthCredentialDto)
Parameters :
Name Type Optional
authCredentialsDto AuthCredentialDto No
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);
      }
}

result-matching ""

    No results matching ""