0

Does anybody know a good way to separate out a controller item into a separate file? I have the following in of my controller.

def admin?
    session[:password] == "password"
end

But I'd like to separate the "password" into a separate file so I can ignore it from a public git repo?

Is there an easy way to do this? Without storing this in a database?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
calabi
  • 283
  • 5
  • 18
  • I don't have much time to deeply explain why you're doing it wrong, but your approach seems *completely* wrong. first, the `admin?` should be tied to a model so you could do `user.admin?` instead of checking the sessions, then the password should NEVER be stored in the session, and finally , you should NEVER hardcode a password in a file. – pjam Feb 06 '13 at 09:38
  • you should read that : http://guides.rubyonrails.org/security.html#session-guidelines – pjam Feb 06 '13 at 09:41
  • Thanks @pjam, I think I will look into implementing a user model. – calabi Feb 06 '13 at 15:00

3 Answers3

1

you can try to use ENV variables. first set the environment variable to a value.

export MYAPPPASSWORD=1234

then use this in an initializer

# config/initializers/my_app_password.rb
ENV['MYAPPPASSWORD'] = `printf "%s" $MYAPPPASSWORD`

then you can just call ENV['MYAPPPASSWORD']

jvnill
  • 29,479
  • 4
  • 83
  • 86
  • Thanks this is useful, after reading some of the other comments, I think I'm going to implement a users model. – calabi Feb 06 '13 at 15:00
0

Although its a bad practice to store password in session and use it in this way. But still, if you have specific reasons to do it this way then you can store in a yml file under your config directory or anywhere. I am giving the example under config directory:

in your /config/passwords.yml

password: your_password_text_here_without_quotes

and in your controller/model/anywhere load the file and get the password.

password = YAML.load_file("#{Rails.root}/config/passwords.yml")["password"]
Manoj Monga
  • 3,033
  • 14
  • 19
0

You could use a global constant to deal with these settings. Define for example a yml file in the config directory:

#config/password.yml
password: MyPassword

Use an initializer to load your settings on system start. Something like:

#config/initializers/load_password.rb
conf_file = File.join(Rails.root, 'config', 'password.yml')
MY_CONFIG = OpenStruct.new YAML.load_file(conf_file)

Access this in your whole project with:

MY_CONFIG.password

But you should not use this approach for dealing with the password in that way. For a simple authentication look for example for this basic authentication

Lars Schirrmeister
  • 2,215
  • 1
  • 22
  • 23