feat: Change password
This commit is contained in:
parent
de99e3af8f
commit
da068dcc12
1 changed files with 46 additions and 0 deletions
|
@ -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);
|
||||
|
|
Loading…
Reference in a new issue