Skip to content

Commit

Permalink
Create route to delete current user (#49)
Browse files Browse the repository at this point in the history
* Create route to delete current user

* Add tests for delete route
  • Loading branch information
Advayp authored Jan 20, 2025
1 parent 741f5fc commit 7bf5467
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
26 changes: 26 additions & 0 deletions backend/app/api/user/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { prismaMock } from '@/__test__/singleton';
import { User } from '@prisma/client';
import { DELETE } from './route';

jest.mock('@/lib/session', () => ({
verifySession: jest.fn(() => ({
isAuth: true,
uid: 2,
})),
deleteSession: jest.fn(() => {}),
}));

test('Delete succeeds if user is authenticated', async () => {
const temporaryUser: User = {
id: 1,
username: 'test',
createdAt: new Date(),
updatedAt: new Date(),
};
prismaMock.user.delete.mockResolvedValue(temporaryUser);

const res = await DELETE();
const data = await res.json();

expect(data.success).toBe(true);
});
16 changes: 16 additions & 0 deletions backend/app/api/user/noAuth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { DELETE } from './route';

jest.mock('@/lib/session', () => ({
verifySession: jest.fn(() => ({
isAuth: false,
})),
deleteSession: jest.fn(() => {}),
}));

test('Delete fails for an invalid session', async () => {
const res = await DELETE();
const data = await res.json();

expect(res.status).toEqual(400);
expect(data.error).toBe('Invalid session');
});
31 changes: 30 additions & 1 deletion backend/app/api/user/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import prisma from '@/lib/prisma';
import { verifySession } from '@/lib/session';
import { deleteSession, verifySession } from '@/lib/session';
import { NextResponse } from 'next/server';

export const GET = async () => {
Expand Down Expand Up @@ -28,3 +28,32 @@ export const GET = async () => {
user,
});
};

type DeleteResponse = {
success: true;
};

export const DELETE = async (): Promise<
NextResponse<DeleteResponse | { error: string }>
> => {
const session = await verifySession();

if (!session.isAuth) {
return NextResponse.json(
{
error: 'Invalid session',
},
{ status: 400 }
);
}

await deleteSession();

await prisma.user.delete({
where: {
id: session.uid,
},
});

return NextResponse.json({ success: true });
};

0 comments on commit 7bf5467

Please sign in to comment.