I am Unable to connect to Backend While I am giving valid Credentials from front End I am Facing this error : POST http://127.0.0.1:5000/api/login 400 (Bad Request) I am Able to Generate the Token from Backend End , But not able to login from Fornt-end and getting Invalid credentials , although I am giving same like this : { "email" : "[email protected]", "password" :14280 }
here is my Backend Code Nodejs Code :
router.post('/login', async(req,res) =>{
try {
const {email,password} =req.body;
let exist = await Auth.findOne({email})
if(!exist){
return res.status(400).json("User Not Found");
}
if(exist.password !== password){
return res.status(400).json('Invalid Credentails');
}
let payload = {
user : {
id : exist.id
}
}
jwt.sign(payload,'jwtSecret',{expiresIn : 3600000}, (err,token)=>
if (err) throw err;
return res.json({token})
})
} catch (error) {
res.status(500).json({error : error.msg})
}
})
Here is the MongoDB Schema
const mongoose = require('mongoose');
const AuthSchema = new mongoose.Schema({
username :{
type : String,
required : true
},
email :{
type : String,
required : true,
unique : true
},
password :{
type : Number,
required : true
},
confirmpassword :{
type : Number,
required : true
},
created :{
type : Date,
default : Date.now()
}
});
let Auth = mongoose.model('auth' , AuthSchema);
module.exports = Auth;
here is the Forntend Login Page
import React,{useState,useContext} from 'react'
import axios from "axios";
import { store } from './../../App';
import { Navigate } from 'react-router-dom';
const Login = () => {
const [data, setData] = useState({
email : '',
password : '',
})
const handleChange = (e) =>{
setData({...data,[e.target.name] : e.target.value});
}
const submitForm =(e) =>{
e.preventDefault();
//console.log(data);
axios.post('http://127.0.0.1:5000/api/login',data).then(res => console.log(res.data));
}
return (
<div>
<div className="container mt-3">
<div className="row">
<div className="col-md-4">
<div className="card">
<div className="card-header bg-info text-white">
<h4>Login</h4>
<hr className="bg-white border-3 border-top border-white"></hr>
<form onSubmit={submitForm}>
<div className="form-group mt-2">
<label htmlFor="exampleInputEmail1" className="form-label fw-bold">Email</label>
<input name="email" className="form-control" placeholder='Email' onChange={handleChange} />
</div>
<div className="form-group mt-2">
<label htmlFor="exampleInputEmail1" className="form-label fw-bold">Passowrd</label>
<input type="text" className="form-control" placeholder='Passowrd' name="Passowrd" onChange={handleChange} />
</div>
<button type="submit" className="btn btn-dark fw-bold mt-4">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Login
Here is the Code for Registration here is the code for Registration
router.post('/register', async(req,res) =>{
try {
const {username,email,password,confirmpassword} = req.body;
//First we need to check wheather is the Email Id is exists or not?
let exist = await Auth.findOne({email});
if(exist){
return res.status(400).json({msg : 'User is alreday exists'});
}
if(password !== confirmpassword){
return res.status(400).json({msg : 'Passwords are not matching'});
}
let newUser = new Auth({
username,
email,
password,
confirmpassword
})
await newUser.save();
res.status(200).send({msg : 'Register Successfully'})
} catch (error) {
res.status(500).json({error : error.msg})
}
})
CodePudding user response:
The error may be caused by the different types of password during comparison since you are storing them as Number
.
Try to cast both of them to a string with .toString()
:
if(exist.password.toString() !== password.toString()) {
return res.status(400).json('Invalid Credentails');
}
Also, I see that you are saving passwords in plain text, which is a pretty bad security issue. Check out some libraries that allow you to hash the stored passwords, like bcrypt.
Your code for registration will become:
// Generate encrypted password
const salt = await bcrypt.genSalt(12);
const encryptedPassword = await bcrypt.hash(password, salt);
let newUser = new Auth({
username,
email,
password: encryptedPassword,
confirmpassword: encryptedPassword
});
And you will check your password during login with:
const isValidPsw = await bcrypt.compare(password, exist.password);
if (!isValidPsw) {
return res.status(400).json('Invalid Credentails');
}