diff --git a/auth_api/index.js b/auth_api/index.js index 2306be5..d453b77 100644 --- a/auth_api/index.js +++ b/auth_api/index.js @@ -87,12 +87,21 @@ app.post("/login", async (req, res) => { if (!ok) return res.status(401).json({ error: "invalid_credentials" }); const isAdmin = ADMIN_USER_CODES.has(Number(user.usercode)); - const payload = { userId: user.id, userCode: user.usercode, isAdmin }; + const payload = { + userId: user.id, + userCode: user.usercode, + isAdmin: Boolean(isAdmin), + }; const token = jwt.sign(payload, JWT_SECRET, { expiresIn: "1h" }); res.json({ token, - user: { id: user.id, userCode: user.usercode, job: user.job, isAdmin }, + user: { + id: user.id, + userCode: user.usercode, + job: user.job, + isAdmin: Boolean(isAdmin), + }, }); } catch (err) { await reportError({ diff --git a/error_log_api/index.js b/error_log_api/index.js index b27b49e..d557460 100644 --- a/error_log_api/index.js +++ b/error_log_api/index.js @@ -9,9 +9,9 @@ const app = express(); app.use(express.json({ limit: "64kb" })); app.use(cors()); -const PORT = Number(process.env.PORT || 5003); -const JWT_SECRET = process.env.JWT_SECRET || ""; -// Admin verification is done by `auth_api` and carried in the JWT as `isAdmin`. +const ERROR_LOG_API_URL = + process.env.ERROR_LOG_API_URL || + "https://error.xtransit.testinstance.nl/error_log"; function toFriendlyError(statusCode) { if (statusCode === 400) return "Controleer je invoer en probeer opnieuw."; @@ -21,6 +21,40 @@ function toFriendlyError(statusCode) { return "Er ging iets mis. Probeer het later opnieuw."; } +async function reportError({ partofservice, error }) { + try { + await fetch(ERROR_LOG_API_URL, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + service: "error_log_api", + partofservice, + error, + }), + }); + } catch (_) {} +} + +app.use((req, res, next) => { + const originalJson = res.json.bind(res); + res.json = (body) => { + if (res.statusCode >= 400 && body && typeof body === "object") { + const rawError = + body.error || body.message || body.details || `HTTP ${res.statusCode}`; + void reportError({ + partofservice: `${req.method} ${req.originalUrl}`, + error: rawError, + }); + return originalJson({ error: toFriendlyError(res.statusCode) }); + } + return originalJson(body); + }; + + next(); +}); + +const PORT = Number(process.env.PORT || 5003); + function normalizeErrorText(value) { if (!value) return "Unknown error"; if (typeof value === "string") return value; @@ -58,7 +92,7 @@ function verifyAdmin(req, res, next) { try { const payload = jwt.verify(auth.slice(7), JWT_SECRET); - if (!payload?.user.isAdmin) { + if (!payload?.isAdmin) { return res.status(403).json({ error: toFriendlyError(403) }); }