简体   繁体   中英

NodeJS sessions, cookies and mysql

I'm trying to build an auth system and I have 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

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

Why do you not just use Express's session handling? if you use the express command line tool as express --sessions it will create the project template with session support. 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? (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).

Final thing, you are using Express wrong (no offence). 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.

(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. 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.

You need to save your cookie value in the response object:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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