Sha256: 08ef47c3825cf9387b3f97b602ed4bfcde5b8260eed6225ea4493fe95f19f85b

Contents?: true

Size: 1.86 KB

Versions: 4

Compression:

Stored size: 1.86 KB

Contents

module Softwear
  module Auth
    module TokenAuthentication
      extend ActiveSupport::Concern

      included do
        cattr_accessor :user_class
        cattr_accessor :token_auth_options
      end

      def token_authenticate_user!
        user_class = self.class.user_class || base_class.user_class || User
        options    = (self.class.token_auth_options || base_class.token_auth_options || {}).with_indifferent_access
        params_options  = (options[:params]  || {}).with_indifferent_access
        headers_options = (options[:headers] || {}).with_indifferent_access

        email_param  = params_options[:email]                 || 'user_email'
        token_param  = params_options[:authentication_token]  || 'user_token'
        email_header = headers_options[:email]                || 'X-User-Email'
        token_header = headers_options[:authentication_token] || 'X-User-Token'

        email = params[email_param] || headers[email_header]
        token = params[token_param] || headers[token_header]

        return render_unauthorized if email.blank? || token.blank?

        case user_class.query "token #{Figaro.env.hub_app_name} #{email} #{token}"
        when 'no'      then render_unauthorized
        when 'invaild' then render_unauthorized
        when 'sorry'   then render_internal_server_error
        when 'yes'     then true
        end
      end

      private

      def render_unauthorized
        respond_to do |format|
          format.json do
            render status: :unauthorized,
                   json: { error: "Invalid or missing credentials" }
          end
        end
      end

      def render_internal_server_error
        respond_to do |format|
          format.json do
            render status: :internal_server_error,
                   json: { error: "Authentication server broke" }
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
softwear-lib-1.5.14 lib/softwear/auth/token_authentication.rb
softwear-lib-1.5.13 lib/softwear/auth/token_authentication.rb
softwear-lib-1.5.9 lib/softwear/auth/token_authentication.rb
softwear-lib-1.5.8 lib/softwear/auth/token_authentication.rb