Sha256: 3b84831fab3159fa520a58ad02cf87018319131cc06e9249ab42ad8f99f17950

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

require 'active_support/concern'

module TokenAuthenticateMe
  module Concerns
    module Controllers
      module TokenAuthenticateable
        extend ActiveSupport::Concern

        included do
          before_action :authenticate
        end

        protected

        def authenticate
          authenticate_token || render_unauthorized
        end

        def current_user
          return unless authenticate_token
          @current_user ||= User.find_by_id(authenticate_token.user_id)
        end

        def authenticate_token
          @session ||= (
            authenticate_with_http_token(&method(:token_handler)) || authenticate_with_params
          )
        end

        def authenticate_with_params
          token = params[:authentication_token]
          token_handler(token, {})
        end

        def render_unauthorized
          headers['WWW-Authenticate'] = 'Token realm="Application"'
          render json: 'Bad credentials', status: 401
        end

        def token_handler(token, _options)
          session = TokenAuthenticateMe::Session.find_by_key(token)
          if session && session.expiration > DateTime.now
            session
          else
            false
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
token_authenticate_me-0.5.3 lib/token_authenticate_me/concerns/controllers/token_authenticateable.rb