hash a password with bcriptjs

◾️ hash a password (※youtube lecture memo)

....
import * as bcrypt from 'bcryptjs';

@Injectable()
export class UsersService {
  constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

  async createUser(user: CreateUserDto) {
    const createdUser = new this.userModel({
      username: user.username,
      password: await bcrypt.hash(user.password, 12),
    });
    return await createdUser.save();
  }
...

◾️ compare password – get password hash info from db and compare with input

.....
async validateUser({ username, password }: CreateUserDto) {
    let isValid = false;
    try {
      const user = await this.usersService.findOne(username);
      if (user) {
        isValid = await bcrypt.compare(password, user.password);
      }
    } catch {
      console.log('EXCEPTION OCCURED');
    }

    return isValid;
  }
.....

◾️ package

npm install –save bcryptjs

npm install –save-dev @types/bcryptjs

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です