import Prisma from "@prisma/client"; const prisma = new Prisma.PrismaClient(); import { log } from "../logs.js"; async function login(req, res) { // Check password if (!req.body.password || req.body.password != process.env.AUTH_PASSWORD) { res.redirect("/login"); return; } // Create a new auth session const session = await prisma.session.create({ data: { // Expires after 14 days of inactivity validUntil: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14), }, }); res.cookie("session", session.token, { httpOnly: true, // Expire "never" expires: new Date(253402300000000), }); log("API / Auth", `New session: ${session.token}`); res.redirect("/"); } async function checkLogin(req, res, next) { // If AUTH_PASSWORD env variable is not present don't require any login if (!process.env.AUTH_PASSWORD) { next(); return; } // If no session cookie is set send 401 Unauthorized // so the app redirects to the login page if (!req.cookies.session) { res.sendStatus(401); return; } // Check the provided session cookie const session = await prisma.session.findUnique({ where: { token: req.cookies.session, }, }); // If no session is found also send 401 if (!session) { res.sendStatus(401); return; } // Renew session expiration date await prisma.session.update({ where: { token: session.token, }, data: { validUntil: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14), }, }); next(); } export default { login, checkLogin, }; // Clean up expired sessions every hour setInterval(async () => { const sessions = await prisma.session.findMany(); for (const session of sessions) { if (session.validUntil < new Date()) { log("API / Auth", `Removed expired session: ${session.token}`); await prisma.session.delete({ where: { token: session.token, }, }); } } }, 1000 * 60 * 60);