开发者

Persistant Login with connect-auth

I'm building a node.js and using connect-auth for user/pass authentication, and what I'd like to do is allow users to be logged in for long periods of time. Playing around and looking through the source it seems like connect-auth depends on connect sessions to maintain authenticated state, so once the session cookie expires (default 4 hrs) the user gets logged out.

One option is to fork connect-auth and refactor to not be dependent on req.ses开发者_如何学Csion, but that's non-trivial. Another option is to change the default age on the session cookie to really high, but I want my session object to be able to die with the session.

Anyone have any suggestions? Am I overlooking an existing solution?

Thanks!


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

Authentification is too simple for a library. (If you a talking about a simple user login)

I'm using a self written auth. You can find a simplified version below. It also depends on session-cookies but it can easily be replaced with persistant cookies.

A very simple authentication with connect

(It's complete. Just execute 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