Skip to content

Instantly share code, notes, and snippets.

@runvnc
Last active March 7, 2016 01:17
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 runvnc/5689ab4cff350e10108e to your computer and use it in GitHub Desktop.
Save runvnc/5689ab4cff350e10108e to your computer and use it in GitHub Desktop.
import cryptojs from 'crypto-js';
import Token from './models/token';
import User from './models/user';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
dotenv.load();
const {ENCRYPT, DECRYPT} = process.env;
export async function authenticate (req, res, next) {
const token = req.get('Authorization') || '';
try {
const tokenHash = cryptojs.MD5(token).toString();
const instance = await Token.findOne({tokenHash});
if (!instance) { throw new Error('Authorization token invalid'); }
req.token = instance.tokenHash;
const decodedJWT = jwt.verify(token, DECRYPT);
const bytes = cryptojs.AES.decrypt(decodedJWT.token, ENCRYPT);
const tokenData = JSON.parse(bytes.toString(cryptojs.enc.Utf8));
const user = await User.findById(tokenData.id);
if (!user) { throw new Error('Invalid user id') }
req.user = user;
next();
} catch(e) {
res.status(401).send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment