繁体   English   中英

使用 mongodb 在 nodejs 中验证用户名和密码

[英]Authenticating Username and Password in nodejs with mongodb

我正在创建一个登录页面,每次登录时都需要验证用户的用户名和密码。我的数据库是 mongodb,我在 nodejs 中使用 expressjs。 注册功能运行良好,我可以注册用户,但登录功能不起作用。 请帮助我了解 MongoDB 以验证用户身份并存储他们的 cookies。

这是我的服务器代码..

//------------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`));

使用此代码登录 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"); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM