| [7bc636b] | 1 | /**
|
|---|
| 2 | * Auth middleware
|
|---|
| 3 | */
|
|---|
| 4 |
|
|---|
| 5 | /**
|
|---|
| 6 | * Validate a "next" URL for safe redirect after login.
|
|---|
| 7 | * Returns the URL if safe, otherwise null.
|
|---|
| 8 | *
|
|---|
| 9 | * Rules:
|
|---|
| 10 | * - Must be a string, max 256 chars (prevent abuse).
|
|---|
| 11 | * - Must start with "/" but NOT "//" or "/\" (no protocol-relative open redirects).
|
|---|
| 12 | * - Must not point back at /auth/* (prevents login → login loop).
|
|---|
| 13 | */
|
|---|
| 14 | export function safeNext(raw) {
|
|---|
| 15 | if (typeof raw !== 'string' || !raw.length || raw.length > 256) return null;
|
|---|
| 16 | if (raw[0] !== '/' || raw[1] === '/' || raw[1] === '\\') return null;
|
|---|
| 17 | if (/^\/auth(\/|$)/i.test(raw)) return null;
|
|---|
| 18 | return raw;
|
|---|
| 19 | }
|
|---|
| 20 |
|
|---|
| 21 | function loginRedirect(req, res) {
|
|---|
| 22 | // Preserve the originally-requested URL so login can return us there.
|
|---|
| 23 | const next = encodeURIComponent(req.originalUrl || req.url || '/');
|
|---|
| 24 | const target = `/auth/login?next=${next}`;
|
|---|
| 25 | if (req.headers['hx-request'] === 'true') {
|
|---|
| 26 | res.setHeader('HX-Redirect', target);
|
|---|
| 27 | return res.status(401).send('Login required');
|
|---|
| 28 | }
|
|---|
| 29 | return res.redirect(target);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | export function requireAuth(req, res, next) {
|
|---|
| 33 | if (!req.session?.user) return loginRedirect(req, res);
|
|---|
| 34 | next();
|
|---|
| 35 | }
|
|---|
| 36 |
|
|---|
| 37 | export function requireGod(req, res, next) {
|
|---|
| 38 | if (!req.session?.user) return loginRedirect(req, res);
|
|---|
| 39 | if (req.session.user.role !== 'god') {
|
|---|
| 40 | return res.status(403).send('God role required');
|
|---|
| 41 | }
|
|---|
| 42 | next();
|
|---|
| 43 | }
|
|---|