1
votes

I am working on a rails application which has a both a website and an api(which will be consumed by my android app).

I have created separate controllers under controllers/api directory to handle all the api controllers code, the controllers to handle website are directly under controllers folder

I am using Devise for authentication in my website and now I want to extend the devise authentication system so that it can support both api and web authentication at the same time i.e a person can login/signup using the same credentials from web and from api.

I am using simple_token_authentication gem to enable token authentication with devise.

I am following this blog post to implement token based authentication for devise -: http://provoost.tumblr.com/post/80873086965/json-api-authentication-using-devise-tokens

The code for my routes file is

 Rails.application.routes.draw do
  resources :products
  devise_for :users
  root 'products#index'

  namespace :api do
   devise_for :users, :controllers => {registrations: "api/registrations", sessions: "api/sessions"}
  end

end

I added this line in my devise.rb file:

config.navigational_formats = ['*/*', :html, :json]

I created sessions controller and registrations controller under controller/api directory

Code for sessions controller

   class API::SessionsController < Devise::SessionsController

   def create
    self.resource = warden.authenticate!(auth_options)
    sign_in(resource_name, resource)

    current_user.update authentication_token: nil

    respond_to do |format|
     format.json {
     render :json => {
       :user => current_user,
       :status => :ok,
       :authentication_token => current_user.authentication_token
      }
     }
   end
   end

   # DELETE /resource/sign_out
   def destroy

     respond_to do |format|
     format.json {
       if current_user
        current_user.update authentication_token: nil
        signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
        render :json => {}.to_json, :status => :ok
       else
        render :json => {}.to_json, :status => :unprocessable_entity
       end


       }
     end
    end
   end 

Code for registrations controller:

        class API::RegistrationsController < Devise::RegistrationsController

          def create
            @user = User.create(user_params)
            if @user.save
              render :json => {:state => {:code => 0}, :data => @user }
            else
              render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
            end

          end

          private

          def user_params
            params.require(:user).permit(:email, :password)
          end
        end            class API::RegistrationsController < Devise::RegistrationsController

          def create
            @user = User.create(user_params)
            if @user.save
              render :json => {:state => {:code => 0}, :data => @user }
            else
              render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
            end

          end

          private

          def user_params
            params.require(:user).permit(:email, :password)
          end
        end 

Also, for test purpose I disabled the csrf tags

Now, I am trying to send the following requests from curl

1) Sign_up

 curl -H 'Content-Type: application/json'   -H 'Accept: application/json' -X POST http://localhost:3000/api/users.json   -d '{"user": {"email": "[email protected]", "password": "12345678"}}'

This request is working fine and is creating the new user

2) Sign_in

curl -H 'Content-Type: application/json'   -H 'Accept: application/json' -X POST http://localhost:3000/api/users/sign_in   -d '{"user": {"email": "[email protected]", "password": "12345678"}}'

When I am trying to sign_up using this request, it is throwing the following error:

    Started POST "/api/users/sign_in" for 127.0.0.1 at 2015-08-17 17:48:52 +0530
    Processing by API::SessionsController#create as JSON
      Parameters: {"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}}
    Completed 401 Unauthorized in 2ms (ActiveRecord: 0.0ms)
    Processing by API::SessionsController#new as JSON
      Parameters: {"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}}
    Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)

    NoMethodError (undefined method `users_url' for #<API::SessionsController:0x007ff4ca92ad80>):
      actionpack (4.2.3) lib/action_dispatch/routing/polymorphic_routes.rb:220:in `polymorphic_method'
      actionpack (4.2.3) lib/action_dispatch/routing/polymorphic_routes.rb:114:in `polymorphic_url'
      actionpack (4.2.3) lib/action_dispatch/routing/url_for.rb:163:in `url_for'
      actionpack (4.2.3) lib/action_controller/metal/rendering.rb:95:in `_process_options'
      actionpack (4.2.3) lib/action_controller/metal/streaming.rb:200:in `_process_options'
      actionpack (4.2.3) lib/action_controller/metal/renderers.rb:43:in `block in _render_to_body_with_renderer'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/set.rb:283:in `each_key'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/set.rb:283:in `each'
      actionpack (4.2.3) lib/action_controller/metal/renderers.rb:41:in `_render_to_body_with_renderer'
      actionpack (4.2.3) lib/action_controller/metal/renderers.rb:37:in `render_to_body'
      actionpack (4.2.3) lib/abstract_controller/rendering.rb:25:in `render'
      actionpack (4.2.3) lib/action_controller/metal/rendering.rb:16:in `render'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
      activesupport (4.2.3) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
      activesupport (4.2.3) lib/active_support/core_ext/benchmark.rb:12:in `ms'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
      activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:43:in `render'
      responders (2.1.0) lib/action_controller/responder.rb:258:in `display'
      responders (2.1.0) lib/action_controller/responder.rb:214:in `api_behavior'
      responders (2.1.0) lib/action_controller/responder.rb:191:in `rescue in to_format'
      responders (2.1.0) lib/action_controller/responder.rb:185:in `to_format'
      responders (2.1.0) lib/action_controller/responder.rb:163:in `respond'
      responders (2.1.0) lib/action_controller/responder.rb:156:in `call'
      responders (2.1.0) lib/action_controller/respond_with.rb:203:in `respond_with'
      devise (3.5.2) app/controllers/devise/sessions_controller.rb:12:in `new'
      actionpack (4.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
      actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/rendering.rb:10:in `process_action'
      actionpack (4.2.3) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
      activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:553:in `block (2 levels) in compile'
      activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:88:in `run_callbacks'
      actionpack (4.2.3) lib/abstract_controller/callbacks.rb:19:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/rescue.rb:29:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
      activesupport (4.2.3) lib/active_support/notifications.rb:164:in `block in instrument'
      activesupport (4.2.3) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
      activesupport (4.2.3) lib/active_support/notifications.rb:164:in `instrument'
      actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
      actionpack (4.2.3) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
      activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
      actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process'
      actionview (4.2.3) lib/action_view/rendering.rb:30:in `process'
      actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action'
      devise (3.5.2) lib/devise/failure_app.rb:53:in `call'
      devise (3.5.2) lib/devise/failure_app.rb:53:in `recall'
      devise (3.5.2) lib/devise/failure_app.rb:37:in `respond'
      actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action'
      actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process'
      actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
      actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action'
      devise (3.5.2) lib/devise/failure_app.rb:22:in `call'
      devise (3.5.2) lib/devise/failure_app.rb:22:in `call'
      devise (3.5.2) lib/devise/delegator.rb:5:in `call'
      warden (1.2.3) lib/warden/manager.rb:130:in `call_failure_app'
      warden (1.2.3) lib/warden/manager.rb:116:in `process_unauthenticated'
      warden (1.2.3) lib/warden/manager.rb:47:in `call'
      rack (1.6.4) lib/rack/etag.rb:24:in `call'
      rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
      rack (1.6.4) lib/rack/head.rb:13:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call'
      rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
      rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call'
      activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call'
      activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
      activerecord (4.2.3) lib/active_record/migration.rb:377:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
      activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks'
      actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
      web-console (2.2.1) lib/web_console/middleware.rb:39:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
      railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app'
      railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call'
      activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged'
      activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged'
      activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged'
      railties (4.2.3) lib/rails/rack/logger.rb:20:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call'
      rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
      rack (1.6.4) lib/rack/runtime.rb:18:in `call'
      activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
      rack (1.6.4) lib/rack/lock.rb:17:in `call'
      actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call'
      rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
      railties (4.2.3) lib/rails/engine.rb:518:in `call'
      railties (4.2.3) lib/rails/application.rb:165:in `call'
      rack (1.6.4) lib/rack/lock.rb:17:in `call'
      rack (1.6.4) lib/rack/content_length.rb:15:in `call'
      rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
      /home/lovish/.rbenv/versions/2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'


      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.1ms)
      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.5ms)
      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.4ms)
      Rendered /home/lovish/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (34.6ms)
    Cannot render console with content type application/jsonAllowed content types: [#<Mime::Type:0x007ff4d7750b10 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x007ff4d77507f0 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x007ff4d7748488 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]

The complete code is also available at https://github.com/lovishchoudhary/devisetest

Can anybody please help me figure out what error I am doing ?

1

1 Answers

1
votes

@Lovish Choudhary I found you sent request for sign up with

http://localhost:3000/api/users/sign_in URL.

But you defined that your registration route with api/registrations

Problem occurred as you have multiple devise routeing in your route file.