summaryrefslogtreecommitdiff
path: root/site-ruby/myldap.rb
blob: 770502979c720155b0d08413d0c3c0e2545fc969 (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
#
# 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'])
		@basedn = config['basedn']
		if use
			@binddn = config['credentials'][use]['binddn']
			@bindpw = config['credentials'][use]['bindpw']
		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