Module: Sinatra::BasicAuthorization

Includes:
AbstractAuthorization
Defined in:
lib/amp/server/extension/authorization.rb

Overview

HTTP Authorization helpers for Sinatra.

In your helpers module, include Sinatra::Authorization and then define an #authorize(user, password) method to handle user provided credentials.

Inside your events, call #login_required to trigger the HTTP Authorization window to pop up in the browser.

Code adapted from Ryan Tomayko and Christopher Schneid, shared under an MIT License Code significantly refactored for Amp

Instance Method Summary collapse

Methods included from AbstractAuthorization

#authorized?, #bad_request!, #current_user, #unauthorized!

Instance Method Details

#authorize(username, password) ⇒ Boolean

Whether or not the supplied username and password (and path) combination are, as Taco Bell says, “Good To Go”.

Parameters:

  • username (String)

    the plaintext that is passed in from the browser

  • password (String)

    the plaintext (!!!!!!) password from the browser

Returns:

  • (Boolean)

    is the user/pass/path combo authorized?



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/amp/server/extension/authorization.rb', line 71

def authorize(username, password)
  repo = self.class.amp_repositories[request.path_info]
  return true unless repo && repos[repo]
  
  user = get_user_and_permissions repo, username # user = {:user => ..., :read => ..., :write => ...}
  return false if command_reads?(params["cmd"]) && !user[:read]
  return false if !command_reads?(params["cmd"]) && 
                  !user[:write] && repo_is_private?(repo)
              
  user[:user].password == password
end

#challengeObject

# From you app, call set :authorization_realm, “my app” to set this # or define a #authorization_realm method in your helpers block.



50
51
52
# File 'lib/amp/server/extension/authorization.rb', line 50

def challenge
  %(Basic realm="#{options.authorization_realm}")
end

#login_requiredObject

Call in any event that requires authentication



55
56
57
58
59
60
61
# File 'lib/amp/server/extension/authorization.rb', line 55

def 
  return if authorized?
  unauthorized! unless auth.provided?
  bad_request!  unless auth.basic?
  unauthorized! unless authorize(*auth.credentials)
  request.env['REMOTE_USER'] = auth.username
end