Roll Your Own Remember Me

October 11, 2009

I’ve been setting up Fluid Applications for a lot of the web applications I use frequently. This lets you run a web application in a lightweight browser, like it’s a native OS X application. Instead of having Gmail, Google Reader, Pivotal Tracker, and New Relic running in tabs in a browser I have them running as separate applications that I can switch between using the normal Cmd-Tab.

This has been working really well for me, until I hit one annoyance with New Relic. This web app doesn’t have a remember me feature. Its login cookies expire every time you close your browser session (as is the default in ruby on rails). This meant that every time I would pop it open I would have to re-enter my login credentials. Turns out I like to quit and reopen this application a lot, and was starting to get really irritated by having to retype my email and password to do a quick check of the production servers.

Luckily Fluid makes it really easy to include UserScripts, which allow you to inject custom javascript into web pages you’re viewing. Just create one in the “Scripts” menu, or add a javascript file at ~/Library/Application\ Support/Fluid/SSB/YourAppName/Userscripts/. Here’s one a threw together. Now I can quit and reopen my New Relic application and it remembers me across browser sessions. I haven’t had to enter my user credentials since.


// ==UserScript==
// @name        login
// @namespace   http://fluidapp.com
// @description This keeps you logged in to new relic across browser sessions
// @include     *
// @author      Sam Goldstein
// ==/UserScript==

(function () {
    if (window.fluid) {
      // Session cookie identifier
      var CookieName = '_newrelic_session_id'

      function LongTermCookie(cookieName) {

        // http://www.quirksmode.org/js/cookies.html#script
        function createCookie(name,value,days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else var expires = "";
            document.cookie = name+"="+value+expires+"; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name,"",-1);
        }

        // Set the cookie to expire in 3000 days
        createCookie(cookieName, readCookie(cookieName), 3000);
      }
    }
    new LongTermCookie(CookieName)
})();

I’ve pasted it into gist on github.