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