Using config/secrets.yml in Rails 4.0.2 version - ruby-on-rails

I was reading http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html
and saw there the trick with config/secrets.yml
I moved my secret_base_keys to that file, and removed secret_token.rb file.
But server doesn't start.
DEPRECATION WARNING: You didn't set config.secret_key_base. Read the upgrade documentation to learn more about this new config option. (called from service at /home/bismailov/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/1.9.1/webrick/httpserver.rb:138)
[2014-01-15 16:15:51] ERROR RuntimeError: You must set config.secret_key_base in your app's config.
I believe that is because I don't use Rails 4.1 yet.
Is there any way to implement this new functionality (secrets.yml) in Rails version 4.0? Maybe some kind of gem...
Thank you very much!

This secret_key_base deprecation does not seem to have alternative syntax to remove the deprecation warning in a Rails 4.0 application. To satisfy the deprecation, follow the steps for moving the production key to secrets.yml and delete the secret_token.rb file. The implement a YAML loader in your application.rb to extract the token from your secrets.yml file.
Use rake secret to generate a new token for each of your environments. Copy and paste the output to each section of your secrets.yml file.
# config/secrets.yml
development:
secret_key_base: __pasted from rake secret___
test:
secret_key_base: __pasted from rake secret___
production:
secret_key_base: __pasted token from config/initializers/secret_token.rb___
# config/application.rb
# TODO Remove this in Rails 4.1
config.secret_key_base = YAML.load(File.open("#{Rails.root}/config/secrets.yml"))[Rails.env]['secret_key_base']
Cite: https://github.com/rails/rails/pull/13298
UPDATE:
My original post focused on Inspired by #user2998870, I added a method to my application.rb that is allows one to implement multiple secrets, not just secret_key_base. This makes top-level keys accessible as methods e.g. Rails.application.secrets.braintree_merchant_id.
If nested, one can call the nested key value using Rails.application.secrets.braintree['merchant_key'].
Note: The original code above is still needed for secret_key_base to operate correctly in Rails 4.0.
# config/application.rb
def secrets
#secrets ||= begin
yaml = YAML.load(File.open("#{Rails.root}/config/secrets.yml"))[Rails.env]
ActiveSupport::OrderedOptions.new.merge!(yaml.symbolize_keys)
end
end

config/secrets.yml is a feature of Rails 4.1. Upgrade to Rails 4.1 to use the feature.

I did like #scarver2 mentioned, but I did it by borrowing some code from Rails 4.1 (I'm currently using on 4.0.3)
# Load 3rd party service passwords from config/services.rb.
# This is patch code to support config/services.rb till we upgrade to Rails 4.1.
# TODO: Remove this section after upgrading to Rails 4.1.
# Borrowed from rails/railties/lib/rails/application/configuration.rb
config.paths.add "config/secrets", with: "config/secrets.yml"
# Borrowed from rails/railties/lib/rails/application.rb
def secrets #:nodoc:
#secrets ||= begin
secrets = ActiveSupport::OrderedOptions.new
yaml = config.paths["config/secrets"].first
if File.exist?(yaml)
require "erb"
all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {}
env_secrets = all_secrets[Rails.env]
secrets.merge!(env_secrets.symbolize_keys) if env_secrets
end
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
secrets.secret_key_base ||= config.secret_key_base
secrets
end
end

Related

Cannot understand rails deprecation warning for secret_token

After upgrading from rails 5.1 to rails 5.2.3 I am getting this deprecation warning:
secrets.secret_token` is deprecated in favor of `secret_key_base` and will be removed in Rails 6.0. (called from <main> at /config/initializers/stripe.rb:3
If I look at the stripe initializer, I have:
Rails.configuration.stripe = {
publishable_key: Rails.application.secrets.stripe_publishable_key,
secret_key: Rails.application.secrets.stripe_secret_key
}
so there is no mention of secret.token. If I look at config.secrets.yml I have
test:
secret_key_base: some-key
stripe_secret_key: another_key
stripe_publishable_key: yet_another_key
So why am I getting the deprecation warning?
Rails 5.2 has replaced secrets with credentials to store encrypted credentials or API keys in the repository. You can read more about the changing from secrets to credentials in the following article.
https://medium.com/#wintermeyer/goodbye-secrets-welcome-credentials-f4709d9f4698
Even though Rails 5.2 has replaced secrets with credentials, you can still use secrets if you wish to. However as the warning message states, secrets will be removed from Rails 6 and you have to embrace in using credentials for storing API keys and secret_keys.

Set SECRET_KEY_BASE in production using a .env file

I've a .env file in my root folder in production. This file defines SECRET_KEY_BASE which is used in config/secrets.yml. The problem is that I can't manage to load my .env file before my config/secrets.yml. I've tried using the dotenv gem without success.
Any idea on how todo this in production?
I don't want to set it globally for my webmaster user on the production server. The SECRET_KEY_BASE value should only be accessable for by application.
I'm using rails 4.1.
I too use dotenv gem. It works for me in almost all case.
This is my configuration of dotenv gem (yes, i put dotenv in Gemfile). I just create an aaaaa.rb initializer file.
config/initializers/aaaaaa.rb
#obscure name because rails load initializers/* files based on alphabets
require 'dotenv'
Dotenv.load
And, cases which it doesn't, i do this this finally in config/boot.rb file
ENV["SECRET_KEY_BASE"] = "foobar"
I was also having this problem. Here is how I got it to work. I followed documentation to initialize dotenv early:
# config/application.rb
Bundler.require(*Rails.groups)
Dotenv::Railtie.load
HOSTNAME = ENV['HOSTNAME']
But then I came across this error (issue #155):
gems/dotenv-rails-1.0.2/lib/dotenv/rails.rb:17:in `load': undefined method `join' for nil:NilClass (NoMethodError)
The workaround (also documented in issue #155) is to replace Dotenv::Railtie.load with:
Dotenv.load(File.expand_path("../../.env.#{Rails.env}", __FILE__))
Apparently this is only a problem when using rails 4.1.
Was also having this problem, but manage to get it to work by having this in my secrets.yml file:
production:
secret_key_base: ENV["SECRET_KEY_BASE"]
It worked after removing the <%= %>

Error with Oauth token not redirect

Basically, I can't find my production ID and my production API secret. I can only find the developer ones. Am I supposed to submit for review first? My OAuth is all set up.
I also have my YML So do I submit first and I will get this second ID? This has been my problem all day long. Thanks.
It looks like this:
Development:
facebook_api_key:
facebook_api_secret:
Production:
facebook_api_key:
facebook_api_secret:
I tried adding my ID and secret for both of them even though it was only on dev! Please help me!
Actually, your problem has nothing to do with oauth. It is about how to setup secret variables between different environments.
I use figaro gem to handle this kind of variables:
First, add figaro in your Gemfile.
Gemfile
gem 'figaro'
Setup variables in config/applicaiton.yml. (I usually use UPPER CASE for these variables)
config/application.yml
development:
FB_KEY: your_fb_key_for_development
FB_SECRET: your_fb_secret_for_development
production:
FB_KEY: your_fb_key_for_production
FB_SECRET: your_fb_secret_for_production
And use ENV to get variables where you want,
config/initializers/devise.rb
Devise.setup do |config|
# ...
# Onmi configurations
require "omniauth-facebook"
config.omniauth :facebook, ENV['FB_KEY'], ENV['FB_SECRET']
# ...
end
If you want to do it without any gem, please see:
stackoverflow - Setting Environment Variables in Rails 3 (Devise + Omniauth)

Rails Devise Gem

Am using rails 3.2.6 , ruby 1.8.7
I want add devise authentication in application..
I do following below mentioned in my app..
gem 'devise' add in Gemfile
after rails g devise:install in cmd prompt.
Add this line in developement.rb
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
Add this line in config/application.rb
config.assets.initialize_on_precompile = false
Finally, I run this cmd rails g devise user.
I got this error.
SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
This poses a security threat. It is strongly recommended that you
provide a secret to prevent exploits that may be possible from crafted
cookies. This will not be supported in future versions of Rack, and
future versions will even invalidate your existing user cookies.
If you know answer for this error. please let me know..
You need to generate application token. It can be simply done by running:
rake secret
And add to config/initializers/secret_token.rb
AppName::Application.config.secret_token = 'CODE_HERE'
EDIT: Thanks #Nick

Remove ActiveRecord in Rails 3

Now that Rails 3 beta is out, I thought I'd have a look at rewriting an app I have just started work on in Rails 3 beta, both to get a feel for it and get a bit of a head-start. The app uses MongoDB and MongoMapper for all of its models and therefore has no need for ActiveRecord. In the previous version, I am unloading activerecord in the following way:
config.frameworks -= [ :active_record ] # inside environment.rb
In the latest version this does not work - it just throws an error:
/Library/Ruby/Gems/1.8/gems/railties-3.0.0.beta/lib/rails/configuration.rb:126:in
`frameworks': config.frameworks in no longer supported. See the generated
config/boot.rb for steps on how to limit the frameworks that will be loaded
(RuntimeError)
from *snip*
Of course, I have looked at the boot.rb as it suggested, but as far as I can see, there is no clue here as to how I might go about unloading AR. The reason I need to do this is because not only is it silly to be loading something I don't want, but it is complaining about its inability to make a DB connection even when I try to run a generator for a controller. This is because I've wiped database.yml and replaced it with connection details for MongoDB in order to use this gist for using database.yml for MongoDB connection details. Not sure why it needs to be able to initiate a DB connection at all just to generate a controller anyway....
Is anyone aware of the correct Rails 3 way of doing this?
I'm going by this from reading the source, so let me know if it actually worked. :)
The rails command that generates the application template now has an option -O, which tells it to skip ActiveRecord.
If you don't feel like rerunning rails, you should check the following in your existing app:
Check that your config/application.rb doesn't have require 'rails/all' or require "active_record/railtie". Instead, for a standard Rails setup without ActiveRecord, it should have only the following requires:
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
# Auto-require default libraries and those for the current Rails environment.
Bundler.require :default, Rails.env
If, in config/application.rb, you are using the config.generators section, make sure it doesn't have the line g.orm :active_record. You can set this explicitly to nil, if you want, but this should be the default when g.orm is completely omitted.
Optional, but in your Gemfile, remove the gem line that loads the module for your database. This could be the line gem "mysql" for example.
Rails 4
I was looking for how to disable it in rails 4 and only found this answer which no longer works in rails 4. So this is how you can do it in rails 4 (tested in RC1).
In a new project
rails new YourProject --skip-active-record
In an existing project
In your Gemfile, remove the database driver gem, e.g. gem 'sqlite3' or gem 'pg'.
In config/application.rb, replace require 'rails/all' with
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
In config/environments/development.rb, remove or comment out config.active_record.migration_error = :page_load
Potentially you have to remove active_record helpers from the spec_helper (via VenoM in the comments)
Potentially you have to remove the ConnectionManagement middleware (seems to be the case with unicorn): config.app_middleware.delete "ActiveRecord::ConnectionAdapters::ConnectionManagement" (via https://stackoverflow.com/a/18087332/764342)
I hope this helps others looking for how to disable ActiveRecord in Rails 4.
For a new rails app, you can have it exclude active record by specifying the --skip-active-record parameter. Eg:
rails new appname --skip-active-record
If you generated a new project using Rails 3.2, you will also need to comment out:
config.active_record.mass_assignment_sanitizer = :strict
and
config.active_record.auto_explain_threshold_in_seconds = 0.5
in your development.rb file.
All of the above are true. The one more thing which I had to do in rails 3.1 is to comment out
config.active_record.identity_map = true
in config/application.rb.
If you're running rspec, you also need to remove (in spec_helper):
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
and remove
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
Also comment out
# config/application.rb
config.active_record.whitelist_attributes = true
(noted on rails 3.2.13)

Resources