Node,Express 3和Passport:登录表单不起作用

时间:2013-02-13 16:46:36

标签: javascript node.js express passport.js

我是Node的新手,拥有Node,Express和Passport设置,看起来很有效。也就是说,我看不到任何错误消息。

问题是当我进入登录页面并尝试登录时,没有任何反应。单击按钮后页面刷新,但未执行任何操作。

我已粘贴以下代码。

这是我提交表单时的终端输出:

08:19:53 web.1  | POST /login 302 3ms - 68
08:19:53 web.1  | GET /login 304 11ms
08:19:53 web.1  | GET /stylesheets/base.css 304 1ms

这是登录视图(Jade):

- if (message)
  p
    strong =message

form(method="post", action="/login")
  fieldset
    label(for="username") Username
    input.text-input(type="text", name="username")

    label(for="password") Password
    input.text-input(type="password", name="password")

    button.btn-submit(type="submit") Login!

    a.btn-cancel(href="/") Cancel

这是最初调用登录页面的代码(为了清楚起见,我拿出了其他东西):

app.js

app.get("/login", routes.login);

路由/ index.js

(function() {
  var Post;

  Post = require('../models/Post');

  module.exports = {
    login: function(req, res) {
      return res.render("login", {
        user: req.user,
        message: req.flash("Login error!"),
        title: "Login | David Yeiser"
      });
    }
  };

}).call(this);

这是处理帖子的 app.js 的一部分:

app.post("/login", passport.authenticate("local", {
    failureRedirect: "/login",
    failureFlash: true
}), function(req, res) {
    return res.redirect("/office");
});

最后,这是整个 app.js

(function() {
  var LocalStrategy, app, express, findById, findByUsername, flash, http, mongoose, passport, path, routes, user, users, util;

  express = require('express');
  routes = require('./routes');
  user = require('./routes/user');
  http = require('http');
  path = require('path');
  mongoose = require('mongoose');
  passport = require('passport');
  flash = require('connect-flash');
  util = require('util');
  LocalStrategy = require('passport-local').Strategy;

  users = [
    {
      id: 1,
      username: 'bob',
      password: 'secret',
      email: 'bob@me.com',
      id: 2,
      username: 'nancy',
      password: 'secrettoo',
      email: 'nancy@me.com'
    }
  ];

  findById = function(id, fn) {
    var idx;
    idx = id - 1;
    if (users[idx]) {
      return fn(null, users[idx]);
    } else {
      return fn(new Error('User does not exist'));
    }
  };

  findByUsername = function(username, fn) {
    var i, len;
    i = 0;
    len = users.length;
    while (i < len) {
      user = users[i];
      if (user.username === username) {
        return fn(null, user);
      }
      i++;
    }
    return fn(null, null);
  };

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

  passport.deserializeUser(function(id, done) {
    return findById(id, function(err, user) {
      return done(err, user);
    });
  });

  passport.use(new LocalStrategy(function(username, password, done) {
    return process.nextTick(function() {
      return findByUsername(username, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          return done(null, false, {
            message: "Unknown user " + username
          });
        }
        if (user.password !== password) {
          return done(null, false, {
            message: "Invalid password"
          });
        }
        return done(null, user);
      });
    });
  }));

  app = express();

  app.configure(function() {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({
      secret: 'keyboard cat'
    }));
    app.use(flash());
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    return app.use(express["static"](path.join(__dirname, 'public')));
  });

  app.configure('development', function() {
    mongoose.connect('mongodb://localhost/davidyeiser_dev');
    return app.use(express.errorHandler());
  });

  app.get("/", routes.index);

  app.get("/login", routes.login);

  app.post("/login", passport.authenticate("local", {
    failureRedirect: "/login",
    failureFlash: true
  }), function(req, res) {
    return res.redirect("/office");
  });

  app.get("/logout", function(req, res) {
    req.logout();
    return res.redirect("/");
  });

  app.get("/post/new", routes.newPost);
  app.post("/post/new", routes.addPost);
  app.get("/post/:id", routes.viewPost);
  app.get("/users", user.list);

  http.createServer(app).listen(app.get("port"), function() {
    return console.log("Express server listening on port " + app.get("port"));
  });

}).call(this);

您看到的大部分内容都来自Passport Express 3示例: https://github.com/jaredhanson/passport-local/blob/master/examples/express3/

我很感谢你能给我的任何帮助。

1 个答案:

答案 0 :(得分:2)

啊哈!用户数组构造不正确。

  users = [
    {
      id: 1,
      username: 'bob',
      password: 'secret',
      email: 'bob@me.com',
      id: 2,
      username: 'nancy',
      password: 'secrettoo',
      email: 'nancy@me.com'
    }
  ];

需要:

  users = [
    {
      id: 1,
      username: 'bob',
      password: 'secret',
      email: 'bob@me.com'
    },
    {
      id: 2,
      username: 'nancy',
      password: 'secrettoo',
      email: 'nancy@me.com'
    }
  ];

我发现它的方式是我只是减少到一个用户(在大约1000个其他东西中)然后最终意识到这是错误。其他一切都保持不变。

(之前我没有抓住它的原因是因为我每次都在使用“bob”,并且从未想过尝试“南希”)