tether/src/services/auth/auth.ts
2026-01-01 17:06:31 +01:00

96 lines
2.2 KiB
TypeScript

import type { User, Session } from "../../generated/prisma/client.js";
import { getDB } from "../../store/store.js";
import {
createSessionCookie,
createToken,
hashPassword,
verifyPassword,
} from "./helpers.js";
import type { IUserLogin, IUserRegistration } from "./types.js";
const registerUser = async (
registration: IUserRegistration,
): Promise<User | null> => {
const existingUserUsername = await getDB().user.findUnique({
where: { username: registration.username },
});
if (existingUserUsername) {
return null;
}
if (registration.email) {
const existingUserEmail = await getDB().user.findUnique({
where: { email: registration.email },
});
if (existingUserEmail) {
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 },
});
if (!user || !user.passwordHash) {
return null;
}
if (!(await verifyPassword(user.passwordHash, login.password))) {
return null;
}
await getDB().user.update({
data: {
lastLogin: new Date(),
},
where: {
id: user.id,
},
});
return await getDB().session.create({
data: {
cookie: createSessionCookie(),
userId: user.id,
},
});
};
const refreshSession = async (
cookie: string | undefined,
): Promise<[Session, string] | null> => {
if (!cookie) {
return null;
}
const session = await getDB().session.findFirst({
where: {
cookie: cookie,
},
});
if (!session) {
return null;
}
return [session, createToken(session.id)];
};
export { registerUser, loginUser, refreshSession };