UNPKG

jwtinoauth

Version:

Simple script helper for jwt token verification and creation

111 lines (96 loc) 2.75 kB
/********************************************* * Created by Armen Hakobyan * * Json web token methods *********************************************/ const jwt = require('jsonwebtoken'); const fs = require('fs'); /************************************ * @returns {String} //private key */ function getPrivateKey() { return fs.readFileSync("./node_modules/jwtinoauth/jwt_key/private.key",'utf-8'); } /************************************ * @returns {String} //public key */ function getPublicKey() { return fs.readFileSync("./node_modules/jwtinoauth/jwt_key/public.key",'utf-8'); } /*************************** * Validate token from req.body using jwt module * * @param req * @param res * @param next * @returns {any | Promise<any>} */ function validateToken(req,res,next){ let token = req.body.token || req.params.token || req.headers.Authorization || req.query.token; Verify(token,req,res,next) } function Verify(token,req,res,next) { if(token == 'null'){ return res.json({error : true, code : 401, message : "Forbidden"}) } const verifyOptions = { expiresIn: "1d", algorithm : "RS256" }; jwt.verify(token,getPublicKey(),verifyOptions,function (err,decode) { if(err){ res.json({ error : true, code : 401, message : "Forbidden" }); }else{ req.user = decode; next(); } }); } function forceVerify(token,cb) { const verifyOptions = { expiresIn: "1h", algorithm : "RS256" }; jwt.verify(token,getPublicKey(),verifyOptions,function (err,decode) { if(err){ cb({ error : true, code : 401, message : "Forbidden" }); }else{ cb({ error: false, code : 401, message:decode }) } }); } /************************************ * Create new token * * Set json web token documentation for nodejs * * @param data {Object} //Information that must be stored in the token * @param exp {Object}//token expiration date * @returns {Promise<String>} //token */ function signToken(data,exp){ return new Promise((resolve,rejecet)=>{ let config = { algorithm :"RS256", }; if(exp){ config.expiresIn = exp } jwt.sign(data,getPrivateKey(),config,(err,token)=>{ if(err){ return rejecet(err); } resolve(token); }); }); } module.exports.validateToken = validateToken; module.exports.signToken = signToken; module.exports.forceVerify = forceVerify;