swaf/src/auth/password/UserPasswordComponent.ts

40 lines
1.2 KiB
TypeScript
Raw Normal View History

import argon2, {argon2id} from "argon2";
import ModelComponent from "../../db/ModelComponent";
import User from "../models/User";
import Validator from "../../db/Validator";
export default class UserPasswordComponent extends ModelComponent<User> {
public static readonly PASSWORD_MIN_LENGTH = 12;
private password?: string = undefined;
public init(): void {
this.setValidation('password').acceptUndefined().maxLength(128);
}
public async setPassword(rawPassword: string, fieldName: string = 'password'): Promise<void> {
await new Validator<string>()
.defined()
.minLength(UserPasswordComponent.PASSWORD_MIN_LENGTH)
.maxLength(512)
.execute(fieldName, rawPassword, true);
this.password = await argon2.hash(rawPassword, {
timeCost: 10,
memoryCost: 65536,
parallelism: 4,
type: argon2id,
hashLength: 32,
});
}
public async verifyPassword(passwordGuess: string): Promise<boolean> {
if (!this.password || !passwordGuess) return false;
return await argon2.verify(this.password, passwordGuess);
}
public hasPassword(): boolean {
return typeof this.password === 'string';
}
}