用戶認證和會話存儲使用Passport
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api'),
http = require('http'),
path = require('path'),
mysql = require('mysql'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
//MySQL
var sqlInfo = {
host: 'localhost',
user: 'root',
password: '',
database: 'dbname'
}
global.client = mysql.createConnection(sqlInfo);
client.connect();
var app = module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser("secret"));
app.use(express.session({
secret: 'keyboard cat'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
passport.use(new LocalStrategy(
function(username, password, done) {
return check_auth_user(username,password,done);
}
));
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
}
/**
* routes start---------------------------------------------------------------
*/
// home page contain login form
app.get('/home', function(reg, res){
//check user session value, is logged in
if(req.user)
res.render('dash',{
username: req.user['member_id']//req.user array contains serializeUser data
});
else
res.render('index');
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/home');
});
//login form submit as post
app.post('/login',
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/home'
})
);
//to project dashboard
app.get('/dash',routes.dash);
//to project dashboard
app.get('/signup',routes.signup);
//to project dashboard
app.get('*', routes.index);
/**
* routes end---------------------------------------------------------------------
*/
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Click for more details with example!
passportJs是最好的安全認證,我的建議是一樣的passportJS – FLF
如何使用socket.id作爲會話ID?它也是可行的嗎? –
@HongZhou,我不知道。但我知道Passport使得身份驗證非常簡單,如果有一個使用passport和socket.io的模塊,那麼很明顯其他人已經嘗試過它,它似乎工作正常:) – kentcdodds