Skip to content

Instantly share code, notes, and snippets.

@LeoNero
Created September 2, 2016 03:16
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 LeoNero/68a8188f4dbbf24dea8143255ed07a4c to your computer and use it in GitHub Desktop.
Save LeoNero/68a8188f4dbbf24dea8143255ed07a4c to your computer and use it in GitHub Desktop.
'use strict';
const moment = require('moment');
const jwt = require('jwt-simple');
const config = require('../config/config.js');
exports.createJWT = user => {
let payload = {
sub: user._id,
iat: moment().unix(),
exp: moment().add(14, 'days').unix()
};
return jwt.encode(payload, config.TOKEN_SECRET);
};
exports.handleError = (res, err) => {
return res.send(400, err);
};
exports.ensureAuthenticated = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
}
let token = req.headers.authorization.split(' ')[1];
let payload = null;
try {
payload = jwt.decode(token, config.TOKEN_SECRET);
} catch (err) {
return res.status(401).send({ message: err.message });
}
if (payload.exp <= moment().unix()) {
return res.status(401).send({ message: 'Token has expired' });
}
req.user = payload.sub;
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment