1

我无法让与 mongodb 的会话正常工作。我已经设置了以下代码,它可以毫无问题地创建用户。

我还可以看到我的sessions数据库正在填充,如下所示:

http://wes.io/LNbg/content

问题是,我从来没有处于登录状态。如果我只使用内存来存储会话,它工作正常,但是当移动到 mongodb 时,它不起作用。这是我认为问题代码所在的位置,但您可以在此处查看整个应用程序:http ://wes.io/LNVg

passport.use(new LocalStrategy(
  function(username, password, done) {
    console.log('Trying to log in as '.green, username);

    User.findOne({ name: username }, function(err, user) {
      if (err) {return done(err); }

      if(user) {
        console.log('Found user with the username of'.green,user); 
        done(null, user);
      } 

      else {
        console.log('No user found...  '.red.inverse, username, password);
        var user = new User();
        user.name = username;
        user.username = username;
        user.password = password;
        user.save(function(err){
          if(err) { throw err; }
          console.log('User created and saved'.green, user)
          done(null, user);
        })
      };

    });
  }
));

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

passport.deserializeUser(function(user, done) {
  done(null, user);
});

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(require('less-middleware')({ src: __dirname + '/public' }));
  app.use(express.favicon());
  app.use(express.bodyParser());
  app.use(express.logger('dev'));
  app.use(express.methodOverride());
  app.use(express.session({ 
        store: store
      , secret: 'applecake'
      , cookie : {
            maxAge : 604800 // one week
        }
  }));
  app.use(passport.initialize());
  app.use(passport.session()); 
  app.use(app.router);
});

编辑:这是会话存储的代码:

var express = require('express')
  , colors = require('colors')
  , routes = require('./routes')
  , mongoose = require('mongoose')
  , SessionStore = require("session-mongoose")(express)
  , store = new SessionStore({
        url: "mongodb://localhost/fb-session",
        interval: 120000 // expiration check worker run interval in millisec (default: 60000)
    })
  , Schema = mongoose.Schema
  , flash = require('connect-flash')
  , userz = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
4

1 回答 1

0

原来这是序列化和反序列化方法的问题。这是我的名称示例,尽管它将更改为用户 ID

passport.serializeUser(function(user, done) {
    done(null, user.name);
});
passport.deserializeUser(function(name, done) {
    done(null, { name: name });
});
于 2012-12-14T22:04:45.640 回答