feat: Update username
This commit is contained in:
parent
76bd311ae8
commit
2aa80f7d52
2 changed files with 39 additions and 1 deletions
|
@ -1,6 +1,7 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals: { authReq } }) => {
|
||||
const session = await authReq.validate();
|
||||
|
@ -11,6 +12,43 @@ export const load: PageServerLoad = async ({ locals: { authReq } }) => {
|
|||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
updateAccount: async ({ request, locals: { auth, authReq } }) => {
|
||||
const session = await authReq.validate();
|
||||
if (!session) return fail(401);
|
||||
|
||||
const formData = await request.formData();
|
||||
const username = formData.get('username') as string;
|
||||
|
||||
// Attempty to update username
|
||||
//
|
||||
// Fails if wanted new username is already assigned to another user
|
||||
try {
|
||||
await auth.updateUserAttributes(session.user.userId, {
|
||||
username
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof PrismaClientKnownRequestError && err.code === 'P2002') {
|
||||
return fail(400, {
|
||||
type: 'updateAccount',
|
||||
message: 'User with username already exists.',
|
||||
success: false
|
||||
});
|
||||
}
|
||||
|
||||
console.log(err);
|
||||
return fail(500, {
|
||||
message: 'Internal server error, please try again later.'
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'updateAccount',
|
||||
message: 'Account updated.',
|
||||
success: true,
|
||||
username
|
||||
};
|
||||
},
|
||||
|
||||
signout: async ({ locals: { auth, authReq } }) => {
|
||||
const session = await authReq.validate();
|
||||
if (!session) return fail(401);
|
||||
|
|
|
@ -18,7 +18,7 @@
|
|||
<main class="container">
|
||||
<h1>Account</h1>
|
||||
<section>
|
||||
<form method="POST" action="?/updateAccount">
|
||||
<form method="POST" action="?/updateAccount" use:enhance>
|
||||
{#if form?.type === 'updateAccount'}
|
||||
<small style="color: {form?.success ? 'green' : 'red'}">{form?.message}</small>
|
||||
{/if}
|
||||
|
|
Loading…
Reference in a new issue