Last active
October 9, 2018 14:39
-
-
Save sudipp/0b26b9d4ead5e0ccbdc45adb0f605bf7 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
const fs = require('fs'); | |
const config = require('../assets/configs/config'); | |
const jwt = require('jsonwebtoken'); | |
const urlBuilder = require('build-url'); | |
//We use Public/Private key, but you can use Secret (with HMAC algorithm) | |
let secretOrPrivateKey = fs.readFileSync(config.sslPrivatekey_path); | |
let secretOrPublicKey = fs.readFileSync(config.sslPublickey_path); | |
function uriTokenizer(signOptions, verifyOptions){ | |
// Sign options incluses | |
// algorithm, keyid, expiresIn, notBefore, audience, subject, issuer, jwtid, noTimestamp, header, encoding | |
this.signOptions= signOptions; | |
// Verify options incluses | |
// algorithms, audience, clockTimestamp, clockTolerance, issuer, ignoreExpiration, ignoreNotBefore, jwtid, subject | |
this.verifyOptions = verifyOptions; | |
} | |
//To sign a Uri with any payload provided | |
uriTokenizer.prototype.signUri = async function (uri, payload){ | |
let that=this; | |
const promise = new Promise(function(resolve, reject) { | |
jwt.sign(payload, secretOrPrivateKey, that.signOptions, function(err, token) { | |
if(err) | |
return reject(err); | |
return resolve( | |
urlBuilder(uri, {queryParams: {token: token }}); //append Toekn query string with the Uri | |
); | |
}); | |
}); | |
return await promise; | |
}; | |
//An async middleware to verify if a token passed is valid & not expired. | |
uriTokenizer.prototype.verifyUriRequest = async function (req,res,next){ | |
const token = req.query.token; | |
if (!token) //if token is missing | |
return res.status(400).json({ message: config.TOKEN_NOT_FOUND_MESSAGE }); | |
jwt.verify(token, secretOrPublicKey, this.verifyOptions, (err, payload) => { | |
//return 403 in case of TokenExpiredError/JsonWebTokenError | |
if(err) return res.status(403).json({ message: err.message }); | |
return next(); | |
}); | |
}; | |
module.exports = uriTokenizer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment