2 # Functions for interacting with the persons table in the database
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
7 # $Id: Persons.py,v 1.15 2006/10/27 15:32:56 mlhuang Exp $
10 from types import StringTypes
11 from datetime import datetime
14 from random import Random
18 from PLC.Faults import *
19 from PLC.Parameter import Parameter
20 from PLC.Debug import profile
21 from PLC.Table import Row, Table
22 from PLC.Keys import Key, Keys
27 Representation of a row in the persons table. To use, optionally
28 instantiate with a dict of values. Update as you would a
29 dict. Commit to the database with sync().
32 table_name = 'persons'
33 primary_key = 'person_id'
35 'person_id': Parameter(int, "Account identifier"),
36 'first_name': Parameter(str, "Given name", max = 128),
37 'last_name': Parameter(str, "Surname", max = 128),
38 'title': Parameter(str, "Title", max = 128, nullok = True),
39 'email': Parameter(str, "Primary e-mail address", max = 254),
40 'phone': Parameter(str, "Telephone number", max = 64, nullok = True),
41 'url': Parameter(str, "Home page", max = 254, nullok = True),
42 'bio': Parameter(str, "Biography", max = 254, nullok = True),
43 'enabled': Parameter(bool, "Has been enabled"),
44 'password': Parameter(str, "Account password in crypt() form", max = 254),
45 'last_updated': Parameter(int, "Date and time of last update", ro = True),
46 'date_created': Parameter(int, "Date and time when account was created", ro = True),
47 'role_ids': Parameter([int], "List of role identifiers", ro = True),
48 'roles': Parameter([str], "List of roles", ro = True),
49 'site_ids': Parameter([int], "List of site identifiers", ro = True),
50 'key_ids': Parameter([int], "List of key identifiers", ro = True),
51 'slice_ids': Parameter([int], "List of slice identifiers", ro = True),
54 def validate_email(self, email):
56 Validate email address. Stolen from Mailman.
59 invalid_email = PLCInvalidArgument("Invalid e-mail address")
60 email_badchars = r'[][()<>|;^,\200-\377]'
62 # Pretty minimal, cheesy check. We could do better...
63 if not email or email.count(' ') > 0:
65 if re.search(email_badchars, email) or email[0] == '-':
69 at_sign = email.find('@')
72 user = email[:at_sign]
73 rest = email[at_sign+1:]
74 domain = rest.split('.')
76 # This means local, unqualified addresses, are no allowed
82 conflicts = Persons(self.api, [email])
83 for person_id, person in conflicts.iteritems():
84 if 'person_id' not in self or self['person_id'] != person_id:
85 raise PLCInvalidArgument, "E-mail address already in use"
89 def validate_password(self, password):
91 Encrypt password if necessary before committing to the
97 if len(password) > len(magic) and \
98 password[0:len(magic)] == magic:
101 # Generate a somewhat unique 8 character salt string
102 salt = str(time.time()) + str(Random().random())
103 salt = md5.md5(salt).hexdigest()[:8]
104 return crypt.crypt(password.encode(self.api.encoding), magic + salt + "$")
106 def can_update(self, person):
108 Returns true if we can update the specified person. We can
111 1. We are the person.
113 3. We are a PI and the person is a user or tech or at
117 assert isinstance(person, Person)
119 if self['person_id'] == person['person_id']:
122 if 'admin' in self['roles']:
125 if 'pi' in self['roles']:
126 if set(self['site_ids']).intersection(person['site_ids']):
127 # Can update people with higher role IDs
128 return min(self['role_ids']) < min(person['role_ids'])
132 def can_view(self, person):
134 Returns true if we can view the specified person. We can
137 1. We are the person.
139 3. We are a PI and the person is at one of our sites.
142 assert isinstance(person, Person)
144 if self.can_update(person):
147 if 'pi' in self['roles']:
148 if set(self['site_ids']).intersection(person['site_ids']):
149 # Can view people with equal or higher role IDs
150 return min(self['role_ids']) <= min(person['role_ids'])
154 def add_role(self, role_id, commit = True):
156 Add role to existing account.
159 assert 'person_id' in self
161 person_id = self['person_id']
163 if role_id not in self['role_ids']:
164 self.api.db.do("INSERT INTO person_role (person_id, role_id)" \
165 " VALUES(%(person_id)d, %(role_id)d)",
171 self['role_ids'].append(role_id)
173 def remove_role(self, role_id, commit = True):
175 Remove role from existing account.
178 assert 'person_id' in self
180 person_id = self['person_id']
182 if role_id in self['role_ids']:
183 self.api.db.do("DELETE FROM person_role" \
184 " WHERE person_id = %(person_id)d" \
185 " AND role_id = %(role_id)d",
191 self['role_ids'].remove(role_id)
193 def add_key(self, key, commit = True):
195 Add key to existing account.
198 assert 'person_id' in self
199 assert isinstance(key, Key)
200 assert 'key_id' in key
202 person_id = self['person_id']
203 key_id = key['key_id']
205 if key_id not in self['key_ids']:
206 self.api.db.do("INSERT INTO person_key (person_id, key_id)" \
207 " VALUES(%(person_id)d, %(key_id)d)",
213 self['key_ids'].append(key_id)
215 def remove_key(self, key, commit = True):
217 Remove key from existing account.
220 assert 'person_id' in self
221 assert isinstance(key, Key)
222 assert 'key_id' in key
224 person_id = self['person_id']
225 key_id = key['key_id']
227 if key_id in self['key_ids']:
228 self.api.db.do("DELETE FROM person_key" \
229 " WHERE person_id = %(person_id)d" \
230 " AND key_id = %(key_id)d",
236 self['key_ids'].remove(key_id)
238 def set_primary_site(self, site, commit = True):
240 Set the primary site for an existing account.
243 assert 'person_id' in self
244 assert isinstance(site, PLC.Sites.Site)
245 assert 'site_id' in site
247 person_id = self['person_id']
248 site_id = site['site_id']
249 self.api.db.do("UPDATE person_site SET is_primary = False" \
250 " WHERE person_id = %(person_id)d",
252 self.api.db.do("UPDATE person_site SET is_primary = True" \
253 " WHERE person_id = %(person_id)d" \
254 " AND site_id = %(site_id)d",
260 assert 'site_ids' in self
261 assert site_id in self['site_ids']
263 # Make sure that the primary site is first in the list
264 self['site_ids'].remove(site_id)
265 self['site_ids'].insert(0, site_id)
267 def delete(self, commit = True):
269 Delete existing account.
273 keys = Keys(self.api, self['key_ids'])
274 for key in keys.values():
275 key.delete(commit = False)
277 # Clean up miscellaneous join tables
278 for table in ['person_role', 'person_site', 'slice_person', 'person_session']:
279 self.api.db.do("DELETE FROM %s" \
280 " WHERE person_id = %d" % \
281 (table, self['person_id']))
284 self['deleted'] = True
287 class Persons(Table):
289 Representation of row(s) from the persons table in the
290 database. Specify deleted and/or enabled to force a match on
291 whether a person is deleted and/or enabled. Default is to match on
292 non-deleted accounts.
295 def __init__(self, api, person_id_or_email_list = None, enabled = None):
298 sql = "SELECT %s FROM view_persons WHERE deleted IS False" % \
299 ", ".join(Person.fields)
301 if enabled is not None:
302 sql += " AND enabled IS %(enabled)s"
304 if person_id_or_email_list:
305 # Separate the list into integers and strings
306 person_ids = filter(lambda person_id: isinstance(person_id, (int, long)),
307 person_id_or_email_list)
308 emails = filter(lambda email: isinstance(email, StringTypes),
309 person_id_or_email_list)
312 sql += " OR person_id IN (%s)" % ", ".join(map(str, person_ids))
314 # Case insensitive e-mail address comparison
315 sql += " OR email IN (%s)" % ", ".join(api.db.quote(emails)).lower()
318 rows = self.api.db.selectall(sql, locals())
321 self[row['person_id']] = person = Person(api, row)
322 for aggregate in 'role_ids', 'roles', 'site_ids', 'key_ids', 'slice_ids':
323 if not person.has_key(aggregate) or person[aggregate] is None:
324 person[aggregate] = []
326 elements = person[aggregate].split(',')
328 person[aggregate] = map(int, elements)
330 person[aggregate] = elements