Skip to content

Instantly share code, notes, and snippets.

@swelham
Last active August 29, 2015 13:55
Show Gist options
  • Save swelham/8691247 to your computer and use it in GitHub Desktop.
Save swelham/8691247 to your computer and use it in GitHub Desktop.
//# api/policies/authenticated.js
var jwt = require('jwt-simple');
var moment = require('moment');
// move this to global config
var secret = 'xStmbyc066BOFn40gIr29y09Ud94z1P7';
module.exports = function (req, res, next) {
// currently just using url query for testing
// this will actually come from the http header
var tokenValue = req.query.token;
var issueDate = req.query.issue;
// validate we have all params
if (!tokenValue || !issueDate) {
return res.send(400);
}
var issued = moment.utc(issueDate);
// check the issue date to see if the token has expired (quick way to kick out expired tokens)
// to check accurately for minutes we need to check in seconds as moment rounds the result down
// to the nearest unit
if (moment.utc().diff(issued, 'seconds') > 1800) {
return res.send(401);
}
// needs to be wrapped in try/catch
var token = jwt.decode(tokenValue, secret);
// validate that the issueDate passed in matches the issue date the token was created with
if (token.issued !== issueDate) {
return res.send(400);
}
// find the user and set req.user
User
.findOne({ id: token.id })
.done(function (err, user) {
if (err) return res.send(500);
if (!user) return res.send(404);
req.user = user;
return next();
});
};
// this is how tokens are generated
// this code would end up in a sails service
var jwt = require('jwt-simple');
var moment = require('moment');
// move this to global config
var secret = 'xStmbyc066BOFn40gIr29y09Ud94z1P7';
// we create a token with the encoded id (this is the user id) and the date the token was created
// we include the date so that tokens can be expired
function generateToken (id) {
var issueDate = moment().utc().format();
// needs to be wrapped in try/catch
return {
issued: issueDate,
token: jwt.encode({ id: id, issued: issueDate }, secret)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment