Refactor transit_api into a repo/routes module split
Split the 5,441-line index.js into an 86-line bootstrap, thin domain
route modules, shared lib/ helpers, and a repo/ layer that isolates the
DEV_MOCK branches (repo/*.mock.js). Repo methods return {statusCode, body};
routes are one-line wrappers. Pin search_path to "transit.bus" and
document the /bus/ prefix with legacy root aliases (Deprecation header).
Parity verified: 57/57 byte-identical on the stub differential harness
plus 24/24 live read-only responses vs the original against real
PostgreSQL. The only intentional behavior change: mock reorder/delete
bus-line endpoints no longer require a live DB (previously 500 in
DEV_MOCK=1 without PG). DEV_MOCK gate and node --check clean.
This commit is contained in:
@@ -3,10 +3,37 @@ require('dotenv').config();
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
|
||||
const ERROR_LOG_API_URL =
|
||||
process.env.ERROR_LOG_API_URL ||
|
||||
"https://error.xtransit.testinstance.nl/error_log";
|
||||
|
||||
function log(level, message, meta = {}) {
|
||||
const timestamp = new Date().toISOString();
|
||||
console.log(JSON.stringify({ timestamp, level, service: "transit_api", message, ...meta }));
|
||||
}
|
||||
|
||||
async function reportError({ partofservice, error }) {
|
||||
try {
|
||||
await fetch(ERROR_LOG_API_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-internal-api-key": process.env.INTERNAL_API_KEY || "",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
service: "transit_api",
|
||||
partofservice,
|
||||
error,
|
||||
}),
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Middleware to verify JWT token
|
||||
const authMiddleware = (req, res, next) => {
|
||||
const auth = req.headers.authorization;
|
||||
if (!auth || !auth.startsWith('Bearer ')) {
|
||||
log("warn", "Missing or invalid Authorization header", { path: req.originalUrl });
|
||||
return res.status(401).json({ error: 'missing_token' });
|
||||
}
|
||||
|
||||
@@ -16,8 +43,23 @@ const authMiddleware = (req, res, next) => {
|
||||
req.user = payload;
|
||||
next();
|
||||
} catch (err) {
|
||||
log("error", "JWT verification failed", { error: err.message, path: req.originalUrl });
|
||||
void reportError({
|
||||
partofservice: `authMiddleware ${req.method} ${req.originalUrl}`,
|
||||
error: err.stack || err.message,
|
||||
});
|
||||
return res.status(401).json({ error: 'invalid_token' });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { authMiddleware };
|
||||
|
||||
// Middleware to enforce admin role
|
||||
const adminMiddleware = (req, res, next) => {
|
||||
if (!req.user || !req.user.isAdmin) {
|
||||
return res.status(403).json({ error: "forbidden" });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = { authMiddleware, adminMiddleware };
|
||||
|
||||
Reference in New Issue
Block a user