diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..002b4aa --- /dev/null +++ b/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["env"] +} diff --git a/index.js b/index.js deleted file mode 100644 index d6eb59d..0000000 --- a/index.js +++ /dev/null @@ -1,5 +0,0 @@ -const auth = require('./src/auth.middleware'); - -module.exports = { - auth -}; diff --git a/lib/auth.middleware.js b/lib/auth.middleware.js new file mode 100644 index 0000000..2dfdb67 --- /dev/null +++ b/lib/auth.middleware.js @@ -0,0 +1,25 @@ +'use strict'; + +var admin = require.main.require('firebase-admin'); + +var logger = require('./util/logger'); + +function firebaseAuthMiddleware(req, res, next) { + var authorization = req.header('Authorization'); + if (authorization) { + var token = authorization.split(' '); + admin.auth().verifyIdToken(token[1]).then(function (decodedToken) { + logger.log(decodedToken); + res.locals.user = decodedToken; + next(); + }).catch(function (err) { + logger.log(err); + res.sendStatus(401); + }); + } else { + logger.log('Authorization header is not found'); + res.sendStatus(401); + } +} + +module.exports = firebaseAuthMiddleware; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..e7d5966 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,7 @@ +'use strict'; + +var auth = require('./auth.middleware'); + +module.exports = { + auth: auth +}; \ No newline at end of file diff --git a/lib/util/logger.js b/lib/util/logger.js new file mode 100644 index 0000000..0e3e792 --- /dev/null +++ b/lib/util/logger.js @@ -0,0 +1,15 @@ +'use strict'; + +var debug = process.env.APP_DEBUG === 'true'; + +function log() { + var _console; + + if (!debug) return; + + (_console = console).log.apply(_console, arguments); +} + +module.exports = { + log: log +}; \ No newline at end of file diff --git a/package.json b/package.json index e3851f9..95c6a24 100644 --- a/package.json +++ b/package.json @@ -2,8 +2,12 @@ "name": "express-firebase-middleware", "version": "1.0.0", "description": "Express middleware for your Firebase applications", - "main": "index.js", + "main": "lib/index.js", + "files": [ + "lib" + ], "scripts": { + "build": "babel src -d lib --ignore spec.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { @@ -23,7 +27,13 @@ }, "homepage": "https://github.com/antonybudianto/express-firebase-middleware#readme", "peerDependencies": { - "express": "^4.15.0", - "firebase-admin": "^4.1.2" + "express": "^4.16.2", + "firebase-admin": "^5.5.0" + }, + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-core": "^6.26.0", + "babel-preset-env": "^1.6.1", + "np": "^2.17.0" } } diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..b422b64 --- /dev/null +++ b/src/index.js @@ -0,0 +1,5 @@ +const auth = require('./auth.middleware'); + +module.exports = { + auth +};