Skip to content

Instantly share code, notes, and snippets.

@kyle-ssg
Created October 10, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyle-ssg/a2fccaad7fb9060c794f71e5c34a26a3 to your computer and use it in GitHub Desktop.
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
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