Sha256: dfb3bd33b0bcb7ab6a0809dba070c69603f14fb7d75cdb9d49a23c490042a439

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

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(&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 = Session.find_by_key(token)
        if session && session.expiration > DateTime.now
          session
        else
          false
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
token_authenticate_me-0.4.3 lib/token_authenticate_me/controllers/token_authenticateable.rb