Created
October 10, 2016 18:48
-
-
Save kyle-ssg/a2fccaad7fb9060c794f71e5c34a26a3 to your computer and use it in GitHub Desktop.
Treat any API call with Auth header the same as a call with username/password body
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jwt = require('jsonwebtoken'); | |
const privateKey = 'secret'; | |
module.exports = function (req, res, next) { | |
const oldSend = res.json; | |
const token = req.headers.authorization; | |
var body = req.body; | |
//When returning json from a username+password request, return a signed token | |
if (res.statusCode == 200 && body.username) { | |
res.json = function (data) { | |
data.token = jwt.sign({ username: body.username, password: body.password }, privateKey); | |
oldSend.apply(res, [data]); | |
}; | |
} | |
//If there's a auth header, add username and password to request body from decoded value | |
if (token && !body.username) { | |
jwt.verify(token, privateKey, function (err, decoded) { | |
if (decoded) { | |
req.body = Object.assign({}, body, decoded); | |
console.log(req.body); | |
} | |
next(); | |
}); | |
} else { | |
next(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment