Advertisement
iPhaco

REFRESH DEL TOKEN NODE , JWT-SIMPLE Y SEQUELIZE

May 20th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //REFRESH TOKEN
  2.  
  3.  
  4. //CREACIÓN DEL TOKEN
  5. exports.createToken = function(usuario){
  6.  
  7.     var payload ={
  8.         id:usuario.id,
  9.         nombre: usuario.nombre,
  10.         apellidos: usuario.apellidos,
  11.         rol:usuario.rol,
  12.         imagen:usuario.imagen,
  13.         iat:moment().unix(),
  14.         exp:moment().add(15,'days').unix()
  15.     };
  16.  
  17.     //Ciframos los datos del usuario con secret
  18.     return jwt.encode(payload,clave_secreta);
  19. };
  20.  
  21. //MIDDLEWARE DEL TOKEN (llamada a la api si ofrece errores 401 o 403)
  22. exports.delvolverIdTokenRefrescar = function(req,res,next){
  23.     if(!req.headers.authorization){
  24.         return res.status(403).send({message: 'La petición no tiene la cabecera de autenticación'});
  25.     }
  26.     //Eliminamos las comillas que nos lleguen del token
  27.     var token = req.headers.authorization.replace(/['"]+/g,'');
  28.  
  29.         console.log(token)
  30.        
  31.         var token_descifrado = jwt.decode(token,clave_secreta,true);
  32.        
  33.          res.locals.id = token_descifrado.id; //Aquí obtengo el id del usuario
  34.  
  35.  
  36.    
  37.  
  38.     next(); //Para salir del middleware
  39. };
  40.  
  41. //FUNCIÓN PARA DEVOLVER NUEVO TOKEN REFRESCADO
  42.  
  43. function refrescarToken(req,res){
  44.     var id_usuario=null;
  45.  
  46.     if ( res.locals.id) {
  47.              id_usuario =  res.locals.id; //Aquí obtengo el id del usuario del middleware
  48.      }
  49.      console.log("Midlleware",id_usuario);
  50.  
  51.     //Busco el usuario con el id
  52.      user.findById(id_usuario).then(function(usuario) {
  53.             if (!usuario) {
  54.                  return res.status(404).send({mesage:'Error al buscar usuario'});
  55.             }
  56.             else{
  57.                 console.log(usuario);
  58.                 //Creo el token nuevo
  59.                  res.status(200).send({
  60.                     token: jwt.createToken(usuario)
  61.                 });
  62.             }
  63.  
  64.             });
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement