Add basic HTTP authentication and /token routes

- the only initial backend option for auth is LDAP
This commit is contained in:
Scott Schneider 2015-04-21 11:35:23 -07:00
parent 331ac33b53
commit e447b754c3
3 changed files with 134 additions and 0 deletions

View file

@ -4,6 +4,60 @@ module Vmpooler
module Helpers
def protected!
return if authorized?
content_type :json
result = { 'ok' => false }
headers['WWW-Authenticate'] = 'Basic realm="Authentication required"'
halt 401, JSON.pretty_generate(result)
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
if @auth.provided? and @auth.basic? and @auth.credentials
username, password = @auth.credentials
if authenticate(Vmpooler::API.settings.config[:auth], username, password)
return true
end
end
return false
end
def authenticate(auth, username_str, password_str)
case auth['provider']
when 'ldap'
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new(
:host => auth[:ldap]['host'],
:port => auth[:ldap]['port'] || 389,
:encryption => {
:method => :start_tls,
:tls_options => { :ssl_version => 'TLSv1' }
},
:base => auth[:ldap]['base'],
:auth => {
:method => :simple,
:username => "#{auth[:ldap]['user_object']}=#{username_str},#{auth[:ldap]['base']}",
:password => password_str
}
)
if ldap.bind
return true
end
end
return false
end
def mean(list)
s = list.map(&:to_f).reduce(:+).to_f
(s > 0 && list.length > 0) ? s / list.length.to_f : 0