merge: combine all features from both codebases - mobile dashboard + layer panel + notifications + shares + all fixes
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Shared Auth Middleware – extractToken, requireAuth, requireAdmin
|
||||
*/
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { AuthService } from './AuthService.js';
|
||||
import type { DBUser } from '../database/DatabaseInterface.js';
|
||||
|
||||
export function extractToken(request: FastifyRequest): string | null {
|
||||
const auth = request.headers?.authorization;
|
||||
if (auth && auth.startsWith('Bearer ')) {
|
||||
return auth.slice(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Require any authenticated user (valid session).
|
||||
* Returns the user object or null (and sends error reply).
|
||||
*/
|
||||
export function requireAuth(request: FastifyRequest, reply: FastifyReply, authService: AuthService): DBUser | null {
|
||||
const token = extractToken(request);
|
||||
if (!token) {
|
||||
reply.code(401).send({ error: 'Authentication required' });
|
||||
return null;
|
||||
}
|
||||
const user = authService.getUserFromSession(token);
|
||||
if (!user) {
|
||||
reply.code(401).send({ error: 'Invalid or expired session' });
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Require admin role (valid session + admin role).
|
||||
* Returns the user object or null (and sends error reply).
|
||||
*/
|
||||
export function requireAdmin(request: FastifyRequest, reply: FastifyReply, authService: AuthService): DBUser | null {
|
||||
const user = requireAuth(request, reply, authService);
|
||||
if (!user) return null;
|
||||
if (user.role !== 'admin') {
|
||||
reply.code(403).send({ error: 'Admin access required' });
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
Reference in New Issue
Block a user