Search code examples
rubysecuritytwitterserverdirectory-structure

Where to put API keys for Twitter app on server


I'm currently writing a couple Twitter bots for my friends using the Twitter gem for Ruby. My plan was to store the keys for them in a .txt file with the rest of the bot's code on my server, but everything I've read has said the keys shouldn't be readable within the code. Is this secure enough, and if not what would be a good solution? Thanks!


Solution

  • A common approach is to save the environment variables into a file called .env that is ignored by version control (and therefore won't be included on Github) but read by the code. One gem to help with this is dotenv.

    1. add .env to the .gitignore file.
    2. create a local .env file with all your env vars
    3. require 'dotenv' and put Dotenv.load somewhere at the beginning of your script. In Rails, the require is unnecessary and you can place the load call in any file in the config/initializers folder
    4. Check that your app works fine locally. The environment variables should be found in the ENV hash from Ruby code.
    5. Save changes and push new version of app to digital ocean
    6. manually create the .env file on the digital ocean server, in the root of the repo
    7. run digital ocean server and check that everything works.

    other notes:

    • see How To Read and Set Environmental and Shell Variables on a Linux VPS

    • some platforms like heroku have a different mechanism for setting environment variables, such as heroku config:set or web UIs.

    • You can set environment variables on a one-off basis using the env command in bash, for example:

      env a=hello b=' world' ruby -e 'puts ENV["a"] + ENV["b"]'
      # => hello world
      

      This can give a quick way to configure a program without getting into argument parsing. For example in Rails, you can say rails c test to open a console using the test environment, but env RAILS_ENV=test rails c should do the same thing.