Module: Sinatra::BasicAuth

Defined in:
lib/sinatra/basic_auth.rb,
lib/sinatra/basic_auth/version.rb

Defined Under Namespace

Modules: Helpers, Version

Constant Summary collapse

REALM_ENV =
"REALM:%s"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.validatorsObject

Returns the value of attribute validators.



8
9
10
# File 'lib/sinatra/basic_auth.rb', line 8

def validators
  @validators
end

Class Method Details

.registered(app) ⇒ Object



60
61
62
# File 'lib/sinatra/basic_auth.rb', line 60

def self.registered(app)
  app.helpers Sinatra::BasicAuth::Helpers
end

Instance Method Details

#authorize(realm = "Restricted", &block) ⇒ Object



33
34
35
# File 'lib/sinatra/basic_auth.rb', line 33

def authorize(realm = "Restricted", &block)
  Sinatra::BasicAuth.validators[realm] = block
end

#protect(_realm = "Restricted", &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sinatra/basic_auth.rb', line 37

def protect(_realm = "Restricted", &block)
  condition do
    @realm = _realm

    catch(:request_authorization) {
      unless authorized?
        if auth.provided? && auth.basic? && valid_credentials?
          request.env[REALM_ENV % realm] = auth.credentials.first
        else
          headers "WWW-Authenticate" => %[Basic realm="#{realm}"]
          throw :halt, [ 401, "Authorization Required" ]
        end

        throw :request_authorization unless authorized?
      end
    }

    authorized?
  end

  yield
end