725 viewsMern Amazona

When signing in with the user created and the password given it shows me this message: “Invalid email or password”.

The console shows  “POST http://localhost:3000/api/users/signin 401 (Unauthorized)”.

userRoutes.js =>

import express from “express”;
import bcrypt from “bcryptjs”;
import expressAsyncHandler from “express-async-handler”;
import User from “../models/userModel.js”;
import { generateToken } from “../utils.js”;
const userRouter = express.Router();
userRouter.post(
  “/signin”,
  expressAsyncHandler(async (req, res) => {
    const user = await User.findOne({ email: req.body.email });
    if (user) {
      if (bcrypt.compareSync(req.body.password, user.password)) {
        res.send({
          _id: user._id,
          name: user.name,
          email: user.email,
          isAdmin: user.isAdmin,
          token: generateToken(user),
        });
        return;
      }
    }
    res.status(401).send({ message: “Invalid email or password” });
  })
);
export default userRouter;

userModel.js =>

import mongoose from “mongoose”;
const userSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    isAdmin: { type: Boolean, default: false, required: true },
  },
  {
    timestamps: true,
  }
);
const User = mongoose.model(“User”, userSchema);
export default User;

data.js =>

import bcrypt from “bcryptjs”;
const data = {
  users: [
    {
      name: “Eugeni”,
      email: “[email protected]”,
      password: bcrypt.hashSync(“123456”),
      isAdmin: true,
    },
    {
      name: “John”,
      email: “[email protected]”,
      password: bcrypt.hashSync(“123456”),
      isAdmin: false,
    },
  ],
  products: [
    {
      // _id: “1”,
      name: “Nike Slim shirt”,
      slug: “nike-slim-shirt”,
      category: “Shirts”,
      image: “/images/p1.jpg”, // 679px × 829px
      price: 120,
      countInStock: 10,
      brand: “Nike”,
      rating: 4.5,
      numReviews: 10,
      description: “high quality shirt”,
    },
    {
      // _id: “2”,
      name: “Adidas Fit Shirt”,
      slug: “adidas-fit-shirt”,
      category: “Shirts”,
      image: “/images/p2.jpg”,
      price: 250,
      countInStock: 0,
      brand: “Adidas”,
      rating: 4.0,
      numReviews: 10,
      description: “high quality product”,
    },
    {
      // _id: “3”,
      name: “Nike Slim Pant”,
      slug: “nike-slim-pant”,
      category: “Pants”,
      image: “/images/p3.jpg”,
      price: 25,
      countInStock: 15,
      brand: “Nike”,
      rating: 4.5,
      numReviews: 14,
      description: “high quality product”,
    },
    {
      // _id: “4”,
      name: “Adidas Fit Pant”,
      slug: “adidas-fit-pant”,
      category: “Pants”,
      image: “/images/p4.jpg”,
      price: 65,
      countInStock: 5,
      brand: “Puma”,
      rating: 4.5,
      numReviews: 10,
      description: “high quality product”,
    },
  ],
};
export default data;

server.js =>

import express from “express”;
import data from “./data.js”;
import mongoose from “mongoose”;
import dotenv from “dotenv”;
import seedRouter from “./routes/seedRoutes.js”;
import productRouter from “./routes/productRoutes.js”;
import userRouter from “./routes/userRoutes.js”;
dotenv.config();
mongoose
  .connect(process.env.MONGODB_URI)
  .then(() => {
    console.log(“connected to db”);
  })
  .catch((err) => {
    console.log(err.message);
  });
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(“/api/seed”, seedRouter);
app.use(“/api/products”, productRouter);
app.use(“/api/users”, userRouter);
app.use((err, req, res, next) => {
  res.status(500).send({ message: err.message });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`serve at http://localhost:${port}`);
});

signInScreen.js =>

import Axios from “axios”;
import { Link, useLocation, useNavigate } from “react-router-dom”;
import Container from “react-bootstrap/Container”;
import Form from “react-bootstrap/Form”;
import Button from “react-bootstrap/Button”;
import { Helmet } from “react-helmet-async”;
import { useContext, useEffect, useState } from “react”;
import { Store } from “../Store”;
import { toast } from “react-toastify”;
import { getError } from “../utils”;
export default function SignInScreen() {
  const navigate = useNavigate();
  const { search } = useLocation();
  const redirectInUrl = new URLSearchParams(search).get(“redirect”);
  const redirect = redirectInUrl ? redirectInUrl : “/”;
  const [email, setEmail] = useState(“”);
  const [password, setPassword] = useState(“”);
  const { state, dispatch: ctxDispatch } = useContext(Store);
  const { userInfo } = state;
  const submitHandler = async (e) => {
    e.preventDefault();
    try {
      const { data } = await Axios.post(“/api/users/signin”, {
        email,
        password,
      });
      ctxDispatch({ type: “USER_SIGNIN”, payload: data });
      localStorage.setItem(“userInfo”, JSON.stringify(data));
      navigate(redirect || “/”);
    } catch (err) {
      toast.error(getError(err));
    }
  };
  useEffect(() => {
    if (userInfo) {
      navigate(redirect);
    }
  }, [navigate, redirect, userInfo]);
  return (
    <Container className=”small-container”>
      <Helmet>
        <title>Sign In</title>
      </Helmet>
      <h1 className=”my-3″>Sign In</h1>
      <Form onSubmit={submitHandler}>
        <Form.Group className=”mb-3″ controlId=”email”>
          <Form.Label>Email</Form.Label>
          <Form.Control
            type=”email”
            required
            onChange={(e) => setEmail(e.target.value)}
          />
        </Form.Group>
        <Form.Group className=”mb-3″ controlId=”password”>
          <Form.Label>Password</Form.Label>
          <Form.Control
            type=”password”
            required
            onChange={(e) => setPassword(e.target.value)}
          />
        </Form.Group>
        <div className=”mb-3″>
          <Button type=”submit”>Sign In</Button>
        </div>
        <div className=”mb-3″>
          New customer?{” “}
          <Link to={`/signup?redirect=${redirect}`}>Create your account</Link>
        </div>
      </Form>
    </Container>
  );
}

Bassir Answered question November 24, 2022

hello there,

first of all, for long code put your code on GitHub and put the link here.

it says the user and password are incorrect.

use console.log before if condition to see what you get for expressions inside if condition:

const user = await User.findOne({ email: req.body.email });
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
res.send({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user),
});
return;
}

Bassir Answered question November 24, 2022