Class: Rack::Ntlm

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/ntlm.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, config = {}) ⇒ Ntlm

Returns a new instance of Ntlm.



8
9
10
11
12
13
14
15
# File 'lib/rack/ntlm.rb', line 8

def initialize(app, config = {})
  @app = app
  @config = {
    :uri_pattern => /\//,
    :port => 389,
    :search_filter => "(sAMAccountName=%1)"
  }.merge(config)
end

Instance Method Details

#auth(user) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/rack/ntlm.rb', line 17

def auth(user)
  ldap = Net::LDAP.new
  ldap.host = @config[:host]
  ldap.port = @config[:port]
  ldap.base = @config[:base]
  ldap.auth @config[:auth][:username], @config[:auth][:password] if @config[:auth]
  !ldap.search(:filter => @config[:search_filter].gsub("%1", user)).empty?
rescue => e
  false
end

#call(env) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rack/ntlm.rb', line 28

def call(env)
  if env['PATH_INFO'] =~ @config[:uri_pattern] && env['HTTP_AUTHORIZATION'].blank?
    return [401, {'WWW-Authenticate' => "NTLM"}, []]
  end

  if /^(NTLM|Negotiate) (.+)/ =~ env["HTTP_AUTHORIZATION"]

    message = Net::NTLM::Message.decode64($2)

    if message.type == 1 
      type2 = Net::NTLM::Message::Type2.new
      return [401, {"WWW-Authenticate" => "NTLM " + type2.encode64}, []]
    end

    if message.type == 3 && env['PATH_INFO'] =~ @config[:uri_pattern]
      user = Net::NTLM::decode_utf16le(message.user)
      if auth(user)
        env['REMOTE_USER'] = user 
      else
        return [401, {}, ["You are not authorized to see this page"]]
      end
    end
	end

  @app.call(env)
end