Search code examples
node.jsreactjsnode-oracledb

The authentication is working properly but whenever I typed the wrong email address, my server is getting crashed


The server is keep getting crashed whenever i typed the wrong email address, i understood the problem, but can anyone tell me how to solve this. Problem:Here the authentication is done for password only, if the password is wrong it is giving me the right error which is "Incorrect email or address", but not give this one when i try with wrong email address. so i need the authentication for the email address also from my understanding this much i summarized.

Logins.js(API)

 var oracledb = require('oracledb');
var bcrypt = require('bcrypt');
var jwt = require('jsonwebtoken');
var config = require(__dirname + '../../config.js');
import { Redirect } from 'react-router'
// var redirect = require("express-redirect");
// var express = require("express");
//var passport = require('passport');
//var LocalStrategy = require('passport-local').Strategy;
//var history = require('history');
//import post from './users';
//var cors = require('cors');
// var history = require('browser-history');
// var app = express();
// redirect(app);
// const targetBaseUrl = '/Signup';

function post(req, res, next) {
    console.log('oye')
    oracledb.getConnection(
        config.database,
        function(err, connection){
            if (err) {
                console.log('haha')
                return next(err);
                // console.log(err);
            }
            console.log('fuha')

            connection.execute(
                'select id as "id", ' +
                '   email as "email", ' +
                '   password as "password", ' +
                '   role as "role" ' +
                'from jsao_users ' +
                'where email = :email',
                {
                    email: req.body.email.toLowerCase()
                },
                {
                    outFormat: oracledb.OBJECT
                },
                function(err, results){
                    var user;
                    console.log('huo')
                    console.log(err)
                    //console.log(results)
                        console.log(results.rows[0])
``````````````````````````````````````````````````````````````````````
                    if (results.rows[0] === undefined) {
                        console.log('hiiiiiii')
                        return <Redirect to='/Signup'  />
                        // app.redirect(targetBaseUrl);
                        // history.push("/Main");
                    }
``````````````````````````````````````````````````````````````````
                    //     else {connection.release(function(err) {
                    //         console.log('hy')
                    //         if (err) {
                    //             console.log('joker')
                    //             console.error(err.message);
                    //         }
                    //     });

                    //     return next(err);
                    //     // console.log(err);
                    // }

                    user = results.rows[0];
                    //debugger;

                    console.log(user)
                    bcrypt.compare(req.body.password,user.password, function(err, pwMatch) {
                        var payload;

                        if (err) {
                            console.log('wrong');
                            return next(err);
                        }

                        /*if (result == true) {
                            //res.redirect('http://localhost:3000/Main');
                            //res.end();
                        } 

                        else {
                         res.send('Incorrect password');
                         //res.redirect('/Signin');
                         //res.end();
                        }

                        /*if(req.body.password != user.password){
                            res.json({success: false, message: 'passwords do not match'});
                        }*/
                        /*if(req.body.password == user.password) {
                            this.props.history.push("/Main");
                        }*/
                        if(pwMatch) {
                             //this.props.history.push("/Main");
                             console.log("password matched");
                        }
                        else {
                            res.status(401).send({message: 'Invalid email or password.'});
                            return;
                        }

                        payload = {
                            sub: user.email,
                            role: user.role
                        };

                        res.status(200).json({
                            user: user,
                            token: jwt.sign(payload, config.jwtSecretKey, {expiresIn: "60m" }),

                        });
                    });
                    //res.status(404).end();
                    connection.release(function(err) {
                        if (err) {
                            console.error(err.message);
                        }
                    }); 

                });
        }
    );
}

module.exports.post = post;



Signin.js (Front-end)

import React, { Component } from "react";
import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import axios from 'axios';
import "./Signin.css";

class Signin extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: ""
    };
  }

  validateForm() {
    return this.state.email.length > 0 && this.state.password.length > 0;
  }

  handleChange = event => {
    this.setState({
      [event.target.id]: event.target.value
    });
  }
```````````````````````````````````````````````````````````````
  handleSubmit = event => {
    event.preventDefault();
    const user = {
        email: this.state.email,
        password : this.state.password
      };
  // API CALL
      axios.post(`http://localhost:4000/api/logins`, user)
        .then(res => {
          console.log(res);
          console.log(res.data);
          //console.log("successful");
        })
        //this.props.history.push("/Main");
  }
`````````````````````````````````````````````````````````````````````
  render() {
    return (
      <div className="Login">
        <form onSubmit={this.handleSubmit}>
          <FormGroup controlId="email" bsSize="large">
            <ControlLabel>Email</ControlLabel>
            <FormControl
              autoFocus
              type="email"
              value={this.state.email}
              onChange={this.handleChange}
            />
          </FormGroup>
          <FormGroup controlId="password" bsSize="large">
            <ControlLabel>Password</ControlLabel>
            <FormControl
              value={this.state.password}
              onChange={this.handleChange}
              type="password"
            />
          </FormGroup>
          <Button
            block
            bsSize="large"
            disabled={!this.validateForm()}
            type="submit"
          >
            Login
          </Button>
        </form>
      </div>
    );
  }
}

export default Signin;


The expected result for the wrong email address is "Invalid email or password"
But instead getting this error:
C:\Users\anura\Desktop\reactApp\eclaims\src\Backend\routes\logins.js:49
                    bcrypt.compare(req.body.password,user.password, function(err, pwMatch) {
                                                          ^

TypeError: Cannot read property 'password' of undefined
    at C:\Users\anura\Desktop\reactApp\eclaims\src\Backend\routes\logins.js:49:59
    at fetchRowsCb (C:\Users\anura\Desktop\reactApp\eclaims\src\Backend\node_modules\oracledb\lib\connection.js:109:7)
[nodemon] app crashed - waiting for file changes before starting...

Solution

  • The app crashed because you didn't throw exception and return immediately when getting user not found err, because the email is invalid, user variable is null, you cannot read property password of null or undefined

    if (err) {
       connection.release(function(err) {
          if (err) {
             console.error(err.message);
          }
       });
       // MUST RETURN HERE !!!
       //return next(err);
       console.log(err);
    }
    
    user = results.rows[0];
    // user IS NULL HERE, CANNOT READ PROPERTY OF NULL OR UNDERFINED
    
    //debugger;
    bcrypt.compare(req.body.password,user.password, function(err, pwMatch) {