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!