public verifyToken(token: string, next: (err: Error, payload: any) => void) {
     let options: jwt.SignOptions = {
         expiresIn: api.helpers.Config.settings.expiration_jwt_minutes * 60,
         issuer: 'tforex-gateway',
         jwtid: 'uniqueId',
     };
     jwt.verify(token, api.helpers.Config.settings.jwt_secret, options, next);
 }
Beispiel #2
0
apiRoutes.use((req:any, res, next) => {

  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  // decode token
  if (token) {

    // verifies secret and checks exp
    jwt.verify(token, app.get('superSecret'), (err, decoded) => {      
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;    
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });
    
  }
});
Beispiel #3
0
export const getUser = async (
  apiSecret: string,
  prisma: Prisma,
  req: IncomingMessage,
): Promise<NexusGenFieldTypes['User'] | null> => {
  const { authorization } = req.headers;
  if (authorization == null) return null;
  const token = authorization.replace('Bearer ', '');

  let decoded = {};
  try {
    decoded = jwt.verify(token, apiSecret);
  } catch (error) {
    if (error.name !== 'JsonWebTokenError') {
      // eslint-disable-next-line no-console
      console.log(error);
    }
    return null;
  }

  const hasUserId = (decoded: any): decoded is JsonWebTokenPayload =>
    'userId' in decoded;
  if (!hasUserId(decoded)) return null;

  const user = await prisma.user({ id: decoded.userId });
  if (user == null) return null;

  // Do not fetch user webs, we don't need it. getUser is used only for auth.
  return { ...user, webs: [] };
};
        return(req, res, next) => {

          if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            const token = req.headers.authorization.split(' ')[1];

            const allowAll = true;
            const allowedOrigins = ['http://localhost:3000', 'http://localhost:4200', 'http://www.resucitoapp.com'];
            if (allowAll || allowedOrigins.indexOf(req.header('Origin')) > -1) {
                if (allowAll) {
                  res.setHeader('Access-Control-Allow-Origin', '*');
                } else {
                  res.setHeader('Access-Control-Allow-Origin', req.header('Origin'));
                }
                res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
                res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
                res.setHeader('Access-Control-Allow-Credentials', true);
            } else {
                return res.status(401).json('Origen no permitido');
            }

            jwt.verify(token, 'my-secret', (err, payload) => {
              if (!err) {
                // confirm identity and check user permissions
                req.payload = payload;
                next();
              } else {
                 return res.status(403).json(err);
              }
            });
          } else {
            return res.status(401).json('El token de acceso no es válido.');
          }
        };
Beispiel #5
0
userRoutes.use(function(req, res, next) {

  // check header or url parameters or post parameters for token
  var token = req.headers['authorization'];
  // decode token
  if (token) {
    var token = token.replace('Bearer ', '')
    // verifies secret and checks exp
    jwt.verify(token, config.secret, function(err, decoded) {
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });
      } else {
        // if everything is good, save to request for use in other routes
        //req.decoded = decoded;
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({
      success: false,
      message: 'No token provided.'
    });

  }
});
Beispiel #6
0
    router.get('/refresh_token/:token', function(req, res) {
        jwt.verify(req.params.token, config.token_secret, function(err, decoded) {
            if (err) {
                res.status(401).json({ error: 'Unauthorized', message: 'failed to authenticate token' });
                return;
            }



            // create the payload for the token
            let payload = decoded; // reuse the payload
            delete payload.exp; // remove the exp date from the payload
            let options = {
                expiresIn: config.time_until_token_expiration
            };

            // create a token and send it to the user
            let token = jwt.sign(payload, config.token_secret, options, function(err, token) {
                if (err) {
                    res.status(500).json({ error: 'Internal Server Error', message: 'error generating token', username: req.body.username });
                    return;
                }

                let exp_date = new Date();
                exp_date.setSeconds(exp_date.getSeconds() + config.time_until_token_expiration);

                res.status(200).json({ message: 'here is a new token', token: token, exp: exp_date });
            });
        });
    });
Beispiel #7
0
    return function(req, res, next) {
        // get the token from the request
        var token = req.headers['x-auth-token'] || req.body.token || req.query.token || req.headers['x-access-token'];

        // if not token is provided, send an error
        if (!token) {
            res.status(401).json({ error: 'Unauthorized', message: 'a token must be provided to demonstrate authentication' });
            return;
        }

        jwt.verify(token, config.token_secret, function(err, decoded) {
            if (err) {
                res.status(401).json({ error: 'Unauthorized', message: 'failed to authenticate token' });
                return;
            }

            // make sure that this is a token for the correct user
            if (decoded.username !== req.params.username) {
                res.status(401).json({ error: 'Unauthorized', message: 'the token provided is not for the user specified in the url', username: req.params.username });
                return;
            }

            // save the decoded payload for any other middleware/routes to use
            req.token_payload = decoded;

            // run the next middeware function or route handler
            next();
        });
    };
 export function authenticate(req: express.Request, res: express.Response) {
         if(req.header('Authorization')){
                 let token = req.header('Authorization');
                 jwt.verify(token, config.JwtStrategy.secretOrKey, {}, function (err: any, userInfo: any) {
                  if(err) throw err;
                 if(userInfo === null) {
                          res.send({
                                 isSuccess: false,
                                 msg: 'token verification is failed!'
                         })
                 }
                 res.send({
                         isSuccess: true,
                         userName: userInfo.username
                 })
         })
         }else{
                 res.send({
                         isSuccess: false,
                         msg: 'There is no token!'
                 })
         }
         
         
        
 }
var middleware = function (req, res, next) {
    let token = req.headers.authorization;
    if (token !== undefined) {
        let jwtoken = token.split(" ")[1];
        jwt.verify(jwtoken, Config.secret, (error, decoded) => {
            if (error) {
                res.locals.loggedIn = false;
                res.locals.user = {};
                res.locals.role = "";
                next();
            } else {
                //good, authenticated request
                delete decoded.user.password;

                res.locals.loggedIn = true;
                res.locals.user = decoded;
                res.locals.user_id = decoded.user._id;
                res.locals.role = res.locals.user.user.role;

                next();
            }
        });
    } else {
        res.locals.loggedIn = false;
        res.locals.user = {};
        res.locals.role = "";
        next();
    }
};
Beispiel #10
0
        return new Promise(async (resolve, reject) => {
            if (!p.token) {
                reject("You must provide a valid token");
                return;
            }
            let options: any = { "issuer": this.issuer.value };

            try {
                let key = this.secretKey.value;
                //options.algorithms=[ALGORITHM];

                jwt.verify(p.token, key, options, (err, payload) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        const token = payload.value;
                        resolve(token);
                    }
                });
            }
            catch (err) {
                reject({ error: err, message: "Invalid JWT token" });
            }
        });