Sha256: 6ef12e6892c85eb4d9bf6012a92e59d5ccefaf52352875942dfc24f2961336ba

Contents?: true

Size: 964 Bytes

Versions: 8

Compression:

Stored size: 964 Bytes

Contents

require 'active_support/concern'

module TokenAuthenticateMe
  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)
        else
          nil
        end
      end

      def authenticate_token
        @session ||= authenticate_with_http_token do |token, _options|
          session = Session.find_by_key(token)
          if session && session.expiration > DateTime.now
            session
          else
            false
          end
        end
      end

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

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
token_authenticate_me-0.4.2 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.4.1 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.4.0 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.3.0 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.2.3 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.2.2 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.2.1 lib/token_authenticate_me/controllers/token_authenticateable.rb
token_authenticate_me-0.2.0 lib/token_authenticate_me/controllers/token_authenticateable.rb