简体   繁体   English

使用 JWT 进行 NodeJS 用户身份验证

[英]NodeJS user authentication with JWT

I am just started with nodejs with react frontend.我刚开始使用带有反应前端的 nodejs。 But I have some issue while authenticating user.但是我在验证用户时遇到了一些问题。 I am trying to fetch user with specific email and password.我正在尝试使用特定的电子邮件和密码获取用户。 My api for this is as follows: I have created three files controller, services and router files for any api request.我的 api 如下:我为任何 api 请求创建了三个文件控制器、服务和路由器文件。

//userServices.js
const db = require('./../../db-connection/connection')

userAuth: (params, callback) => {
    db.query(`SELECT * FROM Users WHERE email = ?`,[params.email],
      (error, result, fields) => {
        if(!error) {
          console.log('result = ' + result[0]);
          return callback(error, result[0])
        }
        else
          return callback(error)
      });
  }

And this is my userController js file.这是我的 userController js 文件。

//userController.js
const {create, userindex, userAuth} = require('./UserServices');
const {genSaltSync, hashSync, compareSync} = require('bcrypt');
const {sign} = require('jsonwebtoken');

userLoginAuth: (req, res) => {
    const body = req.body;
    userAuth(body, (error, results) => {
      if (error)
        console.log(error);

      if (!results) {
        return res.json({
          success: 0,
          data: 'Invalid email or password'
        })
      }

      const result = compareSync(body.password, results.password);
      if(!result) {
        results.password = undefined;
        const jsontoken = sign({result: results}, 'choegyel123', {
          expiresIn: '1h'
        });
        return res.json({
          success: 1,
          message: 'Login successful',
          token: jsontoken
        })
      } else
        console.log('password' + result.password)
      return res.json({
        success: 0,
        error: 'Invalid email or password'
      });
    });
  }

But the problem is in userServices.js file.但问题出在 userServices.js 文件中。 My sql query is correctly executed but in callback for the ' results ' i am getting weird object.我的 sql 查询已正确执行,但在“结果”的回调中,我得到了奇怪的对象。 I think I should get some array of corresponding data from the database table and in my console log I am getting [object object].我想我应该从数据库表中获取一些相应数据的数组,并在我的控制台日志中获取 [object object]。 I am not sure what does this actually mean and I am also all sure this is a blocker, since I cannot retrive password with this object in my userController.我不确定这实际上意味着什么,我也确信这是一个阻止程序,因为我无法在我的 userController 中使用此对象检索密码。 Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks!谢谢!

Issues问题

  • compareSync returns a boolean with true indicating correct password. compareSync返回一个布尔值,其中true表示正确的密码。 You're using if(!result) which is the reverse.您正在使用if(!result) ,这是相反的。
  • Make sure your {} are correct on the else确保您的{}else上是正确的
  • You're logging result.password which is undefined because result is your compareSync return value.您正在记录undefined result.password ,因为result是您的 compareSync 返回值。 You meant to log results.password .你的意思是记录results.password Avoid using result and results for two different things because it makes it easy to make these mistakes.避免将resultresults用于两种不同的事情,因为这样很容易犯这些错误。 Something like bcryptResult and resultObj might be better.bcryptResultresultObj这样的东西可能会更好。
  • When you console.log() , pass data as the second argument or make a second log because concatenating objects always shows [object Object] .当您使用console.log() ,将数据作为第二个参数传递或创建第二个日志,因为连接对象始终显示[object Object]

Updated snippet更新的片段

  const result = compareSync(body.password, results.password);
  if(result) {
    results.password = undefined;
    const jsontoken = sign({result: results}, 'choegyel123', {
      expiresIn: '1h'
    });
    return res.json({
      success: 1,
      message: 'Login successful',
      token: jsontoken
    })
  } else {
    console.log('password', results.password)
    return res.json({
      success: 0,
      error: 'Invalid email or password'
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM