我试图将使用isAuthenticated的isLoggedIn中间件添加到我的小型应用程序,但似乎无法正常工作。
通过删除中间件,登录页面可以正常工作并进行重定向,但是如果我将其添加到管理页面(登录重定向到其中),则console.log(isAuthenticated())
始终为 false 。
添加了中号后,凭证似乎发生了某些事情,无法对其进行检查。
我敢打赌,它很小,但几个小时后我无法弄清楚。
app.js的代码如下:
const express=require("express");
const expressSanitizer=require("express-sanitizer");
const bodyParser=require("body-parser");
const mongoose=require("mongoose");
const methodOverride = require("method-override");
const passport = require("passport");
const LocalStrategy = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const Caruser=require("./models/caruser");
const Carcheck=require("./models/carcheck");
let app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");
app.use(expressSanitizer());
app.use(methodOverride("_method"));
//**********************
//connecting with the Car Check DB
//**********************
mongoose.connect("mongodb://localhost/car_check_app", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to Car Check DB!'))
.catch(error => console.log(error.message));
app.use(require("express-session")({
secret:"secret",
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(Caruser.authenticate()));
passport.serializeUser(Carcheck.serializeUser());
passport.deserializeUser(Carcheck.deserializeUser());
passport.serializeUser(Caruser.serializeUser());
passport.deserializeUser(Caruser.deserializeUser());
//**********************
//Routes
//**********************
app.get("/", function(req, res){
res.send("Hi there!");
});
//LOGIN ROUTE
app.get("/login", function(req, res){
res.render("login");
});
//LOGIN LOGIC
app.post("/login",passport.authenticate("local",{
successRedirect: "/admin",
failureRedirect: "/login"
}), function(req, res){
});
//Admin Page
app.get("/admin",isLoggedIn, (req, res)=>{
Carcheck.find({}).sort({created: -1}).exec( function(err,allentries){
if (err) {
console.log(err);
} else {
res.render("index", {CarchechObj:allentries});
}
});
});
//Drivers Page
app.get("/drivers", (req, res)=>{
Caruser.find({}, function(err,allentries){
if (err) {
console.log(err);
} else {
res.render("drivers", {CaruserObj:allentries});
}
});
});
//Add Driver Page
app.get("/newdriver", function(req, res){
res.render("newdriver");
});
//Create New Driver
app.post("/newdriver", function(req, res){
var newDriver = new Caruser({
username: req.body.username,
firstname: req.body.firstname,
lastname: req.body.lastname,
role: req.body.role
});
Caruser.register(new Caruser(newDriver),req.body.password, function(err, user){
if(err){
console.log(err);
return res.render("newdriver");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/drivers");
});
});
});
//Delete Existing Driver
app.delete("/drivers/:id",function(req, res){
Caruser.findByIdAndRemove(req.params.id, function(err,deletedDriver){
if (err) {
res.redirect("/drivers");
} else {
res.redirect("/drivers/");
}
});
});
//car inspection page
app.get("/car-inspection", function(req, res){
res.render("car-inspection");
});
//car inspection filled
app.get("/car-inspection/:id", function(req, res){
Carcheck.findById(req.params.id).exec(function (err,foundCarInspection){
if(err){
console.log(err);
} else {
res.render("car-inspected-show",{CarchechObj:foundCarInspection});
}
});
});
//car inspection checked by the admin
app.put("/car-inspection/:id", function(req, res){
// find and update the correct car-inspection
Carcheck.findByIdAndUpdate(req.params.id, {checked:"yes"}, function(err, checkedInspection){
if(err){
res.redirect("/car-inspection/"+req.params.id);
} else {
//redirect to the admin page
res.redirect("/admin");
}
});
});
app.post("/car-inspection", (req, res)=>{
var carPlate =req.sanitize( req.body.carPlate)
var carModel =req.sanitize( req.body.carModel)
var carMiles =req.sanitize( req.body.carMiles)
var tyrePressure =req.sanitize( req.body.tyrePressure)
var tyrePressureNotes =req.sanitize( req.body.tyrePressureNotes )
var fluids =req.sanitize( req.body.fluids)
var fluidsNotes =req.sanitize( req.body.fluidsNotes)
var damageVisual =req.sanitize( req.body.damageVisual)
var damageVisualNotes =req.sanitize( req.body.damageVisualNotes)
var cleaned =req.sanitize( req.body.cleaned)
var cleanedNotes =req.sanitize( req.body.cleanedNotes)
var windscreen =req.sanitize( req.body.windscreen)
var windscreenNotes =req.sanitize( req.body.windscreenNotes)
var horn =req.sanitize( req.body.horn)
var hornNotes =req.sanitize( req.body.hornNotes)
var lights =req.sanitize( req.body.lights)
var lightsNotes =req.sanitize( req.body.lightsNotes)
var sparetyre =req.sanitize( req.body.sparetyre)
var sparetyreNotes =req.sanitize( req.body.sparetyreNotes)
var brakes =req.sanitize( req.body.brakes)
var brakesNotes =req.sanitize( req.body.brakesNotes)
var tyreDepth =req.sanitize( req.body.tyreDepth)
var tyreDepthNotes =req.sanitize( req.body.tyreDepthNotes)
var mirrors =req.sanitize( req.body.mirrors)
var mirrorsNotes =req.sanitize( req.body.mirrorsNotes)
var seats =req.sanitize( req.body.seats)
var seatsNotes =req.sanitize( req.body.seatsNotes)
var wipers =req.sanitize( req.body.wipers)
var wipersNotes =req.sanitize( req.body.wipersNotes)
var warninglights =req.sanitize( req.body.warninglights)
var warninglightsNotes =req.sanitize( req.body.warninglightsNotes)
var steeringwheel =req.sanitize( req.body.steeringwheel)
var steeringwheelNotes =req.sanitize( req.body.steeringwheelNotes)
var battery =req.sanitize( req.body.battery)
var batteryNotes =req.sanitize( req.body.batteryNotes)
var leaks =req.sanitize( req.body.leaks)
var leaksNotes =req.sanitize( req.body.leaksNotes)
var doors =req.sanitize( req.body.doors)
var doorsNotes =req.sanitize( req.body.doorsNotes)
var agreement =req.sanitize( req.body.agreement)
var created =req.sanitize( req.body.created)
var newCarcheck={
carPlate:carPlate,
carModel:carModel,
carMiles:carMiles,
tyrePressure:tyrePressure,
tyrePressureNotes:tyrePressureNotes,
fluidsNotes:fluidsNotes,
fluids:fluids,
damageVisual:damageVisual,
damageVisualNotes:damageVisualNotes,
cleaned:cleaned,
cleanedNotes:cleanedNotes,
windscreen:windscreen,
windscreenNotes:windscreenNotes,
horn:horn,
hornNotes:hornNotes,
lights:lights,
lightsNotes:lightsNotes,
sparetyre:sparetyre,
sparetyreNotes:sparetyreNotes,
brakes:brakes,
brakesNotes:brakesNotes,
tyreDepth:tyreDepth,
tyreDepthNotes:tyreDepthNotes,
mirrors:mirrors,
mirrorsNotes:mirrorsNotes,
seats:seats,
seatsNotes:seatsNotes,
wipers:wipers,
wipersNotes:wipersNotes,
warninglights:warninglights,
warninglightsNotes:warninglightsNotes,
steeringwheel:steeringwheel,
steeringwheelNotes:steeringwheelNotes,
battery:battery,
batteryNotes:batteryNotes,
leaks:leaks,
leaksNotes:leaksNotes,
doors:doors,
doorsNotes:doorsNotes,
agreement:agreement,
created:created
}
Carcheck.create(newCarcheck, function(err,newEntry){
if(err){
console.log(err);
} else {
//redirect to thank you page
res.redirect("/checkadded");
}
});
});
//check added page
app.get("/checkadded", function(req, res){
res.render("checkadded");
});
//Logout
app.get("/logout", function(req, res){
req.logout();
res.redirect("/login");
})
//Middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
app.listen(process.env.PORT || 3000, process.env.ID, function()
{
console.log("Server Started");
});
caruser模式是这样的:
//**********************
//Creating Car User Schema to add it to car_check_app
//**********************
const mongoose = require("mongoose");
const passportLocalMongoose=require("passport-local-mongoose");
var carUserSchema=new mongoose.Schema({
username: String,
firstname: String,
lastname: String,
role: String,
password: String
});
carUserSchema.plugin(passportLocalMongoose);
//Creating Car Check Model
module.exports=mongoose.model("Caruser",carUserSchema);
我真的很感激任何帮助,因为我似乎一直呆在这里,不知道该怎么办。
答案 0 :(得分:0)
我发现了为什么isAuthenticated无法正常工作并且总是给出错误的结果。 序列化/反序列化应仅用于身份验证应适用的架构。我在创建的所有架构中都使用了它,因此即使登录凭据正确也给出了错误的答案。