Skip to content

Implement password validation #83

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

Merged
merged 4 commits into from
Jan 27, 2025
Merged
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
12 changes: 10 additions & 2 deletions backend/app/api/songs/dislike/route.test.ts
Original file line number Diff line number Diff line change
@@ -15,7 +15,11 @@ test("Liked songs fails if session isn't valid", async () => {
isAuth: false,
});

prismaMock.song.upsert.mockResolvedValue({ id: 1, trackID: 'test' });
prismaMock.song.upsert.mockResolvedValue({
id: 1,
trackID: 'test',
genreId: null,
});

const req = generateMockRequest({
trackId: 'test',
@@ -33,7 +37,11 @@ test('Liked songs succeeds for valid session', async () => {
uid: 2,
});

prismaMock.song.upsert.mockResolvedValue({ id: 1, trackID: 'test' });
prismaMock.song.upsert.mockResolvedValue({
id: 1,
trackID: 'test',
genreId: null,
});

const req = generateMockRequest({
trackId: 'test',
12 changes: 10 additions & 2 deletions backend/app/api/songs/like/route.test.ts
Original file line number Diff line number Diff line change
@@ -15,7 +15,11 @@ test("Liked songs fails if session isn't valid", async () => {
isAuth: false,
});

prismaMock.song.upsert.mockResolvedValue({ id: 1, trackID: 'test' });
prismaMock.song.upsert.mockResolvedValue({
id: 1,
trackID: 'test',
genreId: null,
});

const req = generateMockRequest({
trackId: 'test',
@@ -33,7 +37,11 @@ test('Liked songs succeeds for valid session', async () => {
uid: 2,
});

prismaMock.song.upsert.mockResolvedValue({ id: 1, trackID: 'test' });
prismaMock.song.upsert.mockResolvedValue({
id: 1,
trackID: 'test',
genreId: null,
});

const req = generateMockRequest({
trackId: 'test',
38 changes: 36 additions & 2 deletions backend/app/api/user/login/route.test.ts
Original file line number Diff line number Diff line change
@@ -3,22 +3,30 @@ import { User } from '@prisma/client';
import { POST } from './route';
import { generateMockRequest } from '@/__test__/utils';
import { NextRequest } from 'next/server';
import argon2 from 'argon2';

jest.mock('@/lib/session', () => ({
createSession: jest.fn(async (x: number) => x),
}));

test('Login succeeds for existing user', async () => {
const password = 'password';
const hashedPassword = await argon2.hash(password);

const temporaryUser: User = {
id: 1,
username: 'test',
password: hashedPassword,
createdAt: new Date(),
updatedAt: new Date(),
};

prismaMock.user.findFirst.mockResolvedValue(temporaryUser);

const req = generateMockRequest(temporaryUser);
const req = generateMockRequest({
username: temporaryUser.username,
password,
});
const res = await POST(req as NextRequest);
const data = await res.json();

@@ -35,9 +43,35 @@ test('Login succeeds for existing user', async () => {
test('Login fails if user does not exist', async () => {
prismaMock.user.findFirst.mockResolvedValue(null);

const req = generateMockRequest({ username: 'test' });
const req = generateMockRequest({ username: 'test', password: 'password' });
const res = await POST(req as NextRequest);
const data = await res.json();

expect(res.status).toEqual(404);
expect(data.error).toEqual("User doesn't exist");
});

test('Login fails if password is incorrect', async () => {
const password = 'password';
const hashedPassword = await argon2.hash(password);

const temporaryUser: User = {
id: 1,
username: 'test',
password: hashedPassword,
createdAt: new Date(),
updatedAt: new Date(),
};

prismaMock.user.findFirst.mockResolvedValue(temporaryUser);

const req = generateMockRequest({
username: temporaryUser.username,
password: 'incorrect password',
});
const res = await POST(req as NextRequest);
const data = await res.json();

expect(res.status).toEqual(400);
expect(data.error).toEqual('Incorrect password');
});
13 changes: 12 additions & 1 deletion backend/app/api/user/login/route.ts
Original file line number Diff line number Diff line change
@@ -2,9 +2,11 @@ import prisma from '@/lib/prisma';
import { createSession } from '@/lib/session';
import { User } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';
import argon2 from 'argon2';

type PostRequest = {
username: string;
password: string;
};

type PostResponse = {
@@ -17,7 +19,7 @@ type PostResponse = {
export const POST = async (
req: NextRequest
): Promise<NextResponse<PostResponse | { error: string }>> => {
const { username }: PostRequest = await req.json();
const { username, password }: PostRequest = await req.json();

const existingUser = await prisma.user.findFirst({
where: {
@@ -29,6 +31,15 @@ export const POST = async (
return NextResponse.json({ error: "User doesn't exist" }, { status: 404 });
}

const isCorrectPassword = await argon2.verify(
existingUser.password,
password
);

if (!isCorrectPassword) {
return NextResponse.json({ error: 'Incorrect password' }, { status: 400 });
}

await createSession(existingUser.id);

return NextResponse.json({ success: true, user: existingUser });
31 changes: 29 additions & 2 deletions backend/app/api/user/register/route.test.ts
Original file line number Diff line number Diff line change
@@ -12,14 +12,18 @@ test('Register route returns intended user', async () => {
const temporaryUser: User = {
id: 1,
username: 'test',
password: 'test1',
createdAt: new Date(),
updatedAt: new Date(),
};

prismaMock.user.findFirst.mockResolvedValue(null);
prismaMock.user.create.mockResolvedValue(temporaryUser);

const req = generateMockRequest(temporaryUser);
const req = generateMockRequest({
username: temporaryUser.username,
password: temporaryUser.password,
});
const res = await POST(req as NextRequest);
const data = await res.json();

@@ -36,16 +40,39 @@ test('Registration fails if user exists', async () => {
const temporaryUser: User = {
id: 1,
username: 'test',
password: 'test1',
createdAt: new Date(),
updatedAt: new Date(),
};

prismaMock.user.findFirst.mockResolvedValue(temporaryUser);

const req = generateMockRequest({ username: 'test' });
const req = generateMockRequest({
username: 'test',
password: temporaryUser.password,
});
const res = await POST(req as NextRequest);
const data = await res.json();

expect(res.status).toEqual(400);
expect(data.error).toEqual('User already exists');
});

test('Registration fails if password is too short', async () => {
const temporaryUser: User = {
id: 1,
username: 'test',
password: 't',
createdAt: new Date(),
updatedAt: new Date(),
};

prismaMock.user.create.mockResolvedValue(temporaryUser);

const req = generateMockRequest({ username: 'user1', password: 't' });
const res = await POST(req as NextRequest);
const data = await res.json();

expect(res.status).toEqual(400);
expect(data.error).toEqual('Password is too short');
});
19 changes: 18 additions & 1 deletion backend/app/api/user/register/route.ts
Original file line number Diff line number Diff line change
@@ -3,19 +3,33 @@ import { createSession } from '@/lib/session';
import { ErrorResponse } from '@/lib/types';
import { User } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';
import argon2 from 'argon2';

type PostRequest = {
username: string;
password: string;
};

type PostResponse = {
user: User;
};

const isValidPassword = (password: string) => {
// Simple password validation
return password.length >= 5;
};

export const POST = async (
req: NextRequest
): Promise<NextResponse<PostResponse | ErrorResponse>> => {
const { username }: PostRequest = await req.json();
const { username, password }: PostRequest = await req.json();

if (!isValidPassword(password)) {
return NextResponse.json(
{ error: 'Password is too short' },
{ status: 400 }
);
}

const existingUser = await prisma.user.findFirst({
where: {
@@ -27,9 +41,12 @@ export const POST = async (
return NextResponse.json({ error: 'User already exists' }, { status: 400 });
}

const hashedPassword = await argon2.hash(password);

const user = await prisma.user.create({
data: {
username,
password: hashedPassword,
},
});

1 change: 1 addition & 0 deletions backend/app/api/user/route.test.ts
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@ test('Delete succeeds if user is authenticated', async () => {
username: 'test',
createdAt: new Date(),
updatedAt: new Date(),
password: 'test',
};
prismaMock.user.delete.mockResolvedValue(temporaryUser);

5 changes: 3 additions & 2 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -13,11 +13,12 @@
},
"dependencies": {
"@prisma/client": "^6.2.1",
"argon2": "^0.41.1",
"jose": "^5.9.6",
"next": "15.1.4",
"prisma": "^6.2.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"prisma": "^6.2.1"
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `password` to the `User` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "User" ADD COLUMN "password" TEXT NOT NULL;
1 change: 1 addition & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@ model Genre {
model User {
id Int @id @default(autoincrement())
username String
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
preferences Genre[]