File size: 1,274 Bytes
57a889c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { Request, Response, NextFunction } from 'express';
import { canAccessTrip, isOwner } from '../db/database';
import { AuthRequest } from '../types';

/** Middleware: verifies the authenticated user is an owner or member of the trip, then attaches trip to req. */
function requireTripAccess(req: Request, res: Response, next: NextFunction): void {
  const authReq = req as AuthRequest;
  const tripId = req.params.tripId || req.params.id;
  if (!tripId) {
    res.status(400).json({ error: 'Trip ID required' });
    return;
  }
  const trip = canAccessTrip(Number(tripId), authReq.user.id);
  if (!trip) {
    res.status(404).json({ error: 'Trip not found' });
    return;
  }
  authReq.trip = trip;
  next();
}

/** Middleware: verifies the authenticated user is the trip owner (not just a member). */
function requireTripOwner(req: Request, res: Response, next: NextFunction): void {
  const authReq = req as AuthRequest;
  const tripId = req.params.tripId || req.params.id;
  if (!tripId) {
    res.status(400).json({ error: 'Trip ID required' });
    return;
  }
  if (!isOwner(Number(tripId), authReq.user.id)) {
    res.status(403).json({ error: 'Only the trip owner can do this' });
    return;
  }
  next();
}

export { requireTripAccess, requireTripOwner };