开发者

Rails authentication with custom fields

开发者 https://www.devze.com 2023-01-26 15:34 出处:网络
I have a rails app where I need to add authentication. The problem is that I have a legacy database with custom user and password fields (t_user and t_pass). Plus, t_pass is not encrypted.

I have a rails app where I need to add authentication. The problem is that I have a legacy database with custom user and password fields (t_user and t_pass). Plus, t_pass is not encrypted.

What I'm looking for is something like http_basic, but where I can have methods like current_user, and probably with a better user interface. I don't need validation, password reset, anything. Just a 开发者_如何学Goway to authenticate my way. I'd use restful_authentication but I'm on rails 3. I saw a fork that works with rails 3 but I was wondering if there is a better way to handle this situation?


It looks to me like you could probably do what you need using Devise and a bit of extra playing around. Specifically, you'll want to:

  • Make sure you create your user model table using your legacy auth table.
  • Override valid_password? on this model to check against your t_pass field.
  • Override self.find_for_database_authentication to find your model based on the t_user field.

If you want to support registration, you'll probably need to write a new encryption strategy as well.

Just a word of warning though: Storing passwords in plain text is very bad practice. If you have any choice at all, I'd seriously consider doing a migration of existing users into Devise's standard structure, with crypted passwords.


If you are looking for alternative gems to use then you can try Devise. You can extend/change the default settings to achieve what you want.


Devise and Authlogic are two potential options. Can't comment on Devise I'm afraid as I've never used it. Seems to be very popular at the moment though.

The following would get you started with Authlogic:

class User < ActiveRecord::Base
  acts_as_authentic do |config|
    config.login_field = :t_user
    config.crypted_password_field = :t_pass
    config.crypto_provider = YourCryptoProvider
  end
  ...
end

There's a railscast on the basics of getting authlogic going.

The difficult part of this is that you would need to create your own crypto provider class as described http://rdoc.info/github/binarylogic/authlogic/master/Authlogic/CryptoProviders as authlogic doesn't provide a plain text password check method.

As discussed above, look into migrating your passwords to encrypted versions if that's an option for you, it will stop you from fighting against the auth frameworks so much.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号