Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. import * as admin from 'firebase-admin'
  2. const {
  3. FIREBASE_INFO,
  4. FIREBASE_DATABASE_URL
  5. } = process.env
  6.  
  7. let serviceAccount = JSON.parse(FIREBASE_INFO)
  8.  
  9. admin.initializeApp({
  10. credential: admin.credential.cert(serviceAccount),
  11. databaseURL: FIREBASE_DATABASE_URL
  12. })
  13.  
  14. // when decoded successfully, the ID Token content will be added as `req.user`.
  15. export function validateFirebaseIdToken(req, res, next) {
  16. // Unauthenticated routes go here
  17. if (['/health', '/users/emails'].includes(req.path)) return next();
  18.  
  19. if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
  20. !(req.cookies && req.cookies.__session)) {
  21. res.status(403).send('Unauthorized');
  22. return;
  23. }
  24.  
  25. let idToken;
  26. if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
  27. // Read the ID Token from the Authorization header.
  28. idToken = req.headers.authorization.split('Bearer ')[1];
  29. } else if(req.cookies) {
  30. // Read the ID Token from cookie.
  31. idToken = req.cookies.__session;
  32. } else {
  33. // No cookie
  34. res.status(403).send('Unauthorized');
  35. return;
  36. }
  37. admin.auth().verifyIdToken(idToken).then((decodedIdToken) => {
  38. req.user = decodedIdToken;
  39. return next();
  40. }).catch((error) => {
  41. res.status(403).send('Unauthorized');
  42. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement