nate (owner)

Forks

Revisions

gist: 109850 Download_button fork
public
Public Clone URL: git://gist.github.com/109850.git
Ruby
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
module Sinatra
  module Authorization
 
  def auth
    @auth ||= Rack::Auth::Basic::Request.new(request.env)
  end
 
  def unauthorized!(realm="flixcloud.com")
    response['WWW-Authenticate'] = %(Basic realm="#{realm}")
    throw :halt, [ 401, 'Authorization Required' ]
  end
 
  def bad_request!
    throw :halt, [ 400, 'Bad Request' ]
  end
 
  def authorized?
    request.env['REMOTE_USER']
  end
 
  def authorize(username, password)
    # Insert your logic here to determine if username/password is good
    false
  end
 
  def require_authorization
    return if authorized?
    unauthorized! unless auth.provided?
    bad_request! unless auth.basic?
    unauthorized! unless authorize(*auth.credentials)
    request.env['REMOTE_USER'] = auth.username
  end
 
  def admin?
    authorized?
  end
 
  end
end
Ruby
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require 'sinatra/authorization'
 
class Whatever < Sinatra::Base
  helpers do
    include Sinatra::Authorization
 
    def authorize(username, password)
      User.authenticate(username, password)
    end
  end
 
  get '/something' do
    require_authorization
    # Do some other crap
  end
 
end