const jwt = require('jwt-simple'); const config = require('../config/config'); const moment = require('moment'); exports.Authenticated = function(req, res, next) { if(req.headers.authorization === "") { res.status(401); return res.json({error: "No has iniciado sesión"}); } let token = req.headers.authorization; try{ let payload = jwt.decode(token, config.TOKEN_SECRET, 'HS512'); if(payload.exp < moment().unix()){ return res.json({error: "Sesión Finalizada"}); } req.usuario = payload.sub.split('-')[0]; req.TFA = payload.TFA; if(payload.TFA){ throw new Error("TOken no valid"); } next(); } catch(error){ res.status(401); return res.json({error: "Token no válido"}); } } exports.AuthenticatedFA = function(req, res, next) { if(req.headers.authorization === "") { res.status(401); return res.json({error: "No has iniciado sesión"}); } let token = req.headers.authorization; try{ let payload = jwt.decode(token, config.TOKEN_SECRET, 'HS512'); if(payload.exp < moment().unix()){ return res.json({error: "Sesión Finalizada"}); } if(!payload.TFA){ throw new Error("TOken no valid"); } req.usuario = payload.sub.split('-')[0]; next(); } catch(error){ res.status(401); return res.json({error: "Token no válido"}); } } /*exports.AlreadyToken = function(req, res, next) { if(req.headers.authorization === "") { next(); } let token = req.headers.authorization; try{ let payload = jwt.decode(token, config.TOKEN_SECRET, 'HS512'); //Nueva version, ahora no suelta una excepcion cuando expira el token... if(payload.exp < moment().unix()){ throw Error(); } return res.status(204).end(); } catch(error){ next(); } }*/