Files
znakovni.hr/packages/backend/src/middleware/auth.ts
johnny2211 3275bc4a4f Add authentication system and admin panel
- Implement JWT-based authentication with login/logout
- Add user management routes and middleware
- Create admin panel for managing words and categories
- Add authentication store and API client
- Update database schema with User model
- Configure CORS and authentication middleware
- Add login page and protected routes
2026-01-17 14:30:22 +01:00

46 lines
1.2 KiB
TypeScript

import { Request, Response, NextFunction } from 'express';
// Extend Express Request type to include user
declare global {
namespace Express {
interface User {
id: string;
email: string;
displayName: string | null;
role: 'ADMIN' | 'USER';
isActive: boolean;
}
}
}
/**
* Middleware to check if user is authenticated
*/
export const isAuthenticated = (req: Request, res: Response, next: NextFunction) => {
if (req.isAuthenticated()) {
return next();
}
res.status(401).json({ error: 'Unauthorized', message: 'Please login to continue' });
};
/**
* Middleware to check if user is an admin
*/
export const isAdmin = (req: Request, res: Response, next: NextFunction) => {
if (req.isAuthenticated() && req.user?.role === 'ADMIN') {
return next();
}
res.status(403).json({ error: 'Forbidden', message: 'Admin access required' });
};
/**
* Middleware to check if user is active
*/
export const isActive = (req: Request, res: Response, next: NextFunction) => {
if (req.isAuthenticated() && req.user?.isActive) {
return next();
}
res.status(403).json({ error: 'Forbidden', message: 'Account is deactivated' });
};