Skip to content

Instantly share code, notes, and snippets.

@sudipp sudipp/uriTokenizer.js
Last active Oct 9, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.