This commit is contained in:
2026-02-16 19:34:35 +00:00
commit 9ab0940ca4
784 changed files with 41710 additions and 0 deletions
@@ -0,0 +1,79 @@
import type { MiddlewareHandler } from 'hono';
import { verify } from '@@/jwt';
import * as errors from '@@/custom-errors';
import { isOriginAllowed } from './origin-validation';
import { officerdb, eq, Users, TokenBlacklist } from 'officerdb';
// Role permissions: which HTTP methods each role can use
// Roles not listed here are denied by default (fail-safe)
const ROLE_PERMISSIONS: Record<string, string[]> = {
Member: ['GET'],
Admin: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
Owner: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
'Super Admin': ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
};
function isMethodAllowed(role: string | null, method: string): boolean {
if (!role) return false;
const allowedMethods = ROLE_PERMISSIONS[role];
if (!allowedMethods) return false; // Unknown role = no access
return allowedMethods.includes(method);
}
export const userMiddleware: MiddlewareHandler = async function (ctx, next) {
const { authorization } = ctx.req.header();
// Support token in query param for media elements (<audio>, <video>, <img>)
// that cannot send Authorization headers
let token: string | undefined;
if (authorization) {
[, token] = authorization.split(' ');
} else {
token = ctx.req.query('token') || undefined;
}
if (!token) throw errors.UNAUTHORIZED();
// Validate origin for authenticated routes
const origin = ctx.get('origin') as string | undefined;
const host = ctx.req.header('host');
if (!isOriginAllowed(origin, host)) {
throw errors.FORBIDDEN('Invalid origin');
}
try {
const user = await verify(token);
if (!user) throw errors.UNAUTHORIZED();
// Check if token is blacklisted (explicit signout)
if (user.jti) {
const blacklisted = await officerdb.query.TokenBlacklist.findFirst({
where: eq(TokenBlacklist.jti, user.jti),
});
if (blacklisted) throw errors.UNAUTHORIZED();
}
// Check if token was issued before password change
if (user.iat && user.id) {
const dbUser = await officerdb.query.Users.findFirst({
where: eq(Users.id, user.id),
columns: { passwordChangedAt: true },
});
if (dbUser?.passwordChangedAt) {
// iat is in seconds, passwordChangedAt is in milliseconds
const tokenIssuedAt = user.iat * 1000;
if (tokenIssuedAt < dbUser.passwordChangedAt) {
throw errors.UNAUTHORIZED();
}
}
}
if (!isMethodAllowed(user.role, ctx.req.method)) {
throw errors.FORBIDDEN('Insufficient permissions');
}
ctx.set('user', user);
return next();
} catch (ex) {
if (ex instanceof errors.CustomError) throw ex;
throw errors.UNAUTHORIZED();
}
};