Gate admin menu and authoring with shared JWT

This commit is contained in:
2026-08-15 09:29:08 +02:00
parent eeaa4138fa
commit 8f1f5a8743
16 changed files with 366 additions and 52 deletions
+38
View File
@@ -0,0 +1,38 @@
import type { NextFunction, Request, Response } from 'express'
import jwt, { type JwtPayload } from 'jsonwebtoken'
export type OsintClaims = JwtPayload & { role?: string; isAdmin?: boolean }
declare global {
namespace Express {
interface Request { authClaims?: OsintClaims }
}
}
export function authenticateJwt(req: Request, _res: Response, next: NextFunction) {
const authorization = req.headers.authorization
const token = req.cookies?.auth_token || (authorization?.startsWith('Bearer ') ? authorization.slice(7) : undefined)
const secret = process.env.JWT_SECRET
if (token && secret) {
try {
const decoded = jwt.verify(token, secret)
if (typeof decoded !== 'string') req.authClaims = decoded as OsintClaims
} catch { /* An absent, expired, or invalid cookie is an anonymous session. */ }
}
next()
}
export function hasAdminClaim(req: Request) {
return req.authClaims?.role === 'admin' || req.authClaims?.isAdmin === true
}
export function requireAdmin(req: Request, res: Response, next: NextFunction) {
if (!hasAdminClaim(req)) return res.status(403).json({ error: 'Administrator claim required' })
next()
}
export function createDevelopmentAdminToken() {
if (process.env.NODE_ENV === 'production') throw new Error('Development sessions are disabled in production')
if (!process.env.JWT_SECRET) throw new Error('JWT_SECRET is required')
return jwt.sign({ sub: 'osint-local-admin', role: 'admin', isAdmin: true }, process.env.JWT_SECRET, { expiresIn: '7d' })
}