Sha256: 6003ca2a444fe73a22640f0f3f3fa2e1e2380aa18e538bb3573d36e7e36a95a2

Contents?: true

Size: 1.05 KB

Versions: 2

Compression:

Stored size: 1.05 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
          if authenticate_token
            @current_user ||= User.find_by_id(authenticate_token.user_id)
          end
        end

        def authenticate_token
          @session ||= authenticate_with_http_token(&method(:token_handler))
        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

2 entries across 2 versions & 1 rubygems

Version Path
token_authenticate_me-0.5.1 lib/token_authenticate_me/concerns/controllers/token_authenticateable.rb
token_authenticate_me-0.5.0 lib/token_authenticate_me/concerns/controllers/token_authenticateable.rb