Add services and auth

This commit is contained in:
Aslan 2025-12-23 17:45:51 -05:00
parent 9b0b5dc040
commit 5dec454afb
46 changed files with 900 additions and 31 deletions

72
src/services/auth/auth.ts Normal file
View file

@ -0,0 +1,72 @@
import argon2 from "argon2";
import jwt from "jsonwebtoken";
import type { User, Session } from "../../generated/prisma/client.js";
import { getDB } from "../../store/store.js";
import type { IUserLogin, IUserRegistration } from "./types.js";
import { getJwtSecret } from "../../helpers.js";
const registerUser = async (
registration: IUserRegistration,
): Promise<User | null> => {
const existingUser = await getDB().user.findUnique({
where: { username: registration.username },
});
if (existingUser) {
return null;
}
const passwordHash = await hashPassword(registration.password);
let newUser: User | null = null;
try {
newUser = await getDB().user.create({
data: {
username: registration.username,
passwordHash: passwordHash,
email: registration.email ?? null,
},
});
} catch {
return null;
}
return newUser;
};
const loginUser = async (login: IUserLogin): Promise<Session | null> => {
const user = await getDB().user.findUnique({
where: { username: login.username },
});
const passwordCorrect = await argon2.verify(
user?.passwordHash ?? "",
login.password,
);
if (!user || !passwordCorrect) {
return null;
}
return await getDB().session.create({
data: {
token: createToken(user.id),
userId: user.id,
},
});
};
const hashPassword = async (password: string): Promise<string> => {
return await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 2 ** 16,
timeCost: 4,
parallelism: 1,
});
};
const createToken = (userId: string) => {
return jwt.sign({ sub: userId }, getJwtSecret());
};
export { registerUser, loginUser, hashPassword };