in React when I input any value in text field,then Cannot validate user email and password from back-end.

I register users from react, store those users in back-end but my requirement is when I try to login unregistered user, then show me error user_name and password incorrect. But in my case just redirect the page cannot check users from back-end.

Please check the code and update the code and also inform me what's the problem in it. Thank you in advance.

user Controller login function in codeIgniter

public function login()
  {
      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");

      $user_email = $this->input->post('user_email');
      $Password   = $this->input->post('Password');

      $row = $this->Usermodel->login_mode($user_email);
      var_dump( $row);
      if (count($row) > 0) {
          //verify password

          if (password_verify($Password, $row['Password'])) {

              $response = array(
                  "status" => 'success',
                  'message' => "User Login successfully"
              );
          } else {

              $response = array(
                  "status" => 'error',
                  'message' => "Password and Username does not match"
              );
          }

      } else {

          $response = array(
              "status" => 'error',
              'message' => 'Account does not exist'
          );

      }

        $this->output->set_content_type('application/json')->set_output(json_encode($response));
  }

user model login function

public function login_mode($user_email){
      $query = $this->db->get_where('users',$user_email);
      echo $query->row_array();
  }

PostData.js

export function PostData(type,userData){
  let headers = new Headers();

  let BaseUrl = 'http://localhost/API/UserController/'
  return new Promise((resolve,reject)=>{
    fetch(BaseUrl+type ,{
      method:'post',
      'Content_type':'application/json',
      body:JSON.stringify(userData),
      headers
    })
    .then((response)=>{
      response.json()
    })
    .then((responseJson)=>{
      resolve(responseJson)
    })
    .catch((error)=>{
      reject(error)
    })
  })
}

login.js Reactjs code

import React, { Component } from 'react';
import { Link,Redirect } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import {PostData} from './PostData';
class Login extends Component {
  constructor(props){
    super(props);
    this.state = {
      user_email:'',
      Password:'',
      redirect :false
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
}

handleSubmit(event){
  event.preventDefault()
  if(this.state.user_email && this.state.Password){
      PostData('login',this.state)
  }
}

handleChange = (event) =>{
  const name  = event.target.name
  const value = event.target.value
  this.setState({ [name]:value })
}
  render() {
    if (this.state.redirect){
      return <Redirect to='/dashboard'/>
    }
    return (
      <div className="app flex-row align-items-center">
        <Container>
          <Row className="justify-content-center">
            <Col md="8">
              <CardGroup>
                <Card className="p-4">
                  <CardBody>
                    <Form  onSubmit={this.handleSubmit} >
                      <h1>Login</h1>
                      <p className="text-muted">Sign In to your account</p>
                      <InputGroup className="mb-3">
                        <InputGroupAddon addonType="prepend">
                          <InputGroupText>
                            <i className="icon-user"></i>
                          </InputGroupText>
                        </InputGroupAddon>
                        <Input type="email" placeholder="Email" name="user_email" value={this.state.user_email} onChange={this.handleChange} autoComplete="username" required />
                      </InputGroup>
                      <InputGroup className="mb-4">
                        <InputGroupAddon addonType="prepend">
                          <InputGroupText>
                            <i className="icon-lock"></i>
                          </InputGroupText>
                        </InputGroupAddon>
                        <Input type="password" placeholder="Password" name="Password" value={this.state.Password} onChange={this.handleChange} autoComplete="current-password" required />
                      </InputGroup>
                      <Row>
                        <Col xs="6">

                          <input  type="submit" color="primary" value="Login" className="px-4" />

                        </Col>
                        <Col xs="6" className="text-right">
                          <Button  color="link"  className="px-0">Forgot password?</Button>
                        </Col>
                      </Row>
                    </Form>
                  </CardBody>
                </Card>
                <Card className="text-white bg-primary py-5 d-md-down-none" style={{ width: '44%' }}>
                  <CardBody className="text-center">
                    <div>
                      <h2>Sign up</h2>
                      <p>welcome here i do many works for you just sign in then start working.</p>
                      <Link to="/register">
                        <Button color="primary" className="mt-3" active tabIndex={-1}>Register Now!</Button>
                      </Link>
                    </div>


        <p>Error:{this.state.error}</p>
                      </CardBody>
                    </Card>
                  </CardGroup>
                </Col>
              </Row>
            </Container>
          </div>
        );
      }
    }

    export default Login;

3 Answers

0
Gaël S On

You should update this part :

fetch("http://localhost/API/UserController/Userlogin",options)
    .then(this.setState({
      user_email : '',
      Password   : '',
      redirect   : true
    }))

Instead of redirecting to the dashboard (by setting redirect at true ) regardless the response from the backend (good or bad), you should create a condition depending on the status code received.

For instance, in case of a response with a 200 status, you indeed redirect to Dashboard but if you get another status, you can show an error message to the user for instance

0
laktherock On

First, You need to check the response of the API. Based on that you can navigate the user to the dashboard.

For Example:

If login credentials are correct. Then I will return the response below

{
 error: false,
 message: "User has logged in successfully"
 data: {
  .....
 }
}

If login credentials are Wrong.

{
 error: true,
 data: {}
 message: "Please check the Username and Password"
}

You need to modify this part

fetch("http://localhost/API/UserController/Userlogin",options)
.then(res => res.json())
.then(response => {
  if (!response.error) {
    this.setState({
      user_email : '',
      Password   : '',
      redirect   : true
    });
  } else {
    this.setState({
        user_email : '',
        Password   : '',
        redirect   : false
      });
  }
})
.catch(err=>console.log(err))
0
Rahul Rana On
fetch("http://localhost/API/UserController/Userlogin",options)
.then(this.setState({
  user_email : '',
  Password   : '',
  redirect   : true
}))
.then(res =>console.log(res.json()))
.catch(err=>console.log(err))

The problem is that irrespective of backend response you are setting the redirect true. So when it rerenders it will redirect to another page. This code redirecting you

const state = this.state.redirect;

if(state){
  return <Redirect to="dashboard" />
}