Last Updated: February 25, 2016
·
795
· smallhadroncollider

Automatically login to a development environment with RequireJS

TL;DR: Setup an autologin.js file which is pulled in by your main config.js but added to .gitignore

If you're working on a front-end web app that authenticates with the API using OAuth you will probably want to set up some way of automatically logging in every time you reload the page (storing the access token in a cookie has potential security implications). However, storing login details in your main configuration file is a potential security risk - you may well forget to remove them before moving the code to production or accidentally push them to a public Git repository.

However, we can change our main configuration file to pull in an autologin.js file, which contains the login details, and then add this file to .gitignore to make sure it never leaves your computer.

.gitignore

# never commit the autologin.js file
autologin.js

autologin.js

define({
    username: 'admin',
    password: '1234' // super secure
});

config.js

define(['autologin'], function (autoLogin) {
    'use strict';

    return {
        environment: 'development',

        // Auto-login details
        autoLogin: autoLogin
    };
});

You now have access to config.autoLogin anywhere in your RequireJS application, but you don't have to worry about the file making its way online.

r.js Optimisation

In your r.js build file you should include the stubModules: ['autologin'] option. This will set autoLogin to be an empty object (make sure your code won't throw an error if it is passed an empty object).