Passport.js - Local strategy doesn't authenticate

痞子三分冷 提交于 2019-12-24 09:08:43

问题


I've build a simple app that allows users to log in through google using passport's google strategy and it all works fine.

I'm trying to add a local strategy as well, but I can't find a solution.

Database works fine as users get created during sign up process. But redirecting to /profile doesn't work right after signing up. Instead, I get redirected to the login page; this normally happens when the user is trying to visit the /profile page but is not logged in.

Logging in seems to work initially as I get redirected to "/" as expected with successRedirect: "/". But if I try to go to the profile page I can't. Also, if i run req.isAuthenticated()it returns false.

EDIT: it seems like authentication itself works, but somehow it doesn't keep up. If I run a console.log("req.isAuthenticated") right after signing up it returns true, but as soon as I go to another route (example: /), by running a console.log("req.isAuthenticated") in the get request of that route I get a false. It's like I can login but I can't stay logged in. Could this be related to cookies? Does anyone know how to solve?

Here is some code:

app.js

const   express           = require("express"),
        mongoose          = require("mongoose"),
        bodyParser        = require("body-parser"),
        cookieSession     = require("cookie-session"),
        passport          = require("passport");  


const keys = require("./config/keys"); // requiring keys
const passportSetup = require("./config/passport-setup"); //requiring passport config
const localPassportSetup = require("./config/passport-local-setup"); // requiring local passport config
const authRoutes = require("./routes/auth"); // requiring auth routes
const profileRoutes = require("./routes/profile");
const Thought = require("./models/thought"); // requiring Thought model

//Initialize express app
const app = express();

app.use(express.static(__dirname + "/public"));
app.set("view engine", "ejs"); 
app.use(bodyParser.urlencoded({extended: true}));

app.use(cookieSession({
    maxAge: 24 * 60 * 60 * 1000,
    keys: [keys.session.cookieKey]
}));

//initialize passport 
app.use(passport.initialize());
app.use(passport.session());

app.use("/auth", authRoutes); // setup auth routes
app.use("/profile", profileRoutes); // setup profile routes

mongoose.connect('mongodb://localhost/thoughtApp'); // connecting database

passport-local-setup.js

const passport = require("passport");
const localStrategy = require("passport-local");
const mongoose = require("mongoose");

const LocalUser = require("../models/localUser");

passport.use(new localStrategy(LocalUser.authenticate()))
passport.serializeUser(LocalUser.serializeUser());
passport.deserializeUser(LocalUser.deserializeUser());

auth.js

const router = require("express").Router();
const passport = require("passport");
const passportLocal = require("passport-local");
const localUser = require("../models/localUser");

const authCheck = function (req, res, next) {
    if (!req.user) {
        next();
    } else {
        res.redirect("/");
    }
};
//login

router.get("/login", authCheck, (req, res) => {
    res.render("login", {user: req.user});
});

router.post("/login", passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login"
}), (req, res) => {

});
// logout
router.get("/logout", (req, res) => {
    //handle with passport
    req.logout();
    res.redirect("/");
});

//register
router.get("/signup", authCheck, (req, res) => {
    res.render("signup", {user: req.user});
});

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

localUser.js

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");

const localUserSchema = new mongoose.Schema({
    username: String,
    password: String
});

localUserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("LocalUser", localUserSchema);

I've been searching the web but I can't find a solution. Why is this not working?

来源:https://stackoverflow.com/questions/51558481/passport-js-local-strategy-doesnt-authenticate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!