import { error, fail } from '@sveltejs/kit'; import type { PageServerLoad, Actions } from './$types'; import { createApiClient } from '$lib/api.server'; import { getErrorMessage } from '$lib/errors'; export const load: PageServerLoad = async ({ params, fetch, locals }) => { const user = locals.user; const hasAdmin = user?.groups?.some((g: { permissions: string[] }) => g.permissions.includes('ADMIN') ); if (!hasAdmin) throw error(403, getErrorMessage('FORBIDDEN')); const api = createApiClient(fetch); const [userResult, groupsResult] = await Promise.all([ api.GET('/api/users/{id}', { params: { path: { id: params.id } } }), api.GET('/api/groups') ]); if (!userResult.response.ok) throw error(404, getErrorMessage('USER_NOT_FOUND')); return { editUser: userResult.data!, groups: groupsResult.data ?? [] }; }; export const actions: Actions = { default: async ({ params, request, fetch }) => { const data = await request.formData(); const newPassword = data.get('newPassword') as string; const confirmPassword = data.get('confirmPassword') as string; if (newPassword && newPassword !== confirmPassword) { return fail(400, { error: getErrorMessage('PASSWORDS_DO_NOT_MATCH') }); } const birthDateRaw = data.get('birthDate') as string; const body = { firstName: (data.get('firstName') as string) || null, lastName: (data.get('lastName') as string) || null, birthDate: birthDateRaw || null, email: (data.get('email') as string) || null, contact: (data.get('contact') as string) || null, newPassword: newPassword || null, groupIds: data.getAll('groupIds') as string[] }; const res = await fetch(`/api/users/${params.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!res.ok) { let code: string | undefined; try { const json = await res.json(); code = json?.code; } catch { // ignore } return fail(res.status, { error: getErrorMessage(code) }); } return { success: true }; } };