How to authenticate the user with warden/devise in a customized way?-Collection of common programming errors
This is a Rails 3.0 app with Mongoid as ODM. Following is the user model in which the devise is installed.
class User
include Mongoid::Document
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
field :email
field :username
field :loginable_token
end
I’m building an API. So, for authentication I wanted to authenticate the users with :email and :password. From the GUI, its fine and working.
Now, I want to implement it via API, so I ve created a separate route /api_login.json
that hits the login
action with params {"username"=>"[email protected]", "password"=>"sachin", "action"=>"login", "controller"=>"api/v1/accounts", "format"=>"json"}
When I try to authenticate with the warden.authenticate!(:scope => :user)
method before sign_in
, it blows up with the following backtrace.
(rdb:1) l
[3, 12] in /Users/sts-151sts-151/Dev/cloudfactory/app/controllers/api/v1/accounts_controller.rb
3 respond_with(@current_account)
4 end
5
6 def login
7 debugger
=> 8 resource = warden.authenticate!(:scope => :user)
9 sign_in(:user, resource)
10 if user == nil
11
12 respond_with(User.account.apps.first)
(rdb:1) p params
{"username"=>"[email protected]", "password"=>"sachin", "action"=>"login", "controller"=>"api/v1/accounts", "format"=>"json"}
(rdb:1) rs = warden.authenticate!(:scope => :user)
*** Unknown command: "rs = warden.authenticate!(:scope => :user)". Try "help".
(rdb:1) p rs = warden.authenticate!(:scope => :user)
1) /api/v1/lines POST send back the default app
Failure/Error: last_response.status.should eql(200)
expected 200
got 401
(compared using eql?)
# ./spec/api/v1/accounts_spec.rb:46:in `block (3 levels) in '
The test is via default rack-test
way.
What is correct way to authenticate?
Originally posted 2013-11-09 21:10:28.