move auth utils

This commit is contained in:
Milo Schwartz
2024-10-05 22:31:30 -04:00
parent 2312cdeea7
commit d9022c5377
9 changed files with 12 additions and 12 deletions

59
server/auth/2fa.ts Normal file
View File

@@ -0,0 +1,59 @@
import { verify } from "@node-rs/argon2";
import db from "@server/db";
import { twoFactorBackupCodes } from "@server/db/schema";
import { eq } from "drizzle-orm";
import { decodeHex } from "oslo/encoding";
import { TOTPController } from "oslo/otp";
export async function verifyTotpCode(
code: string,
secret: string,
userId: string,
): Promise<boolean> {
if (code.length !== 6) {
const validBackupCode = await verifyBackUpCode(code, userId);
return validBackupCode;
} else {
const validOTP = await new TOTPController().verify(
code,
decodeHex(secret),
);
return validOTP;
}
}
export async function verifyBackUpCode(
code: string,
userId: string,
): Promise<boolean> {
const allHashed = await db
.select()
.from(twoFactorBackupCodes)
.where(eq(twoFactorBackupCodes.userId, userId));
if (!allHashed || !allHashed.length) {
return false;
}
let validId;
for (const hashedCode of allHashed) {
const validCode = await verify(hashedCode.codeHash, code, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
if (validCode) {
validId = hashedCode.id;
}
}
if (validId) {
await db
.delete(twoFactorBackupCodes)
.where(eq(twoFactorBackupCodes.id, validId));
}
return validId ? true : false;
}

25
server/auth/password.ts Normal file
View File

@@ -0,0 +1,25 @@
import { hash, verify } from "@node-rs/argon2";
export async function verifyPassword(
password: string,
hash: string,
): Promise<boolean> {
const validPassword = await verify(hash, password, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
return validPassword;
}
export async function hashPassword(password: string): Promise<string> {
const passwordHash = await hash(password, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
return passwordHash;
}

View File

@@ -0,0 +1,13 @@
import z from "zod";
export const passwordSchema = z
.string()
.min(8, { message: "Password must be at least 8 characters long" })
.max(64, { message: "Password must be at most 64 characters long" })
.regex(/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).*$/, {
message: `Your password must meet the following conditions:
- At least one uppercase English letter.
- At least one lowercase English letter.
- At least one digit.
- At least one special character.`,
});