有人可以查看我的代码并说出错误吗? 我是节点js的新手,但我正在尝试理解它并编写将对用户进行身份验证并将实时数据提供给仪表板的应用程序。我坚持登录程序。
登录用户通过后返回登录屏幕。如果我将移动函数res.flash(),它说需要sesion。 我花了两天时间编写这段代码。敬请期待。
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var flash = require('connect-flash');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var passport = require('passport');
var signature = require('cookie-signature');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var http = require('http');
var cookie = require('cookie');
// Starting express server
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {});
// Share variables to socket;
var onlineUsers = []; var dataIO=[];
// MONGOSE DATABASE
mongoose.connect('mongodb://localhost/mydb');
var Schema = mongoose.Schema;
var db = mongoose.connection;
var UserDetail = new Schema({
username: String,
password: String
}, {
collection: 'users'
});
var users = mongoose.model('users', UserDetail);
app.use(flash());
/// PASSPORT
app.use(passport.initialize());
app.use(passport.session());
var session = require('express-session');
var store = new session.MemoryStore();
var secret = 'secret-session-key';
app.use(session({
secret : secret,
store : store,
saveUninitialized: true,
resave: true}
));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/loginSuccess',
failureRedirect: '/loginFailure',
})
);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
process.nextTick(function() {
// auth logic
users.findOne({
'username': username,
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
});
}));
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.send('hi');
socket.send('onlineUsers :'+ onlineUsers);
});
io.on('connection', function(socket) {
if (socket.handshake & socket.handshake.headers & socket.handshake.headers.cookie) {
var raw = cookie.parse(socket.handshake.headers.cookie)['connect.sid'];
if (raw) {
socket.sessionId = signature.unsign(raw.slice(2), secret);
}
}
if (socket.sessionId) {
store.get(socket.sessionId, function(err, session) {
// console.log(session.passport.user.username);
if (session) {
if (onlineUsers.indexOf(session.passport.user.username) == -1) {
onlineUsers.push(session.passport.user.username);
console.log(onlineUsers);
}
}
});
}
socket.on('disconnect', function() {
console.log('disconnecting');
if (socket.handshake & socket.handshake.headers & socket.handshake.headers.cookie) {
var raw = cookie.parse(socket.handshake.headers.cookie)['connect.sid'];
if (raw) {
socket.sessionId = signature.unsign(raw.slice(2), secret);
}
}
if (socket.sessionId) {
// console.log(socket.sessionId);
store.get(socket.sessionId, function(err, session) {
if (session) {
// console.log(session);
console.log(onlineUsers);
onlineUsers.splice(onlineUsers.indexOf(session.passport.user.username), 1);
console.log(onlineUsers);
}
});
}
});
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// 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, next) {
// 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');
});
module.exports.onlineUsers = onlineUsers;
module.exports = app;
答案 0 :(得分:0)
一些事情:
(A)mongoose.connect()
是一个异步操作,它返回一个promise或进行回调。虽然它允许立即开始使用您的模型,而无需等待mongoose建立与MongoDB的连接,但在完成其余代码之前,确保您的连接已打开是更安全的(参见{{3更多细节)
mongoose.connect('mongodb://localhost/mydb')
.then(function() {
// rest of your setup goes here
}).catch(function(err) {
// do some error handling
});
(B)使用会话时,Passport设置应 后调用app.use(session(...))
(参见http://mongoosejs.com/docs/connections.html并向下滚动到“会话”一章)
app.use(session({
secret : secret,
store : store,
saveUninitialized: true,
resave: true}
));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(flash());
/// PASSPORT
app.use(passport.initialize());
app.use(passport.session());
在我看来,您应该将所有快速应用设置重新组合在一起,而不是将其传播到您的代码中,并在所有快速配置和启动后启动服务器app.listen()
。路线设置完成。
Passport的作者写了一个很好的例子,你可以在这里访问http://www.passportjs.org/docs/configure
(C)你应该在某处宣布2条路线/loginSuccess
和/loginFailure
(我看不到它)
总的来说,我的建议是克隆https://github.com/passport/express-4.x-local-example/并从那里逐步增加复杂性(用mongoose替换示例的假数据库,然后添加socket.io,...)
希望有所帮助