目前正在使用:
最近我正在使用重定向进行简单的登录表单,我想在用户成功连接时创建会话。
在密码验证成功时,我尝试了:
req.session.authenticated = true;
但这给了我错误:
无法设置未定义的属性“已验证”
对于处理会话,我有以下代码:
server.js
var express = require('express');
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var options = {
host: 'localhost',
port: 3306,
user: 'myuser',
password: 'mypassword',
database: 'mydb_repo'
};
var router = express.Router();
var sessionStore = new MySQLStore(options);
router.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: sessionStore,
resave: false,
saveUninitialized: false,
path: "/",
// How frequently expired sessions will be cleared; milliseconds:
checkExpirationInterval: 900000,
// The maximum age of a valid session; milliseconds:
expiration: 86400000
}));
// middleware to use for all requests
router.use(function(req, res, next) {
if (req.url === '/bakery' && (!req.session || !req.session.authenticated)) {
res.send('unauthorised');
return;
}else{
// do logging
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log('-- EVENT -- The wolf is in the pen. '+ip);
next(); // make sure we go to the next routes and don't stop here
}
});
require('./routes')(router);
/routes/index.js
var fs = require('fs');
module.exports = function(router){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(router);
});
}
/routes/oven.js
module.exports = function(router){
router.get('/oven/', function(req, res){
var text = fs.readFileSync('./app/views/oven.html','utf8')
var content = text.replace("[TITLE]", "Cookie Touch");
res.send(content);
});
router.route('/oven')
.post(function(req, res) {
var email = req.body.inputEmail;
var pass = req.body.inputPassword;
console.warn("-- WARN -- A new cookie in the Oven: "+email);
authentificate(email, pass, req, res);
});
}
function authentificate(email, pass, req, res){
//get salt and hash passes (long code)
checkPass(email, hash_f, res);
});
}
function checkPass(email, hash, req, res){
connection.query('SELECT password AS pass FROM user WHERE email="'+email+'"', function (error, results, fields) {
if (results[0].pass == hash){
req.session.authenticated = true;
res.redirect('/api/bakery');
console.log("Successfully authentificated!");
}else{
res.send("Wrong Password");
console.log("Wrong Password");
}
});
}
我尝试在 oven.js 中添加会话的定义和router.use,但没有成功而不是router.use(session...
我也尝试了app.use(session...
< / p>
答案 0 :(得分:1)
你正在使用checkPass只有三个参数checkPass(email, hash_f, res)
,你应该通过四个参数。即req
未通过。
function authentificate(email, pass, req, res){
//get salt and hash passes (long code)
checkPass(email, hash_f, req, res)
});
}