Skip to content

Instantly share code, notes, and snippets.

@msukmanowsky
Last active March 14, 2019 16:25
Show Gist options
  • Save msukmanowsky/346971ddc1564e0fc3dbaedace028090 to your computer and use it in GitHub Desktop.
Save msukmanowsky/346971ddc1564e0fc3dbaedace028090 to your computer and use it in GitHub Desktop.
Small Express middleware snippet for Cloud Functions to determine if a user is authenticated via Firebase Auth.
const admin = require('firebase-admin');
function getIdToken(req) {
const authHeader = req.header('Authorization') || '';
const parts = authHeader.split('Bearer ');
if (parts.length === 1) return null;
return parts[1];
}
/**
* Auth middleware, ensures that this request came from a firebase user
*/
function authRequired(req, res, next) {
const idToken = getIdToken(req);
if (idToken === null) {
return next(new Error('no authorization token provided'));
}
// TODO: https://firebase.google.com/docs/auth/admin/manage-sessions#detect_id_token_revocation
// See https://firebase.google.com/docs/auth/admin/verify-id-tokens
admin.auth().verifyIdToken(idToken)
.then(token => {
res.locals.token = token;
admin.auth().getUser(token.uid)
.then(user => {
if (user.disabled) {
return next(new Error('user account disabled'));
}
res.locals.user = user;
next();
})
.catch(error => {
next(new Error('error fetching user info'));
});
})
.catch(error => {
next(new Error('auth token invalid'));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment