43 lines
1.2 KiB
JavaScript
43 lines
1.2 KiB
JavaScript
const logger = require("../utils/logger");
|
|
const admin = require("firebase-admin");
|
|
|
|
/**
|
|
* Lite Firebase ID token validator.
|
|
* - Only accepts Authorization: Bearer <token>
|
|
* - Sets req.user to the decoded token on success
|
|
*/
|
|
const validateFirebaseIdTokenLite = async (req, res, next) => {
|
|
const authHeader = req.headers.authorization || "";
|
|
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
|
|
|
if (!match) {
|
|
logger.log("api-authorization-call", "warn", null, null, {
|
|
type: "unauthorized",
|
|
reason: "missing Bearer token",
|
|
path: req.path,
|
|
body: req.body
|
|
});
|
|
return res.status(401).send("Unauthorized");
|
|
}
|
|
|
|
const idToken = match[1].trim();
|
|
|
|
try {
|
|
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
|
|
req.user = decodedIdToken;
|
|
return next();
|
|
} catch (error) {
|
|
logger.log("api-unauthorized-call", "warn", null, null, {
|
|
type: "unauthorized",
|
|
reason: "invalid or expired token",
|
|
path: req.path,
|
|
body: req.body,
|
|
code: error?.errorInfo?.code || error?.code,
|
|
message: error?.message
|
|
});
|
|
return res.status(401).send("Unauthorized");
|
|
}
|
|
};
|
|
|
|
module.exports = validateFirebaseIdTokenLite;
|