Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

61
Vistas
How should I complete my MERN login system

I am trying to create a login system with MERN. My login route:

const express = require("express");
const bcrypt = require("bcrypt");
const { User } = require("../models/user");
const Joi = require("joi");
const router = express.Router();

//login route
router.post("/", async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  // login
  const user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send("Invalid Email or Psssword");

  // comparing password
  const validPassword = await bcrypt.compare(req.body.password, user.password);
  if (!validPassword) return res.status(400).send("Invalid Email or password");

  // generating the auth token
  const token = user.generateAuthToken()
  res.send(token)
});

// input validation
const validate = (req) => {
  const schema = Joi.object({
    email: Joi.string()
      .min(5)
      .max(100)
      .required()
      .email({ minDomainSegments: 2, tlds: { allow: ["com", "net", "org"] } }),
    password: Joi.string()
      .min(6)
      .max(100)
      .required()
  });
  return schema.validate(req);
};

module.exports = router;

I am using formik at the front end as my form handler

    const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    validationSchema: Yup.object({
      email: Yup.string()
        .email()
        .min(5)
        .max(100)
        .required(),
      password: Yup.string()
        .min(6)
        .max(100)
        .required(),
    }),
    onSubmit: (values, {resetForm}) => {
      axios.post("http://localhost:8080/api/login", values)
        .then((values) => {
          console.log(values)
          // localStorage.setItem(values)
        })
        .catch (er => console.log(er))
    },
  });

When I do the login using postman everything is successful. I need to implement this to my front end in such a way that if user enters wrong credentials is the 400 errors shows as an alert not at the console and redirects users to the login page and if its a 200 user is redirected to the dashboard.

The whole GitHub code is: https://github.com/Joseph-muvevi/rhino-jon

This is for a school project.

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos