Search code examples
ruby-on-railsdevisedevise-token-auth

Override SessionsController to refuse access based on user attribute


I have a rails 4 project, where I'm using DeviseTokenAuth. Everything works fine, but I'd like to refuse access to user with a specific status. So basically

if user.status == :locked => Account :unauthorized

So this is what I've done so far

class SessionsController < DeviseTokenAuth::SessionsController
   def new
      super
   end

   def create
      super
      render json: { error: "Account is locked MOFO " }, status: :unauthorized if current_user.status.to_sym == :locked    
    end
end

But when I do that I get :

AbstractController::DoubleRenderError - Render and/or redirect were called multiple times in this action. Please notethat you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".:

Any idea ?

thanks


Solution

  • This error happens because double render methods are called from sessions controller create method. One option is to override render_create_success method to get the desired result.

    class SessionsController < DeviseTokenAuth::SessionsController
    
       protected
    
       def render_create_success
        if current_user.status.to_sym == :locked
          render json: { error: "Account is locked MOFO " }, status: :unauthorized
        else
          super
        end
      end
    end