Fix is_guest_account for the usergroups transition
[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         self.cache = {}
31
32     def __getitem__(self, key):
33         if key in self.cache:
34             return self.cache[key]
35
36         if key in self.attributes:
37             if key in self.array_values:
38                 self.cache[key] = self.attributes[key]
39             elif not len(self.attributes[key]) == 1:
40                 raise ValueError, 'non-array value has not exactly one value'
41             elif key in self.int_values:
42                 self.cache[key] = int(self.attributes[key][0])
43             else:
44                 self.cache[key] = self.attributes[key][0]
45         elif key in self.defaults:
46             self.cache[key] = self.defaults[key]
47         else:
48             raise IndexError, "No such key: %s (dn: %s)"%(key, self.dn)
49
50         return self.cache[key]
51
52     def __contains__(self, key):
53         return key in self.attributes
54
55     def has_mail(self):
56         if 'mailDisableMessage' in self.attributes:
57             return False
58         return True
59
60     # not locked locked,  just reset to something invalid like {crypt}*SSLRESET* is still active
61     def pw_active(self):
62         if not 'userPassword' in self:
63             return False
64         if self['userPassword'].upper() == '{CRYPT}*LK*':
65             return False
66         if self['userPassword'].upper().startswith("{CRYPT}!"):
67             return False
68         return True
69
70     def get_password(self):
71         p = self['userPassword']
72         if not p.upper().startswith('{CRYPT}') or len(p) > 50:
73             return p
74         else:
75             return p[7:]
76
77     # not expired
78     def shadow_active(self):
79         if 'shadowExpire' in self and \
80             self['shadowExpire'] < (time.time() / 3600 / 24):
81             return False
82         return True
83
84     def numkeys(self):
85         return len(self['keyFingerPrint'])
86
87     def is_active_user(self):
88         return self['accountStatus'] == 'active' and self.numkeys() != 0
89
90     def is_guest_account(self):
91         return 'guest' in self['supplementaryGid']
92
93     def latitude_dec(self, anonymized=False):
94         return userdir_ldap.DecDegree(self['latitude'], anonymized)
95     def longitude_dec(self, anonymized=False):
96         return userdir_ldap.DecDegree(self['longitude'], anonymized)
97
98     def verbose_status(self):
99         status = []
100         status.append('mail: %s'  %(['disabled', 'active'][ self.has_mail() ]))
101         status.append('pw: %s'    %(['locked', 'active'][ self.pw_active() ]))
102         status.append('shadow: %s'%(['expired', 'active'][ self.shadow_active() ]))
103         status.append('keys: %d'  %( self.numkeys() ))
104         status.append('status: %s'%( self['accountStatus'] ))
105
106         return '(%s)'%(', '.join(status))
107
108     def delete_mailforward(self):
109         del self.attributes['emailForward']
110
111     def get_dn(self):
112         return self.dn
113
114     def email_address(self):
115         mailbox = "<%s@%s>" % (self['uid'], userdir_ldap.EmailAppend)
116         tokens = []
117         if 'cn' in self: tokens.append(self['cn'])
118         if 'sn' in self: tokens.append(self['sn'])
119         tokens.append(mailbox)
120         return ' '.join(tokens)
121
122     def is_allowed_by_hostacl(self, host):
123         if not 'allowedHost' in self: return False
124         if host in self['allowedHost']: return True
125         # or maybe it's a date limited ACL
126         for entry in self['allowedHost']:
127             list = entry.split(None,1)
128             if len(list) == 1: continue
129             (h, expire) = list
130             if host != h: continue
131             try:
132                 parsed = datetime.datetime.strptime(expire, '%Y%m%d')
133             except ValueError:
134                 print >>sys.stderr, "Cannot parse expiry date in '%s' in hostACL entry for %s."%(entry, self['uid'])
135                 return False
136             return parsed >= datetime.datetime.now()
137         return False
138
139
140 # vim:set et:
141 # vim:set ts=4:
142 # vim:set shiftwidth=4: