0

I'm beginning with Passport and I can't seem to get the login system to work.

React code:

import React, { Component } from 'react';
import 'antd/dist/antd.css';  // or 'antd/dist/antd.less'
import { Card, Col, Row, Icon, Button, Input, Modal } from 'antd';

class App extends Component {

  state = {
    username: undefined,
    password: undefined
  }

  login(username, password) {
      fetch('http://localhost:8080/login', {
        method: 'post',
        headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
      }).then(function(response) {
        console.log("1111", response.json())
      }).then(function(data) {
        console.log("22222", data);
      }).catch((error) => {
          console.log("33333", error)
        });
    }

  render() {
    return (
      <div className="App">

        <Modal
          title="Log in"
          visible={this.state.modalVisible}
          onOk={() => this.setModalVisible(false)}
          onCancel={() => this.setModalVisible(false)}
          footer={null}
          type="primary"
        >
          <Input style={{marginBottom: "10px"}} name="username" onChange={this.onChangeUsername}/>
          <Input style={{marginBottom: "20px"}} name="password" onChange={this.onChangePassword}/>
          <Button style={{width: "100%"}} onClick={() => this.login(this.state.username, this.state.password)}> Login </Button>
        </Modal>

      </div>
    );
  }
}

export default App;

Node backend, called by this React component:

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);
      }
      checkLogIn(request, response);
      return response.send(true);
    });
  })(request, response);
});

Passport.js

 passport.use(
  'local-login',
  new LocalStrategy({
   usernameField : 'username',
   passwordField: 'password',
   passReqToCallback: true
  },
  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, req.flash('loginMessage', 'No User Found'));
    }
    if(!bcrypt.compareSync(password, rows[0].password))
     return done(null, false, req.flash('loginMessage', 'Wrong Password'));

    return done(null, rows[0]);
   });
  })
 );

in the Chrome console this is what I'm getting:

1111 Promise {} App.js:30
22222 undefined

How can I modify this code so that it returns the user's username if his credentials are correct, and console.log an error message otherwise?

Thanks!

mokiliii Lo
  • 587
  • 3
  • 13
  • 26
  • Instead of `console.log("1111", response.json())` you need `return response.json();` otherwise the data returned by the API request is discarded. You also need to actually send the login data to the backend; right now your `fetch()` isn't sending anything. Thirdly you need to change your backend code to only send back JSON; for instance you don't want to call `req.flash` and the like. –  Nov 13 '18 at 13:34
  • Thanks, but how exactly do I send 'username' and 'password' in my login() function? – mokiliii Lo Nov 13 '18 at 14:24
  • https://stackoverflow.com/questions/29775797/fetch-post-json-data –  Nov 13 '18 at 14:25
  • Okay I have done those 3 things, but now I'm getting 'False' in the Chrome console when I `console.log("22222", data);` any idea? – mokiliii Lo Nov 13 '18 at 14:33
  • Start debugging. Insert `console.log("username:", username);` as first line into the function you're passing to `LocalStrategy`. The docs also seem to suggest a slightly different setup: http://www.passportjs.org/docs/username-password/ –  Nov 13 '18 at 14:42
  • When I do this, Node outputs `[0] username: { message: 'Missing credentials' }` – mokiliii Lo Nov 13 '18 at 14:56
  • I've made a newer, cleaner post with the modifications you suggested: https://stackoverflow.com/questions/53283986/beginner-passport-react-login-system-not-working – mokiliii Lo Nov 13 '18 at 15:11

0 Answers0