UDLdap.py: more useful exception if our array assumptions are violated
[mirror/userdir-ldap.git] / UDLdap.py
1 import ldap
2 import time
3 import datetime
4 import userdir_ldap
5 import sys
6
7
8 class Account:
9     array_values = ['objectClass', 'keyFingerPrint', 'mailWhitelist', 'mailRBL',
10                     'mailRHSBL', 'supplementaryGid', 'sshRSAAuthKey',
11                     'sudoPassword', 'dnsZoneEntry', 'allowedHost']
12     int_values = ['shadowExpire', 'gidNumber', 'uidNumber']
13     defaults = {
14         'accountStatus': 'active',
15         'keyFingerPrint': []
16     }
17
18     @staticmethod
19     def from_search(ldap_connection, base, user):
20         searchresult = ldap_connection.search_s(base, ldap.SCOPE_SUBTREE, 'uid=%s' % (user,))
21         if len(searchresult) < 1:
22             raise IndexError("No such user: %s\n" % (user,))
23         elif len(searchresult) > 1:
24             raise IndexError("More than one hit when getting %s\n" % (user,))
25         else:
26             return Account(searchresult[0][0], searchresult[0][1])
27
28     def __init__(self, dn, attributes):
29         self.dn = dn
30         self.attributes = attributes
31         self.cache = {}
32
33     def __getitem__(self, key):
34         if key in self.cache:
35             return self.cache[key]
36
37         if key in self.attributes:
38             if key in self.array_values:
39                 self.cache[key] = self.attributes[key]
40             elif not len(self.attributes[key]) == 1:
41                 raise ValueError, 'non-array value for %s has not exactly one value'%(key,)
42             elif key in self.int_values:
43                 self.cache[key] = int(self.attributes[key][0])
44             else:
45                 self.cache[key] = self.attributes[key][0]
46         elif key in self.defaults:
47             self.cache[key] = self.defaults[key]
48         else:
49             raise IndexError("No such key: %s (dn: %s)" % (key, self.dn))
50
51         return self.cache[key]
52
53     def __contains__(self, key):
54         return key in self.attributes
55
56     def has_mail(self):
57         if 'mailDisableMessage' in self.attributes:
58             return False
59         return True
60
61     # not locked locked,  just reset to something invalid like {crypt}*SSLRESET* is still active
62     def pw_active(self):
63         if 'userPassword' not in self:
64             return False
65         if self['userPassword'].upper() == '{CRYPT}*LK*':
66             return False
67         if self['userPassword'].upper().startswith("{CRYPT}!"):
68             return False
69         return True
70
71     def get_password(self):
72         p = self['userPassword']
73         if not p.upper().startswith('{CRYPT}') or len(p) > 50:
74             return p
75         else:
76             return p[7:]
77
78     # not expired
79     def shadow_active(self):
80         if 'shadowExpire' in self and \
81            self['shadowExpire'] < (time.time() / 3600 / 24):
82             return False
83         return True
84
85     def numkeys(self):
86         return len(self['keyFingerPrint'])
87
88     def is_active_user(self):
89         return self['accountStatus'] == 'active' and self.numkeys() != 0
90
91     def is_guest_account(self):
92         return 'supplementaryGid' in self and 'guest' in self['supplementaryGid']
93
94     def latitude_dec(self, anonymized=False):
95         return userdir_ldap.DecDegree(self['latitude'], anonymized)
96
97     def longitude_dec(self, anonymized=False):
98         return userdir_ldap.DecDegree(self['longitude'], anonymized)
99
100     def verbose_status(self):
101         status = []
102         status.append('mail: %s' % (['disabled', 'active'][self.has_mail()]))
103         status.append('pw: %s' % (['locked', 'active'][self.pw_active()]))
104         status.append('shadow: %s' % (['expired', 'active'][self.shadow_active()]))
105         status.append('keys: %d' % (self.numkeys()))
106         status.append('status: %s' % (self['accountStatus']))
107
108         return '(%s)' % (', '.join(status))
109
110     def delete_mailforward(self):
111         del self.attributes['emailForward']
112
113     def get_dn(self):
114         return self.dn
115
116     def email_address(self):
117         mailbox = "<%s@%s>" % (self['uid'], userdir_ldap.EmailAppend)
118         tokens = []
119         if 'cn' in self:
120             tokens.append(self['cn'])
121         if 'sn' in self:
122             tokens.append(self['sn'])
123         tokens.append(mailbox)
124         return ' '.join(tokens)
125
126     def is_allowed_by_hostacl(self, host):
127         if 'allowedHost' not in self:
128             return False
129         if host in self['allowedHost']:
130             return True
131         # or maybe it's a date limited ACL
132         for entry in self['allowedHost']:
133             list = entry.split(None, 1)
134             if len(list) == 1:
135                 continue
136             (h, expire) = list
137             if host != h:
138                 continue
139             try:
140                 parsed = datetime.datetime.strptime(expire, '%Y%m%d')
141             except ValueError:
142                 print >>sys.stderr, "Cannot parse expiry date in '%s' in hostACL entry for %s." % (entry, self['uid'])
143                 return False
144             return parsed >= datetime.datetime.now()
145         return False
146
147
148 # vim:set et:
149 # vim:set ts=4:
150 # vim:set shiftwidth=4: