diff --git a/src/routes/account/+page.server.ts b/src/routes/account/+page.server.ts index 373de7c..262b784 100644 --- a/src/routes/account/+page.server.ts +++ b/src/routes/account/+page.server.ts @@ -2,6 +2,8 @@ import { fail, redirect } from '@sveltejs/kit'; import type { Actions, PageServerLoad } from './$types'; import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'; +import { LuciaError } from 'lucia'; +import { validatePassword } from '$lib/validators'; export const load: PageServerLoad = async ({ locals: { authReq } }) => { const session = await authReq.validate(); @@ -49,6 +51,50 @@ export const actions: Actions = { }; }, + changePassword: async ({ request, locals: { auth, authReq } }) => { + const session = await authReq.validate(); + if (!session) return fail(401); + + const formData = await request.formData(); + const currentPassword = formData.get('current-password') as string; + const newPassword = formData.get('new-password') as string; + + if (!validatePassword(newPassword)) { + return fail(400, { + type: 'changePassword', + message: 'Password has an invalid length; must be between 8 and 255 characters.', + success: false + }); + } + + // Check that user passed correct password then attempt to change password + // + // Errors if user does not exist or password is incorrect + try { + const username = session.user.username; + const key = await auth.useKey('username', username.toLowerCase(), currentPassword); + + await auth.updateKeyPassword('username', key.userId, newPassword); + } catch (err) { + if ( + err instanceof LuciaError && + (err.message === 'AUTH_INVALID_KEY_ID' || err.message === 'AUTH_INVALID_PASSWORD') + ) { + return fail(400, { + type: 'changePassword', + message: 'Incorrect current password', + success: false + }); + } + } + + return { + type: 'changePassword', + message: 'Password updated.', + success: true + }; + }, + signout: async ({ locals: { auth, authReq } }) => { const session = await authReq.validate(); if (!session) return fail(401);