initial commit
This commit is contained in:
38
backend/src/middleware/auth.ts
Normal file
38
backend/src/middleware/auth.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
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 canAccessDomain(user: AuthUser, domain: string): boolean {
|
||||
return user.role === 'super_admin' || user.allowed_domains.includes(domain.toLowerCase());
|
||||
}
|
||||
Reference in New Issue
Block a user