我正在创建一个登录页面,需要验证用户的用户名和密码,无论他何时登录。我的数据库是mongodb,我正在使用nodejs中的expressjs。注册功能运行良好,我可以注册用户,但登录功能不工作。请帮助我了解MongoDB,以验证用户和存储他们的cookie。
这是我的服务器代码。
//------------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`));
1条答案
按热度按时间ddarikpa1#
将此代码用于登录API