Module: DeviseTokenAuth::Controllers::Helpers

Extended by:
ActiveSupport::Concern
Included in:
DeviseTokenAuth::Concerns::ResourceFinder
Defined in:
lib/devise_token_auth/controllers/helpers.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.define_helpers(mapping) ⇒ Object

Define authentication filters and accessor helpers based on mappings. These filters should be used inside the controllers as before_actions, so you can control the scope of the user who should be signed in to access that specific controller/action. Example:

Roles:
  User
  Admin

Generated methods:
  authenticate_user!                   # Signs user in or 401
  authenticate_admin!                  # Signs admin in or 401
  user_signed_in?                      # Checks whether there is a user signed in or not
  admin_signed_in?                     # Checks whether there is an admin signed in or not
  current_user                         # Current signed in user
  current_admin                        # Current signed in admin
  user_session                         # Session data available only to the user scope
  admin_session                        # Session data available only to the admin scope
  render_authenticate_error            # Render error unless user or admin is signed in

Use:
  before_action :authenticate_user!  # Tell devise to use :user map
  before_action :authenticate_admin! # Tell devise to use :admin map


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/devise_token_auth/controllers/helpers.rb', line 115

def self.define_helpers(mapping) #:nodoc:
  mapping = mapping.name

  class_eval <<-METHODS, __FILE__, __LINE__ + 1
    def authenticate_#{mapping}!(opts={})
      unless current_#{mapping}
        render_authenticate_error
      end
    end

    def #{mapping}_signed_in?
      !!current_#{mapping}
    end

    def current_#{mapping}
      @current_#{mapping} ||= set_user_by_token(:#{mapping})
    end

    def #{mapping}_session
      current_#{mapping} && warden.session(:#{mapping})
    end

    def render_authenticate_error
      return render json: {
        errors: [I18n.t('devise.failure.unauthenticated')]
      }, status: 401
    end
  METHODS

  ActiveSupport.on_load(:action_controller) do
    if respond_to?(:helper_method)
      helper_method(
        "current_#{mapping}",
        "#{mapping}_signed_in?",
        "#{mapping}_session",
        'render_authenticate_error'
      )
    end
  end
end