Rework authentication
This commit is contained in:
parent
a85330e8cf
commit
c07d33bcc9
17 changed files with 317 additions and 128 deletions
|
|
@ -1,10 +1,12 @@
|
|||
import argon2 from "argon2";
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
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";
|
||||
import { getJwtSecret } from "./helpers.js";
|
||||
|
||||
const registerUser = async (
|
||||
registration: IUserRegistration,
|
||||
|
|
@ -50,11 +52,7 @@ const loginUser = async (login: IUserLogin): Promise<Session | null> => {
|
|||
return null;
|
||||
}
|
||||
|
||||
const passwordCorrect = await argon2.verify(
|
||||
user.passwordHash,
|
||||
login.password,
|
||||
);
|
||||
if (!passwordCorrect) {
|
||||
if (!(await verifyPassword(user.passwordHash, login.password))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -69,23 +67,30 @@ const loginUser = async (login: IUserLogin): Promise<Session | null> => {
|
|||
|
||||
return await getDB().session.create({
|
||||
data: {
|
||||
token: createToken(user.id),
|
||||
cookie: createSessionCookie(),
|
||||
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 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)];
|
||||
};
|
||||
|
||||
const createToken = (userId: string) => {
|
||||
return jwt.sign({ sub: userId }, getJwtSecret());
|
||||
};
|
||||
|
||||
export { registerUser, loginUser, hashPassword };
|
||||
export { registerUser, loginUser, refreshSession };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue