LocalStrategy Passport返回null

时间:2019-03-08 23:23:20

标签: javascript express mongoose passport.js passport-local

因此,我正在尝试使用Mongoose和NodeJS创建一个护照认证应用程序。但是,每当我发送登录请求时, app.js 中的“本地策略”功能似乎都将返回null。这是代码:

// Issue is here:
passport.use(new LocalStrategy((username, password, done) => {
        User.findOne({username, password}, (err, user) => {
            console.log(`\n${username} : ${password}\n`)
            console.log(user, err)
            return done(null, user); //return done(null, "useraaaa");
        });
    }
));

因此,当使用用户名a和密码a登录时,我的控制台将其记录下来。

输出:

GET /login 304 1503.039 ms - -               
GET /stylesheets/style.css 304 2.296 ms - -  

a : a                                        

null null                                    
POST /login 302 171.891 ms - 56              
GET /login 200 92.865 ms - 501               
GET /stylesheets/style.css 304 2.340 ms - -  

请注意,用户的输出如何为 null (错误)。我还在我的serializeUser和deserializeUser函数中放置了 console.log 语句,但是,代码似乎从未到达那里。

这里是必要的功能。

passport.serializeUser(function(user, done) {
    console.log(user);
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id).then(user  => {
        console.log(user);
        done(err, user);
    });
});

也:

exports.login = passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login"
});

我将提供受影响的主要文件。如果需要更多信息,我会很乐意提供。

app.js (我正在使用Express模板)

const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const flash = require("connect-flash");
const expressValidator = require("express-validator");

const indexRouter = require("./routes/index");
const app = express();

const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo")(session);
const LocalStrategy = require("passport-local").Strategy;

const User = require("./models/User");
mongoose.connect("removed for obvious reasons", {useNewUrlParser: true});
const db = mongoose.connection;

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use(session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: false,
    //cookie: { secure: true }
    store: new MongoStore({mongooseConnection: db})
}));

app.use(passport.initialize());
app.use(passport.session());
app.use("/", indexRouter);



// Issue is here:
passport.use(new LocalStrategy((username, password, done) => {
        User.findOne({username, password}, (err, user) => {
            console.log(`\n${username} : ${password}\n`)
            console.log(user, err)
            return done(null, user); //return done(null, "useraaaa");
        });
    }
));



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get("env") === "development" ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render("./handlers/error");
});

module.exports = app;

user.js (我的路线的控制器模块)

const mongoose = require("mongoose");
const expressValidtor = require("express-validator");
const passport = require("passport");
const User = require("../models/User");
const db = mongoose.connection;

const bcrypt = require("bcrypt");
const salt = 10;

mongoose.connect("removed for obvious reasons", {useNewUrlParser: true});
db.on("error", console.error.bind(this, "DB Error: "))
db.once("open", () => console.log("Connected to DB"));

// Post Requests
exports.register = (req, res) => {
    const {username, email, password} = req.body;

    req.checkBody("username", "Empty username").notEmpty();
    req.checkBody("email", "Empty email").notEmpty();
    req.checkBody("password", "Empty password").notEmpty();

    if (req.validationErrors()) {
        console.log(`Error! ${JSON.stringify(req.validationErrors())}`);
        return req.redirect("/");
    };

    bcrypt.hash(password, salt, (err, hash) => {
        const user = new User();

        user.username = username;
        user.email = email;
        user.password = hash;

        user.save((err, response) => {
            if (err) {
                console.error(err);
                return res.redirect("/");
            };

            User.findOne({username}, function(err, r) {
                if (err) throw err;
                const id = r._id;

                req.login(id, (err) => {
                    console.log("Success!");
                    res.redirect("/");
                }); 
            });
        });
    });
};

exports.auth = (req, res, next) => {
    return (req.isAuthenticated() ? next() : res.redirect("/login"));
};

passport.serializeUser(function(user, done) {
    console.log(user);
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id).then(user  => {
        console.log(user);
        done(err, user);
    });
});

/*
exports.login = async (req, res) => {
    res.send(await User.findOne({username: req.body.username, password: req.body.password}) || "Not found.");
};
*/

exports.login = passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login"
});

// Get Requests
exports.home = (req, res) => {
    console.log("\n");
    console.log(req.user);
    console.log(req.isAuthenticated());
    console.log("\n");
    res.render("home", {title: "Auth App"});
};

exports.register_gui = (req, res) => {
    res.render("register", {title: "Register"});
};

exports.login_gui = (req, res) => {
    res.render("login", {title: "Login"});
};

exports.profile_gui = (req, res) => {
    res.render("profile", {title: "Profile"})
};

exports.list = async (req, res) => {
    res.json(await User.find());
};

User.js (MongoDB模式)

const mongoose = require("mongoose");

function email_validate(n) {
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(n);
};

const User = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        trim: true,
        required: "Enter a username."
    },

    password: {
        type: String,
        required: true,
        trim: true,
        required: "Enter a password."
    },

    email: {
        type: String,
        lowercase: true,
        trim: true,
        unique: true,
        required: "Enter a email address",
        validate: [email_validate, "Invalid email address."]
    }   
});

module.exports = mongoose.model("Users", User);

在进行更改时,我不断收到诸如 CastError的错误:在路径“ _id” 无法将用户序列化为会话 UnhandledPromiseRejectionWarning:CastError:模型“ Users”的路径“ _id”上的“ true”值“ true”转换为ObjectId失败,依此类推...

任何帮助将不胜感激。 谢谢你。

1 个答案:

答案 0 :(得分:0)

调试后,放置无数 console.log 语句,我终于找到了错误。将来,我会将解决方案留给所有可能的观看者。

因此,在第69行的 user.js 中:

passport.serializeUser(function(user, done) {
    console.log(user);
    done(null, user.id);
});

更改为:

passport.serializeUser(function(user, done) {
    console.log(user);
    done(null, user._id); // Underscore before ID.
});

显然,该代码正在尝试返回整个文档。导致缓冲区数据为空或为空(如果未找到文档)。

解决方案是一个字符。

我现在真的很生气。