Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create route to delete current user #49

Merged
merged 2 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 });
};
Loading