我不知道为什么我的代码不通过中间件就直接失败。当我使用路由auth/login
时,代码必须被passport.js
捕获并在数据库中进行验证,但是代码直接失败并返回空用户作为结果:
app.js
const express = require("express");
const path = require("path");
const logger = require("morgan");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const winston = require("winston");
const config = require("config");
let morgan = require("morgan");
let options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }
};
require("dotenv").config();
require("./shared/passport");
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/json"}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
const index = require("./routes/index");
const users = require("./routes/users");
const sites = require("./routes/sites");
const auth = require("./routes/auth");
app.use("/", index);
app.use("/users", users.router);
app.use("/auth", auth.router);
app.use("/sites", sites.router);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res) {
// 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("error");
});
mongoose.connect(config.DBHost, options);
const db = mongoose.connection;
db.on("error", error => {
if (!error) {
winston.log("info", "Mongodb is connected.");
return;
}
winston.log("error connecting mongo...", {error});
return;
});
if(config.util.getEnv("NODE_ENV") !== "test") {
app.use(morgan("combined"));
}
module.exports = app;
auth.js
const express = require("express");
const router = express.Router();
const config = require("config");
const jwt = require("jsonwebtoken");
const passport = require("passport");
router.post("/login", userLogin);
function userLogin(req, res) {
passport.authenticate("local", {session: false}, (err, user) => {
if (err || !user) {
return res.status(400).json({
message: "Something is not right",
user : user
});
}
req.login(user, {session: false}, (err) => {
if (err) {
res.send(err);
}
const token = jwt.sign({
id: user._id
}, config.token_secret, {
expiresIn: 86400
});
return res.json({user, token});
});
})(req, res);
}
module.exports = {
router
};
passport.js
const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const User = require("../schemas/users/index");
const passportJWT = require("passport-jwt");
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
const config = require("config");
passport.use(new localStrategy({
usernameField: "email",
passwordField: "password"}, function (user, password, cb) {
return User.findOne({
$or: [{
username: user,
password
},
{
email: user,
password
}]}).then(user => {
if (!user) {
return cb(null, false, {
message: "Incorrect email or password"
});
}
return cb(null, user, {
message: "Logged In Successfully"
});
}).catch(err => cb(err));
}));
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: config.token_secret
}, function(jwtPayload, cb) {
return User.findOneById(jwtPayload.id)
.then(user => {
return cb(null, user);
})
.catch(err => {
return cb(err);
});
}));
我还必须说用户/密码已正确发送,因为我可以调试req.body
对象以查看正在发送的数据。
当我在{strong> passport.js 内的console.log
处放置passport.use(new localStrategy({...
时,我看不到它们,因此我猜想代码根本没有执行。