Home > Enterprise >  Login Form displays invalid credentials until the button is pressed twice
Login Form displays invalid credentials until the button is pressed twice

Time:11-16

I have a react component "Signin.js", I have some login input fields in it, I am trying to create a login system using nodejs, expressjs and MySQL. To do this, I have created a post request, that sends the data of my input fields to nodejs backend where the data is passed into the database to check if the login credentials are correct or not. If the credentials are found in the database, the global variable auth in my backend "index.js" becomes true, I am sending that variable from nodejs to reactjs using a get request. if auth is true, I should get redirected to the next page other wise it says, login failed. The problem is that when I enter the correct credentials, in the first 2 clicks, I get login failed, but in the 3rd click, it redirects me to the next page.

Here is my react component Signin.js

import React, {useState , useEffect} from 'react';
import Navbar from './Navbar';
import './signin.css';
import {Link} from 'react-router-dom';
import axios, { Axios } from 'axios';

 function Signin()
 {
    const [userId, setUserId] = useState("");
    const [password, setPassword] = useState("");
    const [accessCode, setAccessCode] = useState("");
    const [auth , setAuth] = useState(false);
    
    const receiveauthentication = () => {
        console.log("Calling authentication function");
        axios.get("http://localhost:3001/api/get/signin2").then((response) => {

        setAuth(response.data);

            console.log(response.data);
            if(auth === true)
            {
                console.log(response.data);
                setAuth(false);
                document.location.href = "http://localhost:3000/Dashhome";
            }

            else{
                alert('Incorrect Login/Password');
            }
        })
    };
    const signInInfoSent = () => {
        axios.post("http://localhost:3001/api/get/signin", {userId:userId, password:password}).then(() => {
            console.log("Successfully Login");
            
        }).then(receiveauthentication());
        
    }


    return(
        <>
        <Navbar/>

        <div id="signUp">
            <div id="form">
                <label htmlFor = "userId">User ID</label>
                <input type="textbox" id="userId" placeholder = "Username" onChange={(e) =>{
                    setUserId(e.target.value);
                }}/>

                <label htmlFor = "password">Password</label>
                <input type="password" id="password" placeholder = "Password" onChange={(e) =>{
                    setPassword(e.target.value);
                }}/>

                <label htmlFor = "otp">Access Code</label>
                <input type="textbox" id="otp" placeholder = "OTP" onChange={(e) =>{
                    setAccessCode(e.target.value);
                }}/>


                 <button onClick={()=>{ signInInfoSent() }}>Sign in</button> 

            </div>
        </div>
        </>
    );
 }

 export default Signin;

Here is my nodejs backend index.js

const express = require('express')
const app = express()
const mySql = require('mysql');
const cors = require('cors')
const bodyParser = require('body-parser')

const db = mySql.createPool({
    host:"127.0.0.1",
    user:"root",
    password:"password",
    database:"kotekdatabase"
})

app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())
app.use(cors())

let auth;
var userIdG;

var trade_data = {};
app.post("/api/get/signin", (req,res)=>{
    
    const userid = req.body.userId;
    userIdG = userid;
    const password = req.body.password;
    const sqlSelect =
    `SELECT * FROM signup WHERE userid = ? AND password = ?`;
     db.query(sqlSelect,[userid , password], (err, result)=> {

        //console.log(err);
        if(result != null)
        {
            //res.send(result);
            console.log("Successfully Login");
            auth = true;
        }
        else
        {
            console.log("UnSuccessfully Login");
            auth = false;
        }
         
    })
})






app.get("/api/get/retrieveStrategies" , (req , res)=>{
    const q = 'SELECT * FROM strategy WHERE userid = ?';
    db.query(q , [userIdG] , (err , result)=>{
        if(err)
        {
            console.log(err);
        }
        else{
            console.log(result[0]);
            res.send(result);
        }
    });
})

app.get("/api/get/signin2", (req,res) =>{
                console.log(auth);
                res.send(auth);
                auth = false;
            })



var strategyG;

app.post("/api/get/strategy", (req,res)=>{

    console.log("Strategy Name received\n");
    const str = req.body.strategy;
    strategyG = str;
    console.log(strategyG);
})



 var signupAuth = 0;

