FBLA25/src/routes/signin/+page.server.ts
drake be83b7570d
All checks were successful
ci / docker_image (push) Successful in 1m32s
ci / deploy (push) Successful in 16s
dev
2025-01-26 19:12:15 -06:00

53 lines
1.5 KiB
TypeScript

import { checkUserCreds, createUser, updateLastSignin } from '$lib/db/index.server';
import { fail, redirect, type Actions, type Cookies } from '@sveltejs/kit';
import jwt from 'jsonwebtoken';
import * as dotenv from 'dotenv';
dotenv.config({ path: '.env' });
function setJWT(cookies: Cookies, user: User) {
const payload = {
username: user.username,
perms: user.perms,
id: user.id
};
if (process.env.JWT_SECRET === undefined) {
throw new Error('JWT_SECRET not defined');
}
const maxAge = 60 * 60 * 24 * 30; // 30 days
const JWT = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '30d' });
cookies.set('jwt', JWT, { maxAge, path: '/', httpOnly: false });
}
export const actions: Actions = {
signin: async ({ request, cookies }) => {
const data = await request.formData();
const username = data.get('username')?.toString().trim();
const password = data.get('password')?.toString().trim();
if (username && password && username !== '' && password !== '') {
const user: User | null = await checkUserCreds(username, password);
if (!user) {
return fail(400, { errorMessage: 'Invalid username or password' });
}
if (!user.active) {
return fail(400, {
errorMessage:
'Account is disabled. Please contact your admin if you think this is a mistake.'
});
}
setJWT(cookies, user);
await updateLastSignin(username);
// redirect to home page
throw redirect(303, '/');
} else {
return fail(400, { errorMessage: 'Missing username or password' });
}
}
};