Sha256: f2cb31695088fb7c39ca6aa5df5b64b4250e89d71225fd2ebf28d6a13a5adeee

Contents?: true

Size: 1.57 KB

Versions: 1

Compression:

Stored size: 1.57 KB

Contents

require 'rocketio/controller/token_auth'

module RocketIO
  class Controller

    # easily restrict access to controller using token auth
    #
    # @example simple Token example
    #
    #   class User < RocketIO::Controller
    #     token_auth { |token| token == 'secret' }
    #   end
    #
    def self.token_auth *args, &block
      opts = args.last.is_a?(Hash) ? args.pop : {}
      (args.any? ? args.map!(&:to_sym) : RocketIO::REQUEST_METHODS.values).each do |rm|
        (@__token_auth__ ||= {})[rm] = {
          realm: opts[:realm] || RocketIO::DEFAULT_TOKEN_AUTH_REALM.freeze,
          block: block
        }
      end
      define_token_auth_methods
    end

    def self.define_token_auth_methods source = self
      prompts = allocate.token_auth.merge(source.instance_variable_get(:@__token_auth__) || {}).freeze
      return if prompts.empty?
      private_api << define_method(:token_auth) {prompts}
    end

    def token_auth; RocketIO::EMPTY_HASH end

    def validate_or_request_authorization_if_needed
      return unless auth = token_auth[requested_method]
      return if validate_token_auth(&auth[:block])
      throw(:__response__, request_token_auth(auth[:realm]))
    end

    def validate_or_request_token_auth realm = RocketIO::DEFAULT_TOKEN_AUTH_REALM, &block
      validate_token_auth(&block) || request_token_auth(realm)
    end

    def validate_token_auth &block
      RocketIO::TokenAuth.authenticate(env, &block)
    end

    def request_token_auth realm = RocketIO::DEFAULT_TOKEN_AUTH_REALM
      RocketIO::TokenAuth.authentication_request(realm)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rocketio-0.1.0 lib/rocketio/controller/authorization.rb