34 lines
904 B
TypeScript
34 lines
904 B
TypeScript
import { hash, verify } from "@felix/bcrypt";
|
|
|
|
const DEFAULT_PASSWORD_LENGTH = 32;
|
|
|
|
class Password {
|
|
public generate(length: number = DEFAULT_PASSWORD_LENGTH): string {
|
|
return generateRandomString(length);
|
|
}
|
|
|
|
public async hash(password: string) {
|
|
return await hash(password);
|
|
}
|
|
|
|
public async verify(password: string, hash: string) {
|
|
return await verify(password, hash);
|
|
}
|
|
}
|
|
|
|
export const passwd = new Password();
|
|
|
|
export const generateRandomString = (length: number): string => {
|
|
const charset =
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
const charsetLength = charset.length;
|
|
const randomValues = new Uint8Array(length);
|
|
crypto.getRandomValues(randomValues);
|
|
|
|
let result = "";
|
|
for (let i = 0; i < length; i++) {
|
|
result += charset[randomValues[i] % charsetLength];
|
|
}
|
|
return result;
|
|
};
|