Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6200899
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T04:27:14+00:00 2026-05-24T04:27:14+00:00

I’m working on a simple node.js project that requires authentication. I decided to use

  • 0

I’m working on a simple node.js project that requires authentication. I decided to use connect-redis for sessions and a redis-backed database to store user login data.

Here is what I have setup so far:

// Module Dependencies

var express = require('express');
var redis = require('redis');
var client = redis.createClient();
var RedisStore = require('connect-redis')(express);
var crypto = require('crypto');

var app = module.exports = express.createServer();  

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'obqc487yusyfcbjgahkwfet73asdlkfyuga9r3a4', store: new RedisStore }));
  app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Message Helper

app.dynamicHelpers({
  // Index Alerts
  indexMessage: function(req){
    var msg = req.sessionStore.indexMessage;
    if (msg) return '<p class="message">' + msg + '</p>';
  },
  // Login Alerts
  loginMessage: function(req){
    var err = req.sessionStore.loginError;
    var msg = req.sessionStore.loginSuccess;
    delete req.sessionStore.loginError;
    delete req.sessionStore.loginSuccess;
    if (err) return '<p class="error">' + err + '</p>';
    if (msg) return '<p class="success">' + msg + '</p>';
  },
  // Register Alerts
  registerMessage: function(req){
    var err = req.sessionStore.registerError;
    var msg = req.sessionStore.registerSuccess;
    delete req.sessionStore.registerError;
    delete req.sessionStore.registerSuccess;
    if (err) return '<p class="error">' + err + '</p>';
    if (msg) return '<p class="success">' + msg + '</p>';
  },
  // Session Access
  sessionStore: function(req, res){
    return req.sessionStore;
  }
});

// Salt Generator

function generateSalt(){
  var text = "";
  var possible= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"
  for(var i = 0; i < 40; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  return text;
}

// Generate Hash

function hash(msg, key){
  return crypto.createHmac('sha256', key).update(msg).digest('hex');
}

// Authenticate

function authenticate(username, pass, fn){
  client.get('username:' + username + ':uid', function(err, reply){
    var uid = reply;
    client.get('uid:' + uid + ':pass', function(err, reply){
      var storedPass = reply;
      client.get('uid:' + uid + ':salt', function(err, reply){
        var storedSalt = reply;
        if (uid == null){
          return fn(new Error('cannot find user'));
        }
        if (storedPass == hash(pass, storedSalt)){
          client.get('uid:' + uid + ':name', function(err, reply){
            var name = reply;
            client.get('uid:' + uid + ':username', function(err, reply){
              var username = reply;
              var user = {
                name: name,
                username: username
              }
              return fn(null, user);
            });
          });
        }
      });
    });
  });
  fn(new Error('invalid password'));
}

function restrict(req, res, next){
  if (req.sessionStore.user) {
    next();
  } else {
    req.sessionStore.loginError = 'Access denied!';
    res.redirect('/login');
  }
}

function accessLogger(req, res, next) {
  console.log('/restricted accessed by %s', req.sessionStore.user.username);
  next();
}

// Routes

app.get('/', function(req, res){
  res.render('index', {
    title: 'TileTabs'
  });
});

app.get('/restricted', restrict, accessLogger, function(req, res){
  res.render('restricted', {
    title: 'Restricted Section'
  });
});

app.get('/logout', function(req, res){
  console.log(req.sessionStore.user.username + ' has logged out.');
  req.sessionStore.destroy(function(){
    res.redirect('home');
  });
});

app.get('/login', function(req, res){
  res.render('login', {
    title: 'TileTabs Login'
  });
});

app.post('/login', function(req, res){
  authenticate(req.body.username, req.body.password, function(err, user){
    if (user) {
      req.session.regenerate(function(){
        req.sessionStore.user = user;
        req.sessionStore.indexMessage = 'Authenticated as ' + req.sessionStore.user.name + '.  Click to <a href="/logout">logout</a>. ' + ' You may now access <a href="/restricted">the restricted section</a>.';
        res.redirect('home');
        console.log(req.sessionStore.user.username + ' logged in!');
      });
    } else {
      req.sessionStore.loginError = 'Authentication failed, please check your '
        + ' username and password.';
      res.redirect('back');
    }
  });
});

app.get('/register', function(req, res){
  res.render('register', {
    title: 'TileTabs Register'
  });
});

app.post('/register', function(req, res){
  var name = req.body.name;
  var username = req.body.username;
  var password = req.body.password;
  var salt = generateSalt();

  client.get('username:' + username + ':uid', function(err, reply){
    if (reply !== null){
      console.log(reply);
      req.sessionStore.registerError = 'Registration failed, ' + username + ' already taken.';
      res.redirect('back');
    }
    else{
      client.incr('global:nextUserId');
      client.get('global:nextUserId', function(err, reply){
        client.set('username:' + username + ':uid', reply);
        client.set('uid:' + reply + ':name', name);
        client.set('uid:' + reply + ':username', username);
        client.set('uid:' + reply + ':salt', salt);
        client.set('uid:' + reply + ':pass', hash(password, salt));
      });

      req.sessionStore.loginSuccess = 'Thanks for registering!  Try logging in!';
      console.log(username + ' has registered!');
      res.redirect('/login');
    }
  });
});

// Only listen on $ node app.js

if (!module.parent) {
  app.listen(80);
  console.log("Express server listening on port %d", app.address().port);
}

Registration works great. However, upon logging in with the correct user credentials, I am thrown the following error:

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: Can't set headers after they are sent.

I have managed to identify the line that throws this error (res.redirect('home');) in app.post('/login'). Just wondering, besides my poorly written code, what I need to do to fix this error.

UPDATE:

Versions:

node 0.4.10
express 2.4.3
npm 1.0.22
redis 2.4.0 rc5
connect 1.6.0
connect-redis 1.0.6

Here is the link to my app:

http://dl.dropbox.com/u/4873115/TileTabs.zip

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T04:27:14+00:00Added an answer on May 24, 2026 at 4:27 am

    Update

    The problem was authenticate(). Below I have I think correct implementation:

    function authenticate(username, pass, fn){
      client.get('username:' + username + ':uid', function (err, reply) {
        var uid = reply;
        client.get('uid:' + uid + ':pass', function(err, reply){
          var storedPass = reply;
          client.get('uid:' + uid + ':salt', function(err, reply){
            var storedSalt = reply;
            if (uid == null){
              fn(new Error('cannot find user'));
              return;
            } else  if (storedPass == hash(pass, storedSalt)) {
              client.get('uid:' + uid + ':name', function(err, reply){
                var name = reply;
                client.get('uid:' + uid + ':username', function(err, reply){
                  var username = reply;
                  var user = {
                    name: name,
                    username: username
                  }
                  fn(null, user);
                  return;
                });
              });
            } else {
                return fn(new Error('invalid password'));    
            }
          });
        });
      });
      //return fn(new Error('invalid password'));
    }
    

    I can’t run the example because I don’t have your stylus files. Can’t you archive your project and post it over here, so that we can also run your code. If my memory serves me right, you could have these problems when you combine old modules with new modules. Which versions of express, connect-redis, redis, connect, etc do you have installed??

    P.S: I can not run your code immediately if you upload, because I have to go to bed and have to work in the morning. But hopefully somebody else can help you then. Or maybe it is matter of modules installed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm making a simple page using Google Maps API 3. My first. One marker
I am trying to loop through a bunch of documents I have to put
I have a bunch of posts stored in text files formatted in yaml/textile (from
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have some data like this: 1 2 3 4 5 9 2 6
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.