|
| 1 | +import * as bcrypt from 'bcrypt'; |
1 | 2 | import { Exclude } from 'class-transformer'; |
2 | 3 | import { IsNotEmpty } from 'class-validator'; |
3 | | -import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; |
| 4 | +import { BeforeInsert, Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; |
4 | 5 |
|
5 | 6 | import { Pet } from './Pet'; |
6 | 7 |
|
7 | 8 | @Entity() |
8 | 9 | export class User { |
9 | 10 |
|
| 11 | + public static hashPassword(password: string): Promise<string> { |
| 12 | + return new Promise((resolve, reject) => { |
| 13 | + bcrypt.hash(password, 10, (err, hash) => { |
| 14 | + if (err) { |
| 15 | + return reject(err); |
| 16 | + } |
| 17 | + resolve(hash); |
| 18 | + }); |
| 19 | + }); |
| 20 | + } |
| 21 | + |
| 22 | + public static comparePassword(user: User, password: string): Promise<boolean> { |
| 23 | + return new Promise((resolve, reject) => { |
| 24 | + bcrypt.compare(password, user.password, (err, res) => { |
| 25 | + resolve(res === true); |
| 26 | + }); |
| 27 | + }); |
| 28 | + } |
| 29 | + |
10 | 30 | @PrimaryGeneratedColumn('uuid') |
11 | 31 | public id: string; |
12 | 32 |
|
@@ -38,8 +58,9 @@ export class User { |
38 | 58 | return `${this.firstName} ${this.lastName} (${this.email})`; |
39 | 59 | } |
40 | 60 |
|
41 | | - public toBase64(): string { |
42 | | - return Buffer.from(`${this.username}:${this.password}`).toString('base64'); |
| 61 | + @BeforeInsert() |
| 62 | + public async hashPassword(): Promise<void> { |
| 63 | + this.password = await User.hashPassword(this.password); |
43 | 64 | } |
44 | 65 |
|
45 | 66 | } |
0 commit comments