I am trying to create a login authentication for my form. I have created the user with a hashed password using bcrypt, I am trying to log in but it keeps returning failed. The email and password are both correct I have double checked. This is my server-side code:
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const User = require("./models/user.js");
require("dotenv").config();
const app = express();
const bcryptSalt= bcrypt.genSaltSync(10);
app.use(express.json());
app.use(cors({
credentials: true,
origin: "http://localhost:5173",
}));
mongoose.connect(process.env.MONGO_URL);
app.get("/test",(req,res) => {
res.json("test ok");
});
app.post("/register",async (req,res) => {
const{name, email, password} = req.body;
try{
const newUser = await User.create ({
name,
email,
password: bcrypt.hashSync(password, bcryptSalt)
});
res.json(newUser);
} catch (e){
res.status(422).json(e);
}
});
app.post("/login", async (req,res) => {
const {email, password} = req.body;
const newUser = await User.findOne({email});
if (newUser){
const passOk= bcrypt.compareSync(password, newUser.password);
if (passOk) {
res.json("pass ok");
} else{
res.status(422).json("pass not ok");
}
} else {
res.json("not found");
}
});
app.listen(4000);
I have checked the server logs for any errors that might be preventing the login process from working correctly. There were no error messages instead I keep getting the “login failed” alert whenever I try to log in. Here is my client-side code:
import { Link } from "react-router-dom";
import {useState} from "react"
;
function LoginPage () {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
async function handleOnSubmit (e) {
e.preventDefault();
try{
await axios.post("/login", {email, password});
alert("login successful");
} catch (e) {
alert("login failed");
}
}
return (
<div className="mt-4 grow flex items-center justify-around">
<div className="mb-64">
<h1 className="text-4xl text-center mb-4">Login</h1>
<form className="max-w-md mx-auto" onSubmit={handleOnSubmit}>
<input type="email"
placeholder="[email protected]"
value={email}
onChange={ev => setEmail(ev.target.value)} />
<input type="password"
placeholder="password"
value={password}
onChange={ev => setPassword(ev.target.value)} />
<button className="primary">Login</button>
<div className="text-center py-2 text-gray-500">
Don't have an account yet? <Link className="underline text-black" to={"/register"}>Register now</Link>
</div>
</form>
</div>
</div>
)
}
export default LoginPage;