feat: Change password

This commit is contained in:
Roman Godmaire 2023-11-19 08:52:23 -05:00
parent de99e3af8f
commit da068dcc12

View file

@ -2,6 +2,8 @@ import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'; import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
import { LuciaError } from 'lucia';
import { validatePassword } from '$lib/validators';
export const load: PageServerLoad = async ({ locals: { authReq } }) => { export const load: PageServerLoad = async ({ locals: { authReq } }) => {
const session = await authReq.validate(); 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 } }) => { signout: async ({ locals: { auth, authReq } }) => {
const session = await authReq.validate(); const session = await authReq.validate();
if (!session) return fail(401); if (!session) return fail(401);