Adam Singer
Adam Singer

Reputation: 2957

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 way I can accomplish something like this with Devise:

User.authenticate(params[:username], params[:password])

Upvotes: 37

Views: 16677

Answers (4)

Sheharyar
Sheharyar

Reputation: 75760

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])

Upvotes: 1

LiAh Sheep
LiAh Sheep

Reputation: 91

Or using the one liner:

User.find_by_email(params[:email]).try(:valid_password?, params[:password])

which returns true or nil

Upvotes: 4

Steven
Steven

Reputation: 4963

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])

Upvotes: 78

Andrea Pavoni
Andrea Pavoni

Reputation: 5311

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)

Upvotes: -9

Related Questions