Persistent login with connect-auth

I create node.js and use connect-auth to authenticate the user / password, and what I would like to do is let users log in for extended periods of time. While playing and looking at the source, it seems that connect-auth depends on the connection sessions to maintain the authenticated state, therefore, as soon as the session cookie expires (by default 4 hours), the user logs out.

One option is that fork connect-auth and refactor are not dependent on req.session, but this is not trivial. Another option is to change the default age of the session cookie to really high, but I want my session object to die with the session.

Anyone have any suggestions? Can I ignore an existing solution?

Thank!

+5
source share
1 answer

I would not use / fork Connect-Auth. This connection plugin breaks the idea / architecture of the onion ring and makes (IMHO) your code unreadable / brings unnecessary complexity.

Authentication is too easy for the library. (If you are talking about simple user login)

I use self-signed authorization. Below you can find a simplified version. It also depends on the session files, but it can easily be replaced with persistent cookies.

Very simple authentication with connection

(It is completed. Just do it for testing)

var connect = require('connect');
var urlpaser = require('url');

var authCheck = function (req, res, next) {
    url = req.urlp = urlpaser.parse(req.url, true);

    // ####
    // Logout
    if ( url.pathname == "/logout" ) {
      req.session.destroy();
    }

    // ####
    // Is User already validated?
    if (req.session && req.session.auth == true) {
      next(); // stop here and pass to the next onion ring of connect
      return;
    }

    // ########
    // Auth - Replace this simple if with you Database or File or Whatever...
    // If Database, you need a Async callback...
    if ( url.pathname == "/login" && 
         url.query.name == "max" && 
         url.query.pwd == "herewego"  ) {
      req.session.auth = true;
      next();
      return;
    }

    // ####
    // User is not unauthorized. Stop talking to him.
    res.writeHead(403);
    res.end('Sorry you are unauthorized.\n\nFor a login use: /login?name=max&pwd=herewego');
    return;
}

var helloWorldContent = function (req, res, next) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}

var server = connect.createServer(
      connect.logger({ format: ':method :url' }),
      connect.cookieParser(),
      connect.session({ secret: 'foobar' }),
      connect.bodyParser(),
      authCheck,
      helloWorldContent
);

server.listen(3000);
+6
source

All Articles