Sha256: 068f32d2f062d18cb708def757d7cac93e5f3cd58a76baa2cc424f0e1569f05c

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

module Touth
  module ActionControllerSupport

    module ClassMethods

      mattr_accessor :token_authentication_on

      def token_authentication_for(scope)
        name = scope.to_s

        self.token_authentication_on = {
          model_class: name.camelize.constantize,
          current:     nil,
        }

        before_action :authenticate_entity_from_token!

        define_method "#{name}_signed_in?" do
          !!self.class.token_authentication_on[:current]
        end

        define_method "current_#{name}" do
          self.class.token_authentication_on[:current]
        end
      end

    end

    module InstanceMethods

    protected

      def token_authentication_header
        @token_authentication_header ||= {
          id:    request.headers['X-Auth-ID'],
          token: request.headers['X-Auth-Token'],
        }
      end

      def authenticate_entity_from_token!
        id = token_authentication_header[:id]

        model = id.present? \
          && self.class.token_authentication_on[:model_class].find(id)

        unless model
          return token_authentication_error! :no_entity
        end

        unless model.valid_access_token? token_authentication_header[:token]
          return token_authentication_error! :invalid_token
        end

        self.class.token_authentication_on[:current] = model
      end

      def token_authentication_error!(type)
        render nothing: true, status: :unauthorized
        false
      end

    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
touth-1.0.0 lib/touth/action_controller_support.rb
touth-0.0.2 lib/touth/action_controller_support.rb
touth-0.0.1 lib/touth/action_controller_support.rb