Module: Sinatra::Authorization::HelperMethods

Defined in:
lib/authorization.rb

Instance Method Summary collapse

Instance Method Details

#admin?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/authorization.rb', line 44

def admin?
  authorized?
end

#authObject



11
12
13
14
# File 'lib/authorization.rb', line 11

def auth
  @auth ||= Rack::Auth::Basic::Request.new(request.env)
#    @auth ||= Rack::Auth::Digest::MD5.new(request.env)
end

#authorize(username, password) ⇒ Object



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

def authorize(username, password)
  return false if !File.exists?(passwd_file)
  pf = HTAuth::PasswdFile.new(passwd_file)
  user = pf.fetch(username)
  !user.nil? && user.authenticated?(password)
end

#authorized?Boolean

Returns:

  • (Boolean)


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

def authorized?
  request.env['REMOTE_USER']
end

#bad_request!Object



21
22
23
# File 'lib/authorization.rb', line 21

def bad_request!
  throw :halt, [ 400, 'Bad Request' ]
end

#passwd_fileObject



7
8
9
# File 'lib/authorization.rb', line 7

def passwd_file
  File.expand_path '../config/.htpasswd', __FILE__
end

#require_administrative_privilegesObject



36
37
38
39
40
41
42
# File 'lib/authorization.rb', line 36

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

#unauthorized!(realm = "Please Authenticate") ⇒ Object



16
17
18
19
# File 'lib/authorization.rb', line 16

def unauthorized!(realm = "Please Authenticate")
  header 'WWW-Authenticate' => %(Basic realm="#{realm}")
  throw :halt, [ 401, 'Authorization Required' ]
end