How can I simply verify that a username and password are correct with Devise and Rails 3
I am using Devise
and Rails 3
.
I want to call a function that will simply verify that a user's username
and password combination is correct without actually logging in that user. Is there some w开发者_JAVA技巧ay I can accomplish something like this with Devise:
User.authenticate(params[:username], params[:password])
Get the user out of the database:
user = User.find_by_email(params[:email])
Then you can check their password with:
user.valid_password?(params[:password])
Or using the one liner:
User.find_by_email(params[:email]).try(:valid_password?, params[:password])
which returns true
or nil
Official Devise Way
Devise has two built-in methods that let you do exactly this:
user = User.find_for_authentication(username: params[:username])
user.valid_password?(params[:password])
well, Devise makes it automatically: when user sumbits login information, then it makes that check for you.
if you want more control, then you have 2 choices:
1- look at Devise sources finding where it makes that check
2- write your own login system (it's not that hard as you can think)
精彩评论