app.post("/api/insert", (req,res)=>{

    const userid = req.body.userId;
    const password = req.body.password;
    const consumerKey = req.body.consumerKey;
    const consumerSecret = req.body.consumerSecret;
    const accessToken = req.body.accessToken;

    const sqlInsert = "INSERT INTO  signup (userid, password, consumerKey, consumerSecret, accessToken) VALUES (?,?,?,?,?);"
    db.query(sqlInsert, [userid, password, consumerKey, consumerSecret, accessToken], (err, result)=> {
        if(err){
            console.log(err);
            signupAuth = 0;
            console.log(signupAuth);
        }
        else { 
            signupAuth = 1;
            console.log(signupAuth);
        }
    }) 
})







app.post("/api/tradeinfo", (req,res)=>{
    console.log("Inserting fo user Id,Strategy:", userIdG,strategyG);
    const userid = userIdG;
    const Sno = strategyG;
    const indexName = req.body.indexName;
    const Sprice = req.body.Sprice;
    const SLP = req.body.SLP;
    const PE = req.body.PE;
    const Exitt = req.body.Exit; 
    const TType = req.body.TType;
    const SL = req.body.SL;
    const CE = req.body.CE;
    const Entry = req.body.Entry;

    const sqlInsert = "INSERT INTO  strategy (userid, Sname, indexName, strikePrice, SLP, PE, Exitt, tradeType, SL, CE, Entry) VALUES (?,?,?,?,?,?,?,?,?,?,?);"
    db.query(sqlInsert, [userid, Sno, indexName, Sprice, SLP, PE, Exitt, TType, SL, CE, Entry], (err, result)=> {
        //console.log(err);
        console.log(err);
        
    }) 
})



app.post("/api/get/strategysent", (req,res)=>{
    
    const userid = userIdG;
    const Sno = strategyG;
    const indexName = req.body.indexName;
    const Sprice = req.body.Sprice;
    const SLP = req.body.SLP;
    const PE = req.body.PE;
    const Exitt = req.body.Exit; 
    const TType = req.body.TType;
    const SL = req.body.SL;
    const CE = req.body.CE;
    const Entry = req.body.Entry;
    const sqlSelect =
    `SELECT userid FROM signup WHERE userid = ${userid} AND password = ${password} AND consumerKey = ${consumerKey}`;
     db.query(sqlSelect, (err, result)=> {
        //console.log(err);
        if(result != null)
        {
            //res.send(result);
            console.log("Successfully Login");
            auth = true;
        }
        else
        {
            console.log("UnSuccessfully Login");
            auth = false;
        }
         
    })
})


app.post("/api/get/trade_data" , (req,res)=>{
    res.send(req.body);
    console.log(req.body);
    trade_data = req.body;
})

app.get("/api/send/trade_data" , (req , res)=>{
    res.send(trade_data);
} )




app.listen(3001, () => {
    console.log("running on port 3001");
})

CodePudding user response:

You have a floating promise, receiveauthentication is called too soon, you need to call it within the first .then handler.

Try this:

axios.post("http://localhost:3001/api/get/signin", {userId:userId, password:password}).then(() => {
    console.log("Successfully Login");
    receiveauthentication();

edit

you can merge the signin to remove extra axios request, i.e. return auth on the first request, and wrap state checking within useEffect, as it's a side effect:

server:

app.post("/api/get/signin", (req,res)=>{
    
    const userid = req.body.userId;
    userIdG = userid;
    const password = req.body.password;
    const sqlSelect =
    `SELECT * FROM signup WHERE userid = ? AND password = ?`;
     db.query(sqlSelect,[userid , password], (err, result)=> {

        //console.log(err);
        if(result != null)
        {
            //res.send(result);
            console.log("Successfully Login");
            auth = true;
        }
        else
        {
            console.log("UnSuccessfully Login");
            auth = false;
        }

        res.send(auth);
         
    })
})
client
// set 0 to skip on first render   
 const [auth, setAuth] = useState(0);


    const signInInfoSent = () => {
        axios.post("http://localhost:3001/api/get/signin", {
            userId: userId,
            password: password
        }).then((response) => {
            console.log("Successfully Login");
            setAuth(response.data);

        }).catch(err => console.error(err));

    }

    useEffect(() => {
        console.log('check auth', auth);
        if (auth === true) {

            document.location.href = "http://localhost:3000/Dashhome";
        } else if (auth === false) {
            alert('Incorrect Login/Password');
        }


    }, [auth]);
  • Related