Files
fbla26/src/routes/account/+page.server.ts
T
drake bce9a19776
ci / docker_image (push) Successful in 2m17s
ci / deploy (push) Successful in 50s
fix account save
2026-04-11 09:28:45 -05:00

77 lines
2.4 KiB
TypeScript

import type { PageServerLoad } from '$types';
import sql from '$lib/db/db.server';
import type { User, UserSettings } from '$lib/types/user';
import { type Actions, error, fail } from '@sveltejs/kit';
import { getFormString, getRequiredFormString } from '$lib/shared';
import bcrypt from 'bcrypt';
import { setJWTCookie } from '$lib/auth/index.server';
export const load: PageServerLoad = async ({ locals }) => {
if (!locals || !locals.user) {
throw Error('Need to be logged in!');
}
const [userData] = await sql`
SELECT * FROM users WHERE id = ${locals.user.id}
`;
userData.settings = JSON.parse(userData.settings);
return { userData };
};
export const actions: Actions = {
default: async ({ request, url, locals, params, cookies }) => {
if (!locals || !locals.user) {
throw error(403, 'Need to be logged in!');
}
const data = await request.formData();
let name: string;
let email: string;
let newPassword: string | null;
let retypeNewPassword: string | null;
let staleItemDays: number;
let notifyAllApprovedInquiries: boolean;
let notifyAllTurnedInInquiries: boolean;
try {
name = getRequiredFormString(data, 'name');
email = getRequiredFormString(data, 'email');
newPassword = getFormString(data, 'newPassword');
retypeNewPassword = getFormString(data, 'retypeNewPassword');
staleItemDays = parseInt(getRequiredFormString(data, 'staleItemDays'));
notifyAllApprovedInquiries = getFormString(data, 'notifyAllApprovedInquiries') == 'on';
notifyAllTurnedInInquiries = getFormString(data, 'notifyAllTurnedInInquiries') == 'on';
if (newPassword !== retypeNewPassword) {
fail(400, { password: 'New passwords dont match!' });
}
const passwordHash = newPassword ? await bcrypt.hash(newPassword, 12) : null;
const settings: UserSettings = {
staleItemDays,
notifyAllApprovedInquiries,
notifyAllTurnedInInquiries
};
const [res] = await sql`
UPDATE users SET name = ${name},
email = ${email},
${passwordHash ? sql`password_hash = ${passwordHash},` : sql``}
settings = ${JSON.stringify(settings)}
WHERE id = ${locals.user.id}
RETURNING *;
`;
res.settings = JSON.parse(res.settings);
setJWTCookie(cookies, res as User);
} catch (e) {
return fail(400, {
message: e instanceof Error ? e.message : 'Unknown error occurred',
success: false
});
}
return { success: true };
}
} satisfies Actions;