summaryrefslogtreecommitdiff
path: root/site-ruby/myldap.rb
blob: 9aa66f8a9124ae663b27c12277c9cdd7bf30356e (plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#
# Copyright (c) 2004 Peter Palfrader <peter@palfrader.org>
#
# All rights reserved.
#

class MyLDAP
	def initialize(config, use = nil)
		@conn = LDAP::Conn.new(config['ldapserver'], config['ldapport'])
		@conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)
		@basedn = config['basedn']
		if use
			unless config['credentials'][use]
				throw "No credentials for #{use} found."
			end
			unless config['credentials'][use]['anon']
				@binddn = config['credentials'][use]['binddn']
				@bindpw = config['credentials'][use]['bindpw']
			end
		elsif File.exists? File.expand_path('~/.noreply.ldap')
			myconfig = YAML::load( File.open( File.expand_path('~/.noreply.ldap') ) )
			@binddn = myconfig['binddn']
			@bindpw = myconfig['bindpw']
		end
		if @binddn and @bindpw
			unless @conn.bind(@binddn, @bindpw)
				@conn.perror("bind")
			end
		end
	end

	def add(dn, data)
		puts "dn: #{dn}"
		data.each_pair{
			|key, value|
			value.each { |v|
				puts "#{key}: #{v}"
			}
		}
		puts
		begin
			entry = data.map{
				|key, value|
				LDAP.mod(LDAP::LDAP_MOD_ADD, key, value)
			}
			@conn.add(dn, entry)
		rescue LDAP::ResultError
			@conn.perror("add")
			return false
		end
		@conn.perror("add")
		return true
	end

	def conn()
		return @conn
	end

	def verify_client(client)
		begin
		  clients = @conn.search2(@basedn, LDAP::LDAP_SCOPE_SUBTREE,
		    '(&(objectclass=tnClient)(o='+client+'))')
		rescue LDAP::ResultError => msg
		  $stderr.print(msg)
		  exit 1
		end

		if clients.length != 1
		  STDERR.puts "Found %s clients with o=%s"%[clients.length, client]
		  exit 1
		end
		return clients.pop
	end

	def verify_local_domains_exist(addresses)
		domains = addresses.collect{ |a|
			  a =~ /@(.*)/
			  domain = $1
			  unless domain
				  STDERR.puts "%s is no email address"%[a]
				  exit 1
			  end
			  domain
			}.uniq

		domains.each { |d|
			begin
			  doms = @conn.search2(@basedn, LDAP::LDAP_SCOPE_SUBTREE,
			    '(&(objectclass=tnMailDomain)(tnMailDomainname='+d+'))')
			rescue LDAP::ResultError => msg
			  $stderr.print(msg)
			  exit 1
			end

			if doms.length != 1
			  STDERR.puts "Found %s tnMailDomains with tnMailDomainname=%s"%[doms.length, d]
			  exit 1
			end

			puts "Domain %s: check"%[d]
		}
	end
end