Как внедрить токен проверки jwt в узел js - PullRequest
0 голосов
/ 25 апреля 2019

Я попытался реализовать генерацию токена jwt в узле js.Я получил токен jwt, но как проверить токен с помощью операции js crud. Но я получил верный код токена jwt с помощью функции обратного вызова. Без функции обратного вызова, используемой для реализации асинхронного / awit Функция реализовать.

index.js

router.post('/', async (req, res) => {
    (async function() {
        try {
          await client.connect();
          console.log("Connected correctly to server");
          const db = client.db('olc_prod_db');

          //Validation
          const { error } = validate.validate(req.body);
          if (error)
          {
            return res.status(400).send(error.details[0].message);
          }
          else
          {
            const check_login = req.body
            const r = await db.collection('UserRegistration').find().toArray();
            r.forEach(element => {
                if(element['username'] == check_login['username'])
                {
                    const token = get_token.validate(req.body)
                    res.send({"token ":token})
                }
                else 
                {
                    return res.send(401,"Un Authorized");
                }
            });

          }
          client.close();
        } catch(err) {
          console.log(err.stack);
        }
      })();

  });

authtoken.js

var jwt = require('jsonwebtoken')
function get_token(userdata)
{

    var accessToken = jwt.sign(userdata, 'secretkey', {
        //Set the expiration
        expiresIn: 3600 //we are setting the expiration time of 1 hr. 
    });
    //send the response to the caller with the accesstoken and data
    console.log('Authentication is done successfully.....');
    return accessToken

}





exports.validate = get_token;
...