A class shouldn't write to stderr on error, it should throw an exception
[mirror/userdir-ldap.git] / UDLdap.py
1 import ldap
2 import time
3 import userdir_ldap
4
5 class Account:
6     array_values = ['objectClass', 'keyFingerPrint', 'mailWhitelist', 'mailRBL',
7                     'mailRHSBL', 'supplementaryGid', 'sshRSAAuthKey',
8                     'sudoPassword', 'dnsZoneEntry', 'allowedHost']
9     int_values = ['shadowExpire', 'gidNumber', 'uidNumber']
10     defaults = {
11                  'accountStatus': 'active',
12                  'keyFingerPrint': []
13                }
14
15     @staticmethod
16     def from_search(ldap_connection, base, user):
17         searchresult = ldap_connection.search_s(base, ldap.SCOPE_SUBTREE, 'uid=%s'%(user))
18         if len(searchresult) < 1:
19             raise IndexError, "No such user: %s\n"%(user)
20         elif len(searchresult) > 1:
21             raise IndexError, "More than one hit when getting %s\n"%(user)
22         else:
23             return Account(searchresult[0][0], searchresult[0][1])
24
25     def __init__(self, dn, attributes):
26         self.dn = dn
27         self.attributes = attributes
28
29     def __getitem__(self, key):
30         if key in self.attributes:
31             if key in self.array_values:
32                 return self.attributes[key]
33
34             if not len(self.attributes[key]) == 1:
35                 raise ValueError, 'non-array value has not exactly one value'
36
37             if key in self.int_values:
38                 return int(self.attributes[key][0])
39             else:
40                 return self.attributes[key][0]
41         elif key in self.defaults:
42             return self.defaults[key]
43         else:
44             raise IndexError
45
46     def __contains__(self, key):
47         return key in self.attributes
48
49     def has_mail(self):
50         if 'mailDisableMessage' in self.attributes:
51             return False
52         return True
53
54     # not locked locked,  just reset to something invalid like {crypt}*SSLRESET* is still active
55     def pw_active(self):
56         if self['userPassword'] == '{crypt}*LK*':
57             return False
58         if self['userPassword'].startswith("{crypt}!"):
59             return False
60         return True
61
62     def get_password(self):
63         p = self['userPassword']
64         if not p.startswith('{crypt}') or len(p) > 50:
65             return p
66         else:
67             return p[7:]
68
69     # not expired
70     def shadow_active(self):
71         if 'shadowExpire' in self and \
72             self['shadowExpire'] < (time.time() / 3600 / 24):
73             return False
74         return True
75
76     def numkeys(self):
77         return len(self['keyFingerPrint'])
78
79     def is_active_user(self):
80         return self['accountStatus'] == 'active' and self.numkeys() != 0
81
82     def latitude_dec(self, anonymized=False):
83         return userdir_ldap.DecDegree(self['latitude'], anonymized)
84     def longitude_dec(self, anonymized=False):
85         return userdir_ldap.DecDegree(self['longitude'], anonymized)
86
87     def verbose_status(self):
88         status = []
89         status.append('mail: %s'  %(['disabled', 'active'][ self.has_mail() ]))
90         status.append('pw: %s'    %(['locked', 'active'][ self.pw_active() ]))
91         status.append('shadow: %s'%(['expired', 'active'][ self.shadow_active() ]))
92         status.append('keys: %d'  %( self.numkeys() ))
93         status.append('status: %s'%( self['accountStatus'] ))
94
95         return '(%s)'%(', '.join(status))
96
97     def delete_mailforward(self):
98         del self.attributes['emailForward']
99
100     def get_dn(self):
101         return self.dn
102
103     def email_address(self):
104         mailbox = "<%s@%s>" % (self['uid'], userdir_ldap.EmailAppend)
105         tokens = []
106         if 'cn' in self: tokens.append(self['cn'])
107         if 'sn' in self: tokens.append(self['sn'])
108         tokens.append(mailbox)
109         return ' '.join(tokens)
110
111 # vim:set et:
112 # vim:set ts=4:
113 # vim:set shiftwidth=4: