Module: Sinatra::Authorization

Defined in:
lib/sinatra/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

Instance Method Summary collapse

Instance Method Details

#authorization_realmObject

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



24
25
26
# File 'lib/sinatra/authorization.rb', line 24

def authorization_realm
  options.authorization_realm
end

#authorize(username, password) ⇒ Object

Redefine this method on your helpers block to actually contain your authorization logic.



18
19
20
# File 'lib/sinatra/authorization.rb', line 18

def authorize(username, password)
  false
end

#authorized?Boolean Also known as: logged_in?

Convenience method to determine if a user is logged in

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/sinatra/authorization.rb', line 38

def authorized?
  #!!request.env['REMOTE_USER']
  !!current_user
end

#current_userObject

Name provided by the current user to log in



45
46
47
48
49
# File 'lib/sinatra/authorization.rb', line 45

def current_user
  request.env['REMOTE_USER'] = auth.username if
    auth.provided? && auth.basic? && authorize(*auth.credentials)
  request.env['REMOTE_USER']
end

#login_requiredObject

Call in any event that requires authentication



29
30
31
32
33
34
35
# File 'lib/sinatra/authorization.rb', line 29

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