Skip to content

node.js and authentication

January 2, 2012

So – after creating a first node.js app with express templates and adding database access to the node.js tagsobe hotel travel solution, we need authentication.

Call me greenhorn – I have not been able to find a concise tutorial on adding simple form-based authentication to a node.js/express/sequelize setup. So here it is, and it actually is simple (hmmm – that might be a reason… ;-)):

Setup: We want to be catched if /booking is called with no one logged in. A Login form should be displayed, and when credentials are correct, the /booking URL should be called.

First, for the code below to work, you must use two modules:

  app.use(express.cookieParser());
  app.use(express.session({ secret: "type some fancy code here" }));

Now we start be securing /booking with an express-styled routing chain called loggedIn:

app.get('/booking', loggedIn, function(req, res){
  // Actually render the booking form
});

LoggedIn is as simple as:

function loggedIn(req, res, next) {
	req.session.user!=null
	    ? next()
	    : res.redirect("/login?url="+req.url);
}

So, it redirects to /login, providing the requested URL (/booking in our case), which simply renders a login form:

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

The login form can be very simple, I include it here in Jade for completeness:

form(name="f",action="../authenticate",method="post")
 input(type="hidden",name="url",id="url",value="#{url}")
   fieldset
    legend Login Information
     p
      label(for="username") User:
      input(type="text",name="username",id="username")
     p
      label(for="password") Password:
      input(type="password",name="password",id="password")
     p
      button(id="submit",type="submit") Login

Obviously, we now need an /authenticate POST target – this is where sequelize is used to get Users from the database:

app.post('/authenticate', function(req, res){
	var query = Customer.find({ where: {username: req.param("username")} });
	query.on("success", function(user) {
		if (user!=null && user.password==req.param("password") {
			req.session.user = user.username;
			res.redirect(req.param("url"));
		}
	})
});

In success case, the session is populated and the user is redirected to the originally requested URL.

Of course, this is only a rudimentary solution – credentials should be encrypted, error handling added and so on… But it should give you some first advise. Code is here: https://github.com/joergviola/tagsobe-nodejs
Advertisements

From → node.js

One Comment

Trackbacks & Pingbacks

  1. node.js and databases « tagsobe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: