Tuesday, May 29, 2012

My Developers Life - The Importance of Sleep

When I was reading Just for Fun, I came across this paragraph in the book where Linus Torvalds stated that he never missed a good night’s sleep during the early days when he was hacking together the first version of the Linux kernel. In fact, he clearly stated in his book that he doesn’t allow his pet project to come between him and a minimum of eight hours of sleep each night.

Let’s think about this for a moment.

Here’s this guy who wrote an insane amount of complex code without pulling all night death marches. After I read that passage, I couldn’t help but reflect on my own behavior. I’ve been working on countless little pet projects over the past couple of years, often churning out code until 3 or 4 o’clock in the morning during the weekends or holidays. This made me realize that I needed to do something about it. And you know what the stupid part was? I had the right habits all along! 

Those who know me know that I start my working days quite early. I usually arrive at the office around 7 o’clock in the morning, getting a fresh and quiet head start of my day. This implies that I go to sleep very early as well on working days, trying to get as much sleep as I possibly can every night.

So, now that I realized that I already had the right behaviors in place, the only thing that I needed to do was to extend this behavior to the weekends and holidays. And I must say that it works great! I instantly stopped hacking on code during the night and now I go to sleep early every day. I also get up early every single day which makes me feel more productive, more efficient and definitely more focused. After doing this for a couple of weeks, I could only come to the conclusion that I felt much better overall.

However, I’m still not entirely there yet. There are some nights that I don’t get to have a full eight hours of sleep, mostly on working days. This is something that I still need to work on, so I create the right habits in order to achieve this goal. 

No more sleep deprivation for me. Everyone knows that working more than 8 hours a day is madness. Well, the same goes for writing code after midnight. I came to realize that a good night’s sleep is probably one of the most important tools you have as a developer. A well rested brain is more useful than a tired and a sleepy one.

I encourage you to try this for two weeks and reflect on your mood, productivity and your general well being.

Until next time and good night!

Tuesday, May 15, 2012

Taking Toddler Steps with Node.js – Passport

Recently I added Twitter authentication to TrackMyRun using a library called Passport. I was pretty impressed how smooth this all went as I completely neglected all security concerns from the get go, which is definitely not recommended by the way. For this post I’ll walk you through the process of setting up Passport for Express using Twitter OAuth authentication.

Passport is actually the core library which provides support for OpenId and OAuth authentication. Instead of being one single monolithic library, Passport uses strategies that support authentication directly with specific OpenId/OAuth providers.

So in order to get up and running, we need to install passport as well as passport-twitter for Twitter OAuth authentication. After we install these modules using npm, we can start by configuring the Twitter strategy.

var express = require('express'),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter').Strategy;

var users = [];

passport.use(new TwitterStrategy({
        consumerKey: 'twitter-app-consumer-key',
        consumerSecret: 'twitter-app-consumer-secret',
        callbackURL: "http://test.passport-twitter.com:3000/auth/twitter/callback"
    function(token, tokenSecret, profile, done) {
        var user = users[profile.id] || 
                   (users[profile.id] = { id: profile.id, name: profile.username });
        done(null, user);

The strategy must be configured by providing the consumer key and consumer secret as well as the callback URL. I’m not going too much in depth on how OAuth works. Make sure to check out the Twitter for developers website on how to configure an application that uses the Twitter API.

Besides adding the strategy for Twitter, we also specified a callback function. In this callback, we’re supposed to find and verify a user that matches a specified set of credentials. Usually we have some code here that checks to see if the specified user exists in a database of some sort. In order not to clutter this example, I used a simple array here instead.

If we can find the requested user in our data store, we need to invoke done() to supply the Passport with the user.

done(null, user);

When the user cannot be found, we can simply pass false instead of a user object.

done(null, false);

In our example we always ensure that the specified credentials match a particular user object. Next we need to configure the Passport middleware for initialization and session management.

application.configure(function() {
    application.use(express.session( { secret: '498f99f3bbee4ae3a075eada02488464' } ));
    application.use(express.errorHandler({ showStack: true, dumpExceptions: true }));
    application.set('view engine', 'jade');

Please note that the express.session() middleware needs be called before passport.session(). Next we add the routes necessary for authenticating requests and handling the token callback.

application.get('/auth/twitter', passport.authenticate('twitter'));

        { successRedirect: '/', 
          failureRedirect: '/auth/twitter' }));

Last but not least we also need to declare a serializeUser/deserializeUser callback function. These are necessary for supporting login sessions.

passport.serializeUser(function(user, done) {
    done(null, user.id);

passport.deserializeUser(function(id, done) {
    var user = users[id];
    done(null, user);

Instead of reading the requested user objects from the data store, we simply use the array that we incorporated earlier.

That’s basically the thing. We can add other authentication providers by simply configuring more strategies. Have a look at the full source code of this example and try to get it up and running.

Until next time.