boredgame/src/routes/(auth)/login/+page.server.ts

159 lines
4.5 KiB
TypeScript
Raw Normal View History

import { fail, error, type Actions } from '@sveltejs/kit';
import { and, eq } from 'drizzle-orm';
import { Argon2id } from 'oslo/password';
import { decodeHex } from 'oslo/encoding';
import { TOTPController } from 'oslo/otp';
import { zod } from 'sveltekit-superforms/adapters';
2023-05-21 05:18:04 +00:00
import { setError, superValidate } from 'sveltekit-superforms/server';
import { redirect } from 'sveltekit-flash-message/server';
import { RateLimiter } from 'sveltekit-rate-limiter/server';
2024-02-08 03:37:54 +00:00
import db from '$lib/drizzle';
import { lucia } from '$lib/server/auth';
import { signInSchema } from '$lib/validations/auth';
import { users, recovery_codes } from '../../../schema';
import type { PageServerLoad } from './$types';
2023-05-21 05:18:04 +00:00
export const load: PageServerLoad = async (event) => {
if (event.locals.user) {
const message = { type: 'success', message: 'You are already signed in' } as const;
throw redirect('/', message, event);
}
const form = await superValidate(event, zod(signInSchema));
return {
form,
};
2023-05-21 05:18:04 +00:00
};
const limiter = new RateLimiter({
// A rate is defined by [number, unit]
IPUA: [5, 'm'],
});
export const actions: Actions = {
2023-05-21 05:18:04 +00:00
default: async (event) => {
if (await limiter.isLimited(event)) {
throw error(429);
}
const { locals } = event;
const form = await superValidate(event, zod(signInSchema));
2023-05-21 05:18:04 +00:00
if (!form.valid) {
form.data.password = '';
2023-05-21 05:18:04 +00:00
return fail(400, {
form,
2023-05-21 05:18:04 +00:00
});
}
let session;
let sessionCookie;
2023-05-21 05:18:04 +00:00
try {
const password = form.data.password;
2024-02-08 03:37:54 +00:00
const user = await db.query.users.findFirst({
where: eq(users.username, form.data.username),
});
console.log('user', JSON.stringify(user, null, 2));
if (!user?.hashed_password) {
form.data.password = '';
return setError(form, '', 'Your username or password is incorrect.');
}
const validPassword = await new Argon2id().verify(user.hashed_password, password);
if (!validPassword) {
console.log('invalid password');
form.data.password = '';
return setError(form, '', 'Your username or password is incorrect.');
}
// await db
// .insert(collections)
// .values({
// user_id: user.id,
// })
// .onConflictDoNothing();
// await db
// .insert(wishlists)
// .values({
// user_id: user.id,
// })
// .onConflictDoNothing();
if (user?.two_factor_enabled && user?.two_factor_secret && !form?.data?.totpToken) {
return fail(400, {
form,
twoFactorRequired: true,
});
} else if (user?.two_factor_enabled && user?.two_factor_secret && form?.data?.totpToken) {
console.log('totpToken', form.data.totpToken);
const validOTP = await new TOTPController().verify(
form.data.totpToken,
decodeHex(user.two_factor_secret),
);
console.log('validOTP', validOTP);
if (!validOTP) {
console.log('invalid TOTP code check for recovery codes');
const usedRecoveryCode = await checkRecoveryCode(form?.data?.totpToken, user.id);
if (!usedRecoveryCode) {
console.log('invalid TOTP code');
form.errors.totpToken = ['Invalid code'];
return fail(400, {
form,
twoFactorRequired: true,
});
}
}
}
console.log('ip', locals.ip);
console.log('country', locals.country);
session = await lucia.createSession(user.id, {
ip_country: locals.country,
ip_address: locals.ip,
});
2024-03-11 06:19:55 +00:00
console.log('logging in session', session);
sessionCookie = lucia.createSessionCookie(session.id);
2024-03-11 06:19:55 +00:00
console.log('logging in session cookie', sessionCookie);
2023-05-21 05:18:04 +00:00
} catch (e) {
// TODO: need to return error message to the client
console.error(e);
form.data.password = '';
return setError(form, '', 'Your username or password is incorrect.');
2023-05-21 05:18:04 +00:00
}
console.log('setting session cookie', sessionCookie);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: '.',
...sessionCookie.attributes,
});
form.data.username = '';
form.data.password = '';
const message = { type: 'success', message: 'Signed In!' } as const;
2024-03-11 06:19:55 +00:00
redirect(302, '/', message, event);
},
2023-05-21 05:18:04 +00:00
};
async function checkRecoveryCode(recoveryCode: string, userId: string) {
const userRecoveryCodes = await db.query.recovery_codes.findMany({
where: and(eq(recovery_codes.used, false), eq(recovery_codes.userId, userId)),
});
for (const code of userRecoveryCodes) {
const validRecoveryCode = await new Argon2id().verify(code.code, recoveryCode);
if (validRecoveryCode) {
await db
.update(recovery_codes)
.set({
used: true,
})
.where(eq(recovery_codes.id, code.id));
return true;
}
}
return false;
}