fix: Properly handle login errors
This commit is contained in:
parent
b8a7478fd9
commit
0de228e357
@ -5,6 +5,7 @@ import { redirect } from '@sveltejs/kit';
|
||||
import { fail, message, setError, superValidate } from 'sveltekit-superforms';
|
||||
import { zod } from 'sveltekit-superforms/adapters';
|
||||
import type { Actions } from './$types';
|
||||
import type { APIError } from 'better-auth/api';
|
||||
|
||||
export async function load({ request }) {
|
||||
const session = await auth.api.getSession({
|
||||
@ -25,35 +26,41 @@ export const actions = {
|
||||
const email = form.data.email;
|
||||
const password = form.data.password;
|
||||
|
||||
if (!form.valid) {
|
||||
return fail(400, { form });
|
||||
}
|
||||
try {
|
||||
if (!form.valid) {
|
||||
return fail(400, { form });
|
||||
}
|
||||
|
||||
const signin = await auth.api.signInEmail({
|
||||
body: {
|
||||
email,
|
||||
password,
|
||||
},
|
||||
asResponse: true,
|
||||
});
|
||||
const signin: Response = await auth.api.signInEmail({
|
||||
body: {
|
||||
email,
|
||||
password,
|
||||
},
|
||||
asResponse: true,
|
||||
});
|
||||
|
||||
const setCookieHeader = signin.headers.get('set-cookie');
|
||||
if (setCookieHeader) {
|
||||
const parsedCookie = setCookieHeader.split(';')[0];
|
||||
const [name, encodedValue] = parsedCookie.split('=');
|
||||
// need to decode it first
|
||||
const decodedValue = decodeURIComponent(encodedValue);
|
||||
cookies.set(name, decodedValue, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
maxAge: 604800,
|
||||
secure: !dev,
|
||||
});
|
||||
} else {
|
||||
return setError(form, 'password', 'Invalid email or password', {
|
||||
status: 401,
|
||||
});
|
||||
const setCookieHeader = signin.headers.get('set-cookie');
|
||||
if (setCookieHeader) {
|
||||
const parsedCookie = setCookieHeader.split(';')[0];
|
||||
const [name, encodedValue] = parsedCookie.split('=');
|
||||
// need to decode it first
|
||||
const decodedValue = decodeURIComponent(encodedValue);
|
||||
cookies.set(name, decodedValue, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
maxAge: 604800,
|
||||
secure: !dev,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if ((e as APIError).body.code === 'INVALID_EMAIL_OR_PASSWORD') {
|
||||
return setError(form, 'password', 'Invalid email or password', {
|
||||
status: 401,
|
||||
});
|
||||
} else {
|
||||
return setError(form, 'password', (e as APIError).body.code as string);
|
||||
}
|
||||
}
|
||||
|
||||
return message(form, 'Successfuly signed in.');
|
||||
|
Loading…
Reference in New Issue
Block a user