Возвращаемое значение из вспомогательной функции, не ожидаемой - PullRequest
0 голосов
/ 31 января 2019

Я довольно новичок в NodeJS и Socket.io.У меня есть мой основной файл как index.js , который вызывает вспомогательную функцию verifyToken, но он не ждет возвращаемого значения из вспомогательной функции и продолжает работу.

Я добавилconsole.log для отслеживания потока выполнения, как показано ниже:

Файл: index.js

socket.on('authenticate', function(data, ack) {
    var employeeID = data.employeeID;
    var token = data.Token;
    var tokenHelper = require("@helpers/tokenHelper"); //@helpers is an alias by using the module-alias package for helpers folder

    //Connect with helper to verify token
    var isValid = tokenHelper.verifyToken(employeeID, token);
    if(isValid) {
        socket.auth = true;
        ack("Authenticated");
        console.log("Authenticated");
    }
    else {
        ack("Unauthorised");
        console.log("Unauthorised");
    }
});

Файл: tokenHelper.js

var mysqlDatabase = require("@config/mysql");

module.exports = {
    verifyToken: function(employeeID, token, response) {
        var publicKey = fs.readFileSync(path.resolve("SOME_PATH"), "utf8");
        var isValid = false;

        //Verify options
        var verifyOptions = {
            issuer:  issuer,
            subject:  subject,
            audience:  audience,
            expiresIn:  expiresIn,
            algorithm:  ["RS256"]
        };

        //Extract data from received payload
        var receivedPayload = jwt.verify(token, publicKey, verifyOptions);
        var receivedEmailAddress = receivedPayload.sub;
        var receivedEmployeeID = receivedPayload.EmployeeID;
        console.log("Received email: " + receivedEmailAddress);
        console.log("Received id: " + receivedEmployeeID);
        console.log("Employee id: " + employeeID);

        //SQL Query to check EmployeeID in the database, verification of token is successful if entry is found in the database
        if(results !== null) {
            isValid = true;
            console.log("Verification successful");
        }

        return isValid;
    }
};

Текущий консольный журнал:

Полученный адрес электронной почты: user@test.com

Полученный идентификатор: 1

Идентификатор сотрудника: 1

Несанкционировано

Проверка успешна

Ожидаемый журнал консоли:

Получено письмо: user@test.com

Полученный идентификатор: 1

Идентификатор сотрудника: 1

Проверка успешна

Несанкционирован

Ответы [ 2 ]

0 голосов
/ 31 января 2019

Файл: tokenHelper.js

module.exports = {
    verifyToken: async (employeeID, token, response) => {
        try {
            const publicKey = fs.readFileSync(path.resolve('SOME_PATH'), 'utf8');
            let isValid = false;

            const verifyOptions = {
                issuer: issuer,
                subject: subject,
                audience: audience,
                expiresIn: expiresIn,
                algorithm: ['RS256'],
            };

            const receivedPayload = await jwt.verify(token, publicKey, verifyOptions);
            const receivedEmailAddress = receivedPayload.sub;
            const receivedEmployeeID = receivedPayload.EmployeeID;

            console.log(
                `Received email: ${receivedEmailAddress}, Received id: ${receivedEmployeeID} and Employee id: ${employeeID}`
            );

            if (results !== null) {
                isValid = true;
                console.log('Verification successful');
            }

            return isValid;
        } catch (error) {
            console.error(error);
        }
    },
};

Файл: index.js

const tokenHelper = require('@helpers/tokenHelper');
socket.on('authenticate', async (data, ack) => {
    try {
        const employeeID = data.employeeID;
    const token = data.Token;

    var isValid = await tokenHelper.verifyToken(employeeID, token);
    if (isValid) {
        socket.auth = true;
        ack('Authenticated');
        console.log('Authenticated');
    } else {
        ack('Unauthorised');
        console.log('Unauthorised');
    }
    } catch (error) {
        console.error(error);
    }
});
0 голосов
/ 31 января 2019

Вы пропустили обратный звонок в коде.Пожалуйста, замените ваш код следующим, и дайте мне знать, если что-то пошло не так.

Token Helper:

module.exports = {
  async verifyToken = (employeeID, token, response) => {
    const publicKey = fs.readFileSync(path.resolve("SOME_PATH"), "utf8");
    let isValid = false;

    const verifyOptions = {
      issuer: issuer,
      subject: subject,
      audience: audience,
      expiresIn: expiresIn,
      algorithm: ['RS256']
    };

    const receivedPayload = await jwt.verify(token, publicKey, verifyOptions);
    const receivedEmailAddress = receivedPayload.sub;
    const receivedEmployeeID = receivedPayload.EmployeeID;

    console.log(`Received email: ${receivedEmailAddress}, Received id: ${receivedEmployeeID} and Employee id: ${employeeID}`);

    if (results !== null) {
      isValid = true;
      console.log('Verification successful');
    }

    return isValid;
  }
};

Файл: index.js

const tokenHelper = require("@helpers/tokenHelper");
socket.on('authenticate', async (data, ack) => {
  const employeeID = data.employeeID;
  const token = data.Token;

  var isValid = await tokenHelper.verifyToken(employeeID, token);
  if (isValid) {
    socket.auth = true;
    ack('Authenticated');
    console.log('Authenticated');
  } else {
    ack('Unauthorised');
    console.log('Unauthorised');
  }
});

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...