51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import type { NextFunction, Request, Response } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { config } from '../config.js';
|
|
|
|
export interface AuthUser {
|
|
id: string;
|
|
email: string;
|
|
role: string;
|
|
allowed_domains: string[];
|
|
}
|
|
|
|
declare global {
|
|
namespace Express {
|
|
interface Request { user?: AuthUser }
|
|
}
|
|
}
|
|
|
|
export function signUser(user: AuthUser): string {
|
|
return jwt.sign(user, config.jwtSecret, { expiresIn: '12h' });
|
|
}
|
|
|
|
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
|
|
const token = req.cookies?.mailadmin_token;
|
|
if (!token) {
|
|
res.status(401).json({ error: 'Not authenticated' });
|
|
return;
|
|
}
|
|
try {
|
|
req.user = jwt.verify(token, config.jwtSecret) as AuthUser;
|
|
next();
|
|
} catch {
|
|
res.status(401).json({ error: 'Invalid session' });
|
|
}
|
|
}
|
|
|
|
export function requireSuperAdmin(req: Request, res: Response, next: NextFunction): void {
|
|
if (!req.user) {
|
|
res.status(401).json({ error: 'Not authenticated' });
|
|
return;
|
|
}
|
|
if (req.user.role !== 'super_admin') {
|
|
res.status(403).json({ error: 'Forbidden: super_admin role required' });
|
|
return;
|
|
}
|
|
next();
|
|
}
|
|
|
|
export function canAccessDomain(user: AuthUser, domain: string): boolean {
|
|
return user.role === 'super_admin' || user.allowed_domains.includes(domain.toLowerCase());
|
|
}
|