简体   繁体   English

NodeJS会话,cookie和mysql

[英]NodeJS sessions, cookies and mysql

I'm trying to build an auth system and I have app.js 我正在尝试构建一个auth系统,我有app.js

var express = require('express')
  , MemoryStore = require('express').session.MemoryStore
  , app = express();

app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat', store: new MemoryStore({ reapInterval: 60000 * 10 })}));
app.use(app.router);

and the route.index as 和route.index为

var express = require('express')
  , mysql = require('mysql')
  , crypto = require('crypto')
  , app = module.exports = express();

app.get('/*',function(req,res){
    var url = req.url.split('/');
    if (url[1] == 'favicon.ico')
        return;

    if (!req.session.user) {
        if (url.length == 4 && url[1] == 'login') {     
            var connection = mysql.createConnection({
                host     : 'localhost',
                user     : 'user',
                password : 'pass',
            });
            var result = null;
            connection.connect();
            connection.query('use database');
            var word = url[3];
            var password = crypto.createHash('md5').update(word).digest("hex");
            connection.query('SELECT id,level FROM users WHERE email = "'+url[2]+'" AND password = "'+password+'"', function(err, rows, fields) {
              if (err) throw err;
                for (i in rows) {
                    result = rows[i].level;
                }
                req.session.user = result;
            });
            connection.end();
        }
    }

console.log(req.session.user)

when I access http://mydomain.com/login/user/pass a first time it shows in the last console call but a second time access the cookie is clean 当我第一次访问http://mydomain.com/login/user/pass时它在最后一次控制台调用中显示但是第二次访问cookie是干净的

Why do you not just use Express's session handling? 为什么你不只是使用Express的会话处理? if you use the express command line tool as express --sessions it will create the project template with session support. 如果您使用快速命令行工具作为express --sessions ,它将创建具有会话支持的项目模板。 From there you can copy the session lines into your current project. 从那里,您可以将会话行复制到当前项目中。 There more information in How do sessions work in Express.js with Node.js? 关于如何使用Node.js在Express.js中使用会话的更多信息 (which this looks like it may be a duplicate of) (看起来这可能是重复的)

As for sanitizing your SQL, you seem to be using the library, which will santitize your inputs for your if you use parameterized queries (ie, ? placeholders). 至于清理SQL,你似乎正在使用库,如果你使用参数化查询(即,占位符),它将为你的输入提供优惠。

Final thing, you are using Express wrong (no offence). 最后,你使用Express错误(没有冒犯)。 Express's router will let you split alot of your routes (along with allowing you to configure the favicon. See Unable to Change Favicon with Express.js (second answer). Using the '/*' route will just catch all GET requests, which greatly limits what the router can do for you. Express的路由器可以让你分割很多你的路由(以及允许你配置favicon。请参阅无法用Express.js更改Favicon (第二个答案)。使用'/ *'路由将捕获所有GET请求,这大大限制路由器可以为您做什么。

(continued from comments; putting it here for code blocks) Now that you have an app with session support, try these two routes : (继续评论;将其放在代码块中)现在你有一个支持会话支持的应用程序,试试这两个路径

app.get('/makesession', function (req, res) {
    req.session.message = 'Hello world';
    res.end('Created session with message : Hello world');
});
app.get('/getsession', function (req, res) {
    if (typeof req.session.message == 'undefined') {
        res.end('No session');
    } else {
        res.end('Session message: '+req.session.message);
    }
});

If you navigate in your browser to /makesession, it will set a session message and notify you that it did. 如果您在浏览器中导航到/ makesession,它将设置会话消息并通知您它已执行。 Now if you navigate to /getsession, it will send you back the session message if it exists, or else it will tell you that the session does not exist. 现在,如果您导航到/ getsession,它将返回会话消息(如果存在),否则它将告诉您会话不存在。

You need to save your cookie value in the response object: 您需要将cookie值保存在响应对象中:

res.cookie('session', 'user', result);

http://expressjs.com/api.html#res.cookie http://expressjs.com/api.html#res.cookie

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM