2013-06-21 93 views
2

我一直在本地與Couch和Redis一起構建Express應用程序。它一直在正常工作。使用Express'Connect-Redis將會話存儲在遠程Redis服務器上

我現在試圖使用託管在Iris Redis上的遠程Redis服務器。我已經嘗試了幾天,但似乎無法使用Passport的本地策略進行身份驗證後,Express'Connect-redis返回cookie。但是,當我運行本地Redis服務器時,這樣工作得很好。

app.configure(function(){ 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'jade'); 
app.use(express.favicon()); 
app.use(express.logger('dev')); 
app.use('/upload', upload.fileHandler()); 
app.use(express.bodyParser({ keepExtensions: true, uploadDir: 'public/uploads' })); 
app.use(express.methodOverride()); 
app.use(express.cookieParser()); 
app.use(express.session({ cookie: { maxAge: 60000000 }, secret: "sauce", store: new RedisStore({ 
    port: 6379, 
    host: 'url', 
    pass: 'sauce' 
}) })); 
app.use(flash()); 
app.use(passport.initialize()); 
app.use(passport.session()); 
app.use(app.router); 
app.use(express.static(path.join(__dirname, 'public'))); 

});


// Authentication 
passport.use(new LocalStrategy(function(username, password, done) { 

username = username.toLowerCase(); 
db.get(username, function (err, doc) { 

    if (err) { 
    console.log(err); 
    return done(err); 
    } 
    if (!doc) { 
    return done(null, false, { message: 'No user by that name.' }); 
    } 
    if (doc.password !== password) { 
    return done(null, false, { message: 'Incorrect password.' }); 
    } 
    return done(null, doc); 
    }); 

    }) 
); 

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

passport.deserializeUser(function (userId, done) { 
    db.get(userId, function(err, user){ 
    if(err){ 
     return (500, err); 
    } else {         
    done(null, _.omit(user, ["password"])); 
    } 
    }); 
}); 

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

回答

1

你似乎並不被指定Redis的分貝;這可能是失敗的原因。

更一般地,我建議在環境變量中使用URL來存儲redis參數,因此無論您是連接到本地還是遠程服務器,都使用相同的分析代碼。例如,從app.js:

var config = require('./config/config.js') 

app.use(express.session({ 
    store: new RedisStore({ 
     port: config.redisPort, 
     host: config.redisHost, 
     db: config.redisDatabase, 
     pass: config.redisPassword}), 
    secret: 'pick a good password', 
    proxy: true, // necessary if you're behind a proxy 
    cookie: { secure: true } 
})) 

而且config.js:

var url = require('url') 
var config = {}; 
var redisUrl; 

if (typeof(process.env.REDISTOGO_URL) != 'undefined') { 
    redisUrl = url.parse(process.env.REDISTOGO_URL); 
} 
else redisUrl = url.parse('redis://:@127.0.0.1:6379/0'); 

config.redisProtocol = redisUrl.protocol.substr(0, redisUrl.protocol.length - 1); // Remove trailing ':' 
config.redisUsername = redisUrl.auth.split(':')[0]; 
config.redisPassword = redisUrl.auth.split(':')[1]; 
config.redisHost = redisUrl.hostname; 
config.redisPort = redisUrl.port; 
config.redisDatabase = redisUrl.path.substring(1); 

console.log('Using Redis store ' + config.redisDatabase) 

module.exports = config; 
相關問題