Skip to content

Commit

Permalink
🔒wrote preliminary login function and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Plebbaroni committed Nov 12, 2024
1 parent 481bcec commit 3ee4f56
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 13 deletions.
4 changes: 3 additions & 1 deletion backend/.env.test
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
DATABASE_URL="postgres://postgres:postgres@localhost:5432"
DIRECT_URL="postgres://postgres:postgres@localhost:5432"
NODE_ENV=test
NODE_ENV=test
REDIS_PORT=6380
SESSION_SECRET=notsecret
2 changes: 2 additions & 0 deletions backend/scripts/run-integration.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
DIR="$(cd "$(dirname "$0")" && pwd)"
export $(grep -v '^#' .env.test | xargs)
docker-compose up -d
docker rm -f redis-stack-test 2>/dev/null || true && docker run -d --name redis-stack-test -p 6380:6379 -p 8002:8001 redis/redis-stack:latest
echo '🟡 - Waiting for database to be ready...'
echo "node_env is ${NODE_ENV}"
echo "Using database: ${DATABASE_URL}"
echo "redis port is ${REDIS_PORT}"
$DIR/wait-for-it.sh "${DATABASE_URL}" -- echo '🟢 - Database is ready!'
npx prisma migrate dev --name init
if [ "$#" -eq "0" ]
Expand Down
7 changes: 0 additions & 7 deletions backend/src/expressSession.d.ts

This file was deleted.

22 changes: 17 additions & 5 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,20 @@ import { PrismaClient, Prisma, UserType, User } from "@prisma/client";
import prisma from "./prisma";
import RedisStore from "connect-redis";
import { createClient } from "redis";
declare module "express-session" {
interface SessionData {
userId: number;
}
}

// Initialize client.
let redisClient = createClient();
if (process.env['REDIS_PORT'] === undefined) {
console.error("Redis port not provided in .env file");
process.exit(1);
}
let redisClient = createClient({
url: `redis://localhost:${process.env['REDIS_PORT']}`
});
redisClient.connect().catch(console.error);

// Initialize store.
Expand Down Expand Up @@ -101,7 +112,7 @@ app.post("/auth/login", async (req: TypedRequest<LoginBody>, res: Response) => {
const user = await prisma.user.findFirst({
where: {
username: username
},
}
});

if (!user) {
Expand All @@ -117,17 +128,18 @@ app.post("/auth/login", async (req: TypedRequest<LoginBody>, res: Response) => {
// Set user session
req.session.userId = user.id;
req.session.save(); // Explicitly save session to Redis
return res.status(200)
return res.status(200).json({message:"ok"});
} catch (error) {
return res.status(500).json({ error: "Error logging in" });
}
});

app.get("/user", async (req: TypedRequest<UserIdBody>, res: Response) => {
console.log("running");
if (req.session.userId === req.body.userId) {
return res.status(200)
return res.status(200).json({message:'ok'})
} else {
return res.status(401)
return res.status(401).json({message:'nah'})
}
});

Expand Down
47 changes: 47 additions & 0 deletions backend/tests/register.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//test/sample.test.ts
import { expect, test, vi, describe } from "vitest"; // 👈🏻 Added the `vi` import
import prisma from "../src/prisma";
import request from "supertest";
import app from "../src/index";

describe("Tests", () => {
test("register test", async () => {
const { status, body } = await request(app).post("/auth/register").send({
username: "shinjisatoo",
password: "testpassword",
email: "[email protected]",
userType: "ATTENDEE",
});

const newUser = await prisma.user.findFirst({
where: {
email: "[email protected]",
},
});

expect(status).toBe(201);
expect(newUser).not.toBeNull();
expect(body.newUser).toStrictEqual({
username: "shinjisatoo",
id: newUser?.id,
});
});

test("Email already exists", async () => {
await request(app).post("/auth/register").send({
username: "shinjisatoo",
password: "testpassword",
email: "[email protected]",
userType: "ATTENDEE",
});

const { status, body } = await request(app).post("/auth/register").send({
username: "shinjisatoo2",
password: "testpassword2",
email: "[email protected]",
userType: "ATTENDEE",
});

expect(status).toBe(400);
})
});

0 comments on commit 3ee4f56

Please sign in to comment.