Tuesday, 13 November 2018

Beginner Passport/React/Node - isAuthenticated() always returns False

I'm struggling with Passport.js, Node & React combined.​Basically, I'm trying to build a login/registration system. Seems pretty basic, but I can't get it to work.​THE PROBLEM ---> the function isAuthenticated() always returns False. Annoying, since I wanna call that function in `componentDidMount()` in React to check if the user's already logged in.​My noobie guess is that I should maybe use a 'POST' request for the endpoint `/checkIfLoggedIn` and pass in some data, but what data?​I have included the code for the login system (which works), so you guys can see how I manage to log in the user. Maybe the problem comes from the login, where I forget to do something after the user's been logged in?​Here's my code:​​> Routes.js​app.post("/login", function(request, response) {passport.authenticate("local-login", function(err, user, info) {if (err) {return console.log(err);}if (!user) {return response.send(false);}request.logIn(user, function(err) {if (err) {return console.log(err);}request.session.cookie.maxAge = 1000 * 60 * 3;request.session.cookie.expires = false;return response.send(true);});})(request, response);});app.get('/checkIfLoggedIn', (req, res) => {console.log(req.isAuthenticated())});​> React (probably irrelevant here since the problem comes from the backend. here to give some context)checkAuth () {fetch('http://localhost:8080/checkIfLoggedIn').then(response => response.json()).then(data => console.log(data));}login(username, password) {fetch('http://localhost:8080/login', {method: 'POST',body: JSON.stringify({username: username, password: password}),headers : {'Content-Type': 'application/json','Accept': 'application/json, text/plain, */*',}}).then(res=>res.json()).then(res => {if (res === true) { // connection successfullthis.setState({user_connected: true,username: this.state.username,modalVisible: false})} else {message.info('Incorrect credentials');}});}>>>> Passport.js​passport.use('local-login',new LocalStrategy({usernameField : 'username',passwordField: 'password',passReqToCallback: true,failureFlash: true,badRequestMessage : 'Missing username or password.',},function(req, username, password, done){connection.query("SELECT * FROM tbl_users WHERE username = ? ", [username],function(err, rows){if(err)return done(err);if(!rows.length){return done(null, false, { logged: "NO" });}if(!bcrypt.compareSync(password, rows[0].password)) {return done(null, false, { logged: "NO" });}return done(null, rows[0]);});}))}​I am probably missing on something to be able to keep the user authenticated, I really don't know.​Cheers!

Submitted November 13, 2018 at 06:00PM by pythonistaaaaaaa

No comments:

Post a Comment