Skip to content

Commit

Permalink
feat(auth): ✨ Add "delete account" functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
julianYaman committed Jul 3, 2022
1 parent d690048 commit 5ecc100
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
83 changes: 83 additions & 0 deletions pages/api/profile/deleteAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { withSentry } from '@sentry/nextjs'
import type { NextApiRequest, NextApiResponse } from 'next'
import { prisma } from './../../../db'
import { supabase } from "././../../../util/supabase-service"

import {
withApiAuth,
getUser,
} from '@supabase/auth-helpers-nextjs';

type DeleteResponse = {
user_id: string,
deleted: boolean
}

const handler = withApiAuth(async function(
req: NextApiRequest,
res: NextApiResponse<DeleteResponse>
) {

const userInfo = await getUser({ req, res })

if (req.method === "GET"){

if (userInfo.user && req.headers["delete-account"] === "true") {

console.log(">>>>>>> DELETE-ACCOUNT")

try {
await prisma.votes.deleteMany({
where: {
user_id: userInfo.user?.id,
}
});

await supabase.from('profiles').delete().eq("user_id", userInfo.user.id);
const { data: user, error } = await supabase.auth.api.deleteUser(userInfo.user.id);

if (error){
console.log(error)
return res.status(500).json({
user_id: "Error happened",
deleted: false,
})
}

const response = {
user_id: userInfo.user?.id,
deleted: true,
}

console.log(response)

return res.status(200).json(response);
} catch (error) {

console.log(error)
return res.status(500).json({
user_id: userInfo.user?.id || "Not found",
deleted: false,
})

}

} else {
console.log("Not authorized")
return res.status(401).json({
user_id: "Not authorized",
deleted: false,
})
}

} else {

return res.status(405).json({
user_id: "Method not allowed",
deleted: false
})
}

})

export default withSentry(handler);
14 changes: 14 additions & 0 deletions util/supabase-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL ? process.env.NEXT_PUBLIC_SUPABASE_URL : ''
const supabaseKey = process.env.SUPABASE_SERVICE_KEY ? process.env.SUPABASE_SERVICE_KEY : ''

if (supabaseUrl === "") {
throw new Error("Missing supabase url")
}

if (supabaseKey === "") {
throw new Error("Missing supabase service key")
}

export const supabase = createClient(supabaseUrl, supabaseKey)

0 comments on commit 5ecc100

Please sign in to comment.