feat: better login errors - wip #4

This commit is contained in:
axel 2025-04-18 13:48:33 +02:00
parent f241259f78
commit a6641d7ceb

View File

@ -1,8 +1,10 @@
import { dev } from '$app/environment'; import { dev } from '$app/environment';
import { PARSE_ERROR } from '$lib/server/commonResponses';
import { users } from '$lib/server/db'; import { users } from '$lib/server/db';
import { createSession } from '$lib/server/sessions'; import { createSession } from '$lib/server/sessions';
import { fail, redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import { z } from 'zod';
import type { Actions } from './$types'; import type { Actions } from './$types';
export const actions = { export const actions = {
@ -11,21 +13,23 @@ export const actions = {
redirect(302, '/dash'); redirect(302, '/dash');
} }
const data = await request.formData(); const schema = z.object({
const username = data.get('username')?.toString(); username: z.string({ message: 'Username is required.' }).trim(),
const password = data.get('password')?.toString(); password: z.string({ message: 'Password is required.' }),
if (!username || !password) {
return fail(400, {
error: 'MISSING_CREDENTIALS',
}); });
const data = await request.formData();
const parsed = schema.safeParse(Object.fromEntries(data.entries()));
if (!parsed.success) {
return PARSE_ERROR(parsed.error);
} }
const user = await users.getByName(username); const user = await users.getByName(parsed.data.username);
if (!user || !bcrypt.compareSync(password, user.password)) { if (!user || !bcrypt.compareSync(parsed.data.password, user.password)) {
return fail(403, { return fail(403, {
error: 'INVALID_CREDENTIALS', error: 'Could not sign in. Please verify your username/password are correct.',
}); });
} }