Last active
March 7, 2016 01:17
-
-
Save runvnc/5689ab4cff350e10108e to your computer and use it in GitHub Desktop.
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
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