Skip to content
Open
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
521 changes: 512 additions & 9 deletions shatter-backend/package-lock.json

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions shatter-backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,22 @@
"description": "",
"dependencies": {
"bcryptjs": "^3.0.3",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.19.2",
"react-router-dom": "^7.12.0",
"socket.io": "^4.8.1",
"zod": "^4.1.12"
},
"devDependencies": {
"@eslint/js": "^9.38.0",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.5",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^24.9.2",
"@types/socket.io": "^3.0.1",
"eslint": "^9.38.0",
"globals": "^16.4.0",
"jiti": "^2.6.1",
Expand Down
12 changes: 12 additions & 0 deletions shatter-backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import express from 'express';
import cors from "cors";

import userRoutes from './routes/user_route'; // these routes define how to handle requests to /api/users
import authRoutes from './routes/auth_routes';
import eventRoutes from './routes/event_routes';
Expand All @@ -7,6 +9,16 @@ const app = express();

app.use(express.json());

app.use(cors({
origin: "http://localhost:3000",
credentials: true,
}));

app.use((req, _res, next) => {
req.io = app.get('socketio');
next();
});

app.get('/', (_req, res) => {
res.send('Hello');
});
Expand Down
10 changes: 7 additions & 3 deletions shatter-backend/src/controllers/auth_controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Request, Response } from 'express';
import { User } from '../models/user_model';
import { hashPassword, comparePassword } from '../utils/password_hash';
import { generateToken } from '../utils/jwt_utils';

// Email validation regex
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
Expand Down Expand Up @@ -148,11 +149,14 @@ export const login = async (req: Request, res: Response) => {
user.lastLogin = new Date();
await user.save(); // save the updated user

// 9 - return success
// 9 - generate JWT token for the user
const token = generateToken(user._id.toString());

// 10 - return success with token
res.status(200).json({
message: 'Login successful',
userId: user._id
// TODO: figure out a way to add JWT token here
userId: user._id,
token
});

} catch (err: any) {
Expand Down
176 changes: 163 additions & 13 deletions shatter-backend/src/controllers/event_controller.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,40 @@
import { Request, Response } from "express";
import { Event } from "../models/event_model";
import "../models/participant_model";

import {generateEventId, generateJoinCode} from "../utils/event_utils";
import "../models/participant_model";

import { generateJoinCode } from "../utils/event_utils";
import { Participant } from "../models/participant_model";
import { User } from "../models/user_model";
import { Types } from "mongoose";

export async function createEvent(req: Request, res: Response) {
try {
const { name, description, startDate, endDate, maxParticipant, currentState, createdBy } = req.body;
const {
name,
description,
startDate,
endDate,
maxParticipant,
currentState,
createdBy,
} = req.body;

if (!createdBy) {
return res.status(400).json({ success: false, error: "createdBy email is required" });
return res
.status(400)
.json({ success: false, error: "createdBy email is required" });
}

const eventId = generateEventId();
const joinCode = generateJoinCode();

const event = new Event({
eventId,
name,
description,
joinCode,
startDate,
endDate,
maxParticipant,
participants: [],
participantIds: [],
currentState,
createdBy, // required email field
});
Expand All @@ -37,17 +47,18 @@ export async function createEvent(req: Request, res: Response) {
}
}


export async function getEventByJoinCode(req: Request, res: Response) {
try {
const { joinCode } = req.params;

if (!joinCode) {
return res.status(400).json({ success: false, error: "joinCode is required" });
return res
.status(400)
.json({ success: false, error: "joinCode is required" });
}

// Find event by joinCode and populate participants
const event = await Event.findOne({ joinCode }).populate("participants");
// const event = await Event.findOne({ joinCode }).populate("participantIds");
const event = await Event.findOne({ joinCode });

if (!event) {
return res.status(404).json({ success: false, error: "Event not found" });
Expand All @@ -60,4 +71,143 @@ export async function getEventByJoinCode(req: Request, res: Response) {
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
}
}

export async function joinEventAsUser(req: Request, res: Response) {
try {
const { name, userId } = req.body;
const { eventId } = req.params;

if (!userId || !name)
return res.status(400).json({ success: false, msg: "Missing fields" });

const event = await Event.findById(eventId);
if (!event)
return res.status(404).json({ success: false, msg: "Event not found" });

if (event.participantIds.length >= event.maxParticipant)
return res.status(400).json({ success: false, msg: "Event is full" });

let participant = await Participant.findOne({
userId,
eventId,
});

if (participant) {
return res.status(409).json({ success: false, msg: "Already joined" });
}

participant = await Participant.create({
userId,
name,
eventId,
});

const participantId = participant._id as Types.ObjectId;

const eventUpdate = await Event.updateOne(
{ _id: eventId },
{ $addToSet: { participantIds: participantId } }
);

if (eventUpdate.modifiedCount === 0) {
return res
.status(400)
.json({ success: false, msg: "Already joined this event" });
}

// Add event to user history
await User.updateOne(
{ _id: userId },
{ $addToSet: { eventHistoryIds: eventId } }
);

console.log("Room socket:", eventId);
console.log("Participant data:", { participantId, name });

if (!req.io) {
console.error("ERROR: req.io is undefined!");
} else {
const room = req.io.to(eventId);
console.log("Room object:", room);

room.emit("participant-joined", {
participantId,
name,
});

console.log("Socket event emitted successfully");
}

return res.json({
success: true,
participant,
});
} catch (e) {
console.error("JOIN EVENT ERROR:", e);
return res.status(500).json({ success: false, msg: "Internal error" });
}
}

export async function joinEventAsGuest(req: Request, res: Response) {
try {
const { name } = req.body;
const { eventId } = req.params;

if (!name) {
return res
.status(400)
.json({ success: false, msg: "Missing guest name" });
}

const event = await Event.findById(eventId);
if (!event) {
return res.status(404).json({ success: false, msg: "Event not found" });
}

if (event.participantIds.length >= event.maxParticipant) {
return res.status(400).json({ success: false, msg: "Event is full" });
}

// Create guest participant (userId is null)
const participant = await Participant.create({
userId: null,
name,
eventId,
});

const participantId = participant._id as Types.ObjectId;

// Add participant to event
await Event.updateOne(
{ _id: eventId },
{ $addToSet: { participantIds: participantId } }
);

// Emit socket
console.log("Room socket:", eventId);
console.log("Participant data:", { participantId, name });

if (!req.io) {
console.error("ERROR: req.io is undefined!");
} else {
const room = req.io.to(eventId);
console.log("Room object:", room);

room.emit("participant-joined", {
participantId,
name,
});

console.log("Socket event emitted successfully");
}

return res.json({
success: true,
participant,
});
} catch (err) {
console.error("JOIN GUEST ERROR:", err);
return res.status(500).json({ success: false, msg: "Internal error" });
}
}
97 changes: 97 additions & 0 deletions shatter-backend/src/middleware/auth_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/* eslint-disable @typescript-eslint/no-namespace */
import { Request, Response, NextFunction } from 'express';
import { verifyToken } from '../utils/jwt_utils';

/**
* Extend Express Request type to include user property
* This allows us to attach user info to the request object
*/
declare global {
namespace Express {
interface Request {
user?: {
userId: string;
};
}
}
}

/**
* Authentication Middleware
* Verifies JWT token and attaches user info to request
*
* Usage:
* router.get('/protected', authMiddleware, controller);
*
* Request must include:
* Authorization: Bearer <token>
*/
export const authMiddleware = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
// step 1: Get Authorization header
const authHeader = req.headers.authorization;

if (!authHeader) {
return res.status(401).json({
error: 'Authorization header missing',
});
}

// Step 2: extract token from "Bearer <token>" format
const parts = authHeader.split(' ');

if (parts.length !== 2) {
return res.status(401).json({
error: 'Invalid authorization format. Use: Bearer <token>',
});
}

if (parts[0] !== 'Bearer') {
return res.status(401).json({
error: 'Invalid authorization format. Must start with "Bearer"',
});
}

const token = parts[1];

if (!token) {
return res.status(401).json({
error: 'Token is empty',
});
}

// Step 3: verify token using JWT utility
const decoded = verifyToken(token)

// Step 4: Attach user info to request object
req.user = {
userId: decoded.userId,
};

// step 5: Continue to next Middleware/controller
next();
} catch (error: any) {
// Handle specific JWT errors thrown by jwt_utils
if(error?.message === 'Token expired') {
return res.status(401).json({
error: 'Token expired. Please login again.',
});
}

if (error?.message === 'Invalid token') {
return res.status(401).json({
error: 'Invalid token. Please login again.',
});
}

// Generic error
console.error('Auth middleware error:', error);
return res.status(401).json({
error: 'Authentication failed',
});
}
};
Loading