Home > database >  nodejs mongoose - how to check items in the database before login
nodejs mongoose - how to check items in the database before login

Time:09-22

In my project, I've different roles (seller/user/admin)and i want to check the role and redirect to specific page if they are seller for example.

I struggle on how i can check the role in Mongo DB before the login. My login page is basic email-password and submit button.

for my signup all is good, it's use the correct model and post it in the DB.

here are some pieces of my code:

(client model)

userSchema.statics.login = async function (email, password, role) {
  const user = await this.findOne({ email });

  if (user) {
    const auth = await bcrypt.compare(password, user.password);

    if (auth) {
      return user;
    }
    throw Error("incorrect password");
  }

  throw Error("incorrect email");
};

const ClientModel = mongoose.model("client", userSchema, "users");

login controller:

module.exports.clientSignIn = async (req, res) => {
  const { email, password } = req.body;
  
  try {
    const user = await LoginModel.login(email, password);
    const token = createToken(user._id);
    res.cookie("jwt", token, { httpOnly: true, maxAge });
    res.redirect('/success');
  } catch (err) {
    console.log(err.message);
  }
};

thanks in advance for your help, if you need more info please feel free to ask

CodePudding user response:

Following @EAzevedo 's advice.

i just change my Controller

module.exports.clientSignIn = async (req, res) => {
  const { email, password } = req.body;

  try {
    const user = await LoginModel.login(email, password);
    const token = createToken(user._id);
    res.cookie("jwt", token, { httpOnly: true, maxAge });
    if (user.role == "client") {
      res.redirect("/success");
    } else if (user.role == "technicien") {
      res.redirect("/success-technicien");
    } else if (user.role == "superuser") {
      res.redirect("/success-admin");
    };
  } catch (err) {
    const errors = signInErrors(err);
    res.status(200).json({ errors });
  }
};

CodePudding user response:

when you get the user , you should have field for the role , then check which role logged in and redirect him to where he needs to be

  • Related