Node.JS Passport不保持登录状态

时间:2017-10-13 00:16:16

标签: node.js mongodb session express passport.js

大家。我一直有这个问题,当我登录时,我无法登录。是的我有快速会话模块,并设置没有错误。当我尝试做一些需要你登录的东西时,我应该已经登录,它只是把我带到了登录页面(我已经编程了)。非常感谢您的帮助。对不起,如果这是一个愚蠢的问题(我不认为)。再次感谢你。

let express = require("express"),
    app = express(),
    bodyParser = require("body-parser"),
    methodOV = require("method-override"),
    mongoose = require("mongoose"),
    passport = require("passport"),
    pL = require("passport-local"),
    pLM = require("passport-local-mongoose"),
    User = require("./user.js");

mongoose.connect("mongodb://localhost/max");

let maxBlog = new mongoose.Schema({
    title: String,
    author: String,
    content: String
});

let Blog = mongoose.model('Blog', maxBlog);

Blog.create({
    title: "Test",
    author: "Test",
    content: "Test"
});

app.use(express.static("public"));

app.use(bodyParser.urlencoded({ extended: false }))

app.use(bodyParser.json());

app.use(methodOV("_method"));

app.set('view engine', 'ejs');

//AUTH

app.use(passport.initialize());
app.use(passport.session());
passport.use(new pL(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(require("express-session")({
    secret: "Rusty is the best and cutest dog in the world",
    resave: false,
    saveUninitialized: false
}));

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

app.post("/register", (req, res) =>{
    User.register(new User({username: req.body.username}), req.body.password, (err, user) => {
        if(err){
            console.log(err);
            return res.render("register");
        }
        passport.authenticate("local")(req, res, function(){
           res.redirect("/");
        });
    });
});

// LOGIN ROUTES
app.get("/login", (req, res) =>{
   res.render("login"); 
});
//login logic
app.post("/login", passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login"
}) ,(req, res) =>{
});

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


const isLoggedIn = (req, res, next) =>{
    if(req.isAuthenticated()){
        return next();
    } else {
      res.redirect("/login");
    }
};

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

app.get("/home", (req,res) => {
    res.render("index");
});

app.get("/blog", (req,res) => {
    Blog.find({},(err,blog) => {
        if (err){
            res.send("An unexpected error occured. Please try again later.");
        } else {
            res.render("blog",{blogs:blog});
        }
    });
});

app.post("/blog",isLoggedIn,(req,res) => {
    Blog.create({
        title: req.body.t,
        author: req.body.a,
        content: req.body.c
    }), (err,create) => {
        if (err){
            res.send("There was an error. Try again later.");
        } else {
            res.render("blogs");
        }
    };
});

app.get("/blogs/:id",(req,res) => {
    Blog.findById(req.params.id,(err,find) => {
        if (err){
            res.send("An error occured. Please try again later.");
        } else {
            res.render("show",{blog:find,isLoggedIn:isLoggedIn});
        }
    });
});

app.put("/blogs/:id/edit",isLoggedIn,(req,res) => {
    Blog.findByIdAndUpdate(req.params.id,({
        title: req.body.t,
        content: req.body.c,
        author: req.body.a
    }),(err,update) => {
        if (err){
            res.send("An error occured. Please try again later.");
        } else {
            res.redirect("/blogs"+req.params.id);
        }
    });
});

app.delete("/blogs/:id",isLoggedIn,(req,res) => {
    Blogs.findByIdAndRemove(req.params.id,(err,result) => {
        if(err){
            res.send("Sorry. There was an error please try again later.");
        } else {
            res.redirect("/blogs");
        }
    });
});

app.listen(8080);

1 个答案:

答案 0 :(得分:2)

您需要更新2件事:

1-考虑在护照初始化之前添加会话中间件

2-您需要设置会话cookie的maxAge

所以替换这部分:

app.use(passport.initialize());
app.use(passport.session());
passport.use(new pL(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(require("express-session")({
    secret: "Rusty is the best and cutest dog in the world",
    resave: false,
    saveUninitialized: false
}));

使用:

app.use(require("express-session")({
    secret: "Rusty is the best and cutest dog in the world",
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: false,
        maxAge: 3600000 //1 hour
    }
}));

app.use(passport.initialize());
app.use(passport.session());
passport.use(new pL(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());