0

I am creating a login page and need to authenticate user's username and password whenever he logs in. My Database is mongodb and i am using expressjs in nodejs. Signup functionality is working well and i am able to sign up users but Log In functionality is not working. Kindly help me with knowledge of MongoDB to authenticate users and store their cookies.

Here's my server code..

//------------modules used-------------//
const express = require("express");
const path = require("path");
const helmet = require("helmet");
const cookieparser = require("cookie-parser");
const mongoose = require("mongoose");
//------------modules used-------------//

const app = express();
app.use(helmet());
// allow the app to use cookieparser
app.use(cookieparser());
// allow the express server to process POST request rendered by the ejs files 
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//-------------------mongodb-----------------//
mongoose.connect("mongodb://localhost:27017/loginDB", { useNewUrlParser: true });
const userSchema = new mongoose.Schema({
    email: String,
    pass: String,
})
const User = new mongoose.model("User", userSchema);
//-------------------mongodb-----------------//

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

app.get("/", (req, res) => {
    // check if user is logged in, by checking cookie
    let username = req.cookies.username;
    if(username){
        return res.render("mainpage", {
            username,
        });
    }else{
        res.redirect("/login");
    }

});
app.get("/mainpage", (req, res) => {
    // check if user is logged in, by checking cookie
    let username = req.cookies.username;
    if(username){
        return res.render("mainpage", {
            username,
        });
    }else{
        res.redirect("/login");
    }

});
app.get("/register", (req, res) => {

    return res.render("signup");

});

app.get("/login", (req, res) => {
    // check if there is a msg query
    let bad_auth = req.query.msg ? true : false;

    // if there exists, send the error.
    if (bad_auth) {
        return res.render("login", {
            error: "Invalid username or password",
        });
    } else {
        // else just render the login
        return res.render("login");
    }
});

app.post("/login", (req, res) => {
    // get the data
    let { username, password } = req.body;

    User.find({email: username},(err)=>{
        if(err){
            res.redirect("/");
        }else{
            res.cookie("username", username, {
                maxAge: 30 * 24 * 60 * 60 * 1000,
                secure: true,
                httpOnly: true,
                sameSite: 'lax'
            });
            res.redirect("/mainpage");
        }
    })

    // fake test data
    // let userdetails = {
    //     username: "Bob",
    //     password: "123456",
    // };

    // // basic check
    // if (
    //     username === userdetails["username"] &&
    //     password === userdetails["password"]
    // ) {
    //     // saving the data to the cookies
    //     res.cookie("username", username, {
    //         maxAge: 30 * 24 * 60 * 60 * 1000,
    //         secure: true,
    //         httpOnly: true,
    //         sameSite: 'lax'
    //     });
    //     // redirect

    //     return res.redirect("/");

    // } else {
    //     // redirect with a fail msg
    //     return res.redirect("/login?msg=fail");
    // }
});

app.post("/register",(req,res)=>{
    let { given_username, given_password } = req.body;

    const newUser = new User({
        email: given_username,
        pass: given_password,
    });

    newUser.save((err)=>{
        if(err){
            console.log(err);
        }else{
            console.log('saved');
        }
    })

    res.cookie("username", given_username, {
        maxAge: 30 * 24 * 60 * 60 * 1000,
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    });
    
    res.redirect("/")
})

app.get("/logout", (req, res) => {
    // clear the cookie
    res.clearCookie("username");
    // redirect to login
    return res.redirect("/login");
});



app.listen('3000', () => console.log(`server started`));
14
  • Saving a plain password in DB is an awful idea. You need to save the hash of this password only instead of the password itself. And then on login route you should compare the hash previously saved in DB with the one calculated from the passed password. Commented Dec 30, 2022 at 17:44
  • I can do that, please tell me how to compare the passwords in login route Commented Dec 31, 2022 at 14:01
  • You should calculate a hash of a password the same way you do when you save the hash on sign-up Commented Dec 31, 2022 at 22:10
  • Hi Anatoly, You are right but what is the code to do so.. Currently in my code app.post("/login", (req, res) => { let { username, password } = req.body; User.find({email: username},(err)=>{ if(err){ res.redirect("/login"); }else{ //console.log(email); res.cookie("username", username, { maxAge: 30 * 24 * 60 * 60 * 1000, secure: true, httpOnly: true, sameSite: 'lax' }); res.redirect("/mainpage"); } }) Commented Jan 2, 2023 at 16:49
  • ..even if the email does not exists it never goes to err, should i use different method then the user.find, or should i rectify my code somehow Commented Jan 2, 2023 at 16:51

1 Answer 1

1

Use this code for login API

const bcrypt = require("bcryptjs")

app.post("/login", async (req, res) => {
  let { username, password } = req.body;
  const user = await User.findOne({ email: username }).lean()
  if (!user) {
    res.status(404).send({message: "No  User Found"})
  } else {

    var validatePassword = await bcrypt.compare(password, user.password)

    if (!validatePassword) {
      res.status(400).send({message: "Invalid Password"})
    } else {
      res.cookie("username", username, {
        maxAge: 30 * 24 * 60 * 60 * 1000,
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    });
      res.redirect("/mainpage");
  
    }
  }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.