From 2de7d3613864f3d47ddea79db0aab7383a409767 Mon Sep 17 00:00:00 2001 From: Markus Thielker Date: Sun, 17 Mar 2024 19:55:17 +0100 Subject: [PATCH] N-FIN-47: add server action to delete account --- src/lib/actions/accountDelete.ts | 58 ++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/lib/actions/accountDelete.ts diff --git a/src/lib/actions/accountDelete.ts b/src/lib/actions/accountDelete.ts new file mode 100644 index 0000000..28cf745 --- /dev/null +++ b/src/lib/actions/accountDelete.ts @@ -0,0 +1,58 @@ +import { ActionResponse } from '@/lib/types/actionResponse'; +import { URL_SIGN_IN } from '@/lib/constants'; +import { getUser, lucia } from '@/auth'; +import { prismaClient } from '@/prisma'; +import { cookies } from 'next/headers'; + +export default async function accountDelete(): Promise { + 'use server'; + + const user = await getUser(); + + if (!user) { + return { + type: 'error', + message: 'You aren\'t signed in.', + redirect: URL_SIGN_IN, + }; + } + + await prismaClient.payment.deleteMany({ + where: { + userId: user.id, + }, + }); + + await prismaClient.entity.deleteMany({ + where: { + userId: user.id, + }, + }); + + await prismaClient.category.deleteMany({ + where: { + userId: user.id, + }, + }); + + await prismaClient.session.deleteMany({ + where: { + userId: user.id, + }, + }); + + await prismaClient.user.delete({ + where: { + id: user.id, + }, + }); + + const sessionCookie = lucia.createBlankSessionCookie(); + cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes); + + return { + type: 'success', + message: 'Your account was removed.', + redirect: URL_SIGN_IN, + }; +}