Skip to content

Instantly share code, notes, and snippets.

@abeisgoat
Created September 12, 2017 19:22
Show Gist options
  • Save abeisgoat/832d6f8665454d0cd99ef08c229afb42 to your computer and use it in GitHub Desktop.
Save abeisgoat/832d6f8665454d0cd99ef08c229afb42 to your computer and use it in GitHub Desktop.
const admin = require("admin");
function getFirebaseUser(req, res, next) {
console.log("Check if request is authorized with Firebase ID token");
if (
!req.headers.authorization ||
!req.headers.authorization.startsWith("Bearer ")
) {
console.error(
"No Firebase ID token was passed as a Bearer token in the Authorization header.",
"Make sure you authorize your request by providing the following HTTP header:",
"Authorization: Bearer <Firebase ID Token>"
);
res.status(403).send("Unauthorized");
return;
}
let idToken;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer ")
) {
console.log("Found 'Authorization' header");
idToken = req.headers.authorization.split("Bearer ")[1];
}
admin
.auth()
.verifyIdToken(idToken)
.then(decodedIdToken => {
console.log("ID Token correctly decoded", decodedIdToken);
req.user = decodedIdToken;
next();
})
.catch(error => {
console.error("Error while verifying Firebase ID token:", error);
res.status(403).send("Unauthorized");
});
}
@cyberhuman
Copy link

The second "if" is useless since the second condition is complementary to the first one: !(!x || !y) == !(!(x && y)) == x && y

@valentinMERCIER
Copy link

const admin = require("firebase-admin");
instead of :
const admin = require("admin");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment