41 lines
994 B
TypeScript
41 lines
994 B
TypeScript
import bcrypt from 'bcrypt';
|
|
import type { IValueObject } from '@core/shared/domain';
|
|
|
|
export interface PasswordHashProps {
|
|
value: string;
|
|
}
|
|
|
|
/**
|
|
* Value Object: PasswordHash
|
|
*
|
|
* Wraps a bcrypt-hashed password string and provides verification.
|
|
*/
|
|
export class PasswordHash implements IValueObject<PasswordHashProps> {
|
|
public readonly props: PasswordHashProps;
|
|
|
|
private constructor(value: string) {
|
|
this.props = { value };
|
|
}
|
|
|
|
static async create(plain: string): Promise<PasswordHash> {
|
|
const saltRounds = 12;
|
|
const hash = await bcrypt.hash(plain, saltRounds);
|
|
return new PasswordHash(hash);
|
|
}
|
|
|
|
static fromHash(hash: string): PasswordHash {
|
|
return new PasswordHash(hash);
|
|
}
|
|
|
|
get value(): string {
|
|
return this.props.value;
|
|
}
|
|
|
|
async verify(plain: string): Promise<boolean> {
|
|
return bcrypt.compare(plain, this.props.value);
|
|
}
|
|
|
|
equals(other: IValueObject<PasswordHashProps>): boolean {
|
|
return this.props.value === other.props.value;
|
|
}
|
|
} |