使用Passport

时间:2016-10-29 13:54:16

标签: node.js express reactjs cookies passport.js

My React应用程序已成功登录,后端也正常运行。

问题:这里出了什么问题?这在Postman中工作正常,并保留我的cookie /会话信息。

如何确保react保留从API获取所需的身份验证详细信息?

但是,在呈现新页面并访问我的API以获取用户信息时,我收到了401 Unauthorized错误。

我正在使用emitter来获取我的数据。

我的API使用Postman工作正常,但在React中不起作用。代码如下:

护照登录&用户序列化:

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  connection.query("select * from users where id = "+ id, function(err,user) {
      done(err, user[0]);
    });
});

passport.use('local-signup', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true
  },
  function(req, email, password, done) {
    connection.query("select * from users where email = '"+ email +"'",function(err,user) {
         console.log(user);
       console.log("above row object");
       if (err)
          return done(err);
       if (user.length) {
          return done(null, false);
       } else {
          var passwordHash = sha1(req.body.password)
          var newUserMysql = new Object();
          newUserMysql.name     = req.body.name;
          newUserMysql.password = passwordHash;
                    newUserMysql.email    = req.body.email;
          newUserMysql.group_id = req.body.group_id;

                var insertQuery = "INSERT INTO users (name, password, email, group_id) values ('"+ req.body.name +"','"+ passwordHash +"','"+ req.body.email +"','"+ req.body.group_id +"')";
                  console.log(insertQuery);

          connection.query(insertQuery,function(err,user){
            newUserMysql.id = user.insertId;

            return done(null, newUserMysql);
                });
      }
      });
  }));

我的配置文件信息的反应器:

export default class ProfileController {
constructor(emitter) {
    this.Emitter = emitter;
}
init() {
    this.Emitter.on('GetMyUser', this.getMyUser.bind(this));
}

getMyUser() {
        fetch(`${domain}/api/user/self`, {//This is where it appears to be failing!!!
            method: 'GET',
            credentials: 'include'
        })
        .then((res) => {
            return res.json();
        })
        .then((res) => {
            this.Emitter.emit('OnGetMyUser', res.data); 
        })
        .catch((e) => {
            this.Emitter.emit('OnGetMyUser', 'Failed to load User from Controller.');
            Alert.error('Failed to load user.');
        });
}

}

最后,我的API中的路线本身:

app.get('/api/user/self', function(req, res) {//Get current user by id profile information 
    if (!req.isAuthenticated()) {
        return res.status(401).send({code: 401, message: "Unauthorized"});
    }

    connection.query("SELECT id, name, email, group_id FROM users WHERE id = ?",  [
        req.user.id
    ], function(error, result) {
        if (error) {
            console.log(error);
            return res.status(500).send({code: 500, message: "Internal Server Error"});
        }
        else if (result.rowCount === 0) {
            return res.status(404).send({code: 404, message: "Not found"});
        }

        console.log(result);                
        return res.send(userFull(result));
    });
});

0 个答案:

没有答案