Tuesday, March 22, 2016

Figaro gem and security

According to a friend programmer, Github changed our lives.

While back in the 90's we were all worried about protecting our code, now publishing code is the new rule.

But it is not so simple. Some code must be kept secret, even in these days of Github supremacy. I am talking about code exposing private information, like usernames and passwords. Of course you may always add this to your .gitignore file, but there are still some questions to consider, like deployment.

Figaro gem (GitHub and RubyGems) is an easy way to solve all these problems. Using it is easy as pie (I really don't understand this expression, since making a good pie is no easy task!)

First of all, add

gem 'figaro'

to your Gemfile and run

$ bundle install

Then you are ready to install Figaro, by running

$ bundle exec figaro install

This command will, essentially, create a file named config/application.yml and append the name of this file to your .gitignore file. This is necessary because this file will store your private information.

This config.application.yml file must now be edited. An example of how it should look like is here:

SOME_API_KEY: 'some_api_key_you_use'


GMAIL_USERNAME: 'your_gmail_username_for_test@gmail.com'
GMAIL_PASSWORD: 'your_gmail_password_for_test'


GMAIL_USERNAME: 'your_gmail_username_for_dev@gmail.com'
GMAIL_PASSWORD: 'your_gmail_password_for_dev'


GMAIL_USERNAME: 'your_gmail_username_for_prod@gmail.com'
GMAIL_PASSWORD: 'your_gmail_password_for_prod'

Explaining a bit, we have four sections here. First one is the global section, where we have only  one key, SOME_API_KEY. This key is not in test:, development: or production:, so it will be taken as global and used for all three environments.

The second section is test:, where we have GMAIL_USERNAME and GMAIL_PASSWORD for using in tests. The same keys are repeated in development: and production:, but with different values. Figaro gem will recognize this fact and use the correct keys for the environment you are using.

But... how to recover these values in your application?

Easy again!

You just need to use, for instance, ENV['SOME_API_KEY'], or ENV['GMAIL_USERNAME'], or ENV['GMAIL_PASSWORD'] in your models, controllers or views. Because thats what Figaro gem does. It parses the YAML file config/application.yml and stores the correct keys and values in your environment variables.