- fix errors
[plcapi.git] / PLC / Persons.py
index b549a94..ff1b6cb 100644 (file)
@@ -4,7 +4,7 @@
 # Mark Huang <mlhuang@cs.princeton.edu>
 # Copyright (C) 2006 The Trustees of Princeton University
 #
-# $Id: Persons.py,v 1.5 2006/10/02 15:25:03 mlhuang Exp $
+# $Id: Persons.py,v 1.32 2007/01/11 05:37:55 mlhuang Exp $
 #
 
 from types import StringTypes
@@ -16,13 +16,13 @@ import re
 import crypt
 
 from PLC.Faults import *
+from PLC.Debug import log
 from PLC.Parameter import Parameter
-from PLC.Debug import profile
+from PLC.Filter import Filter
 from PLC.Table import Row, Table
-from PLC.Roles import Roles
-from PLC.Addresses import Address, Addresses
+from PLC.Roles import Role, Roles
 from PLC.Keys import Key, Keys
-import PLC.Sites
+from PLC.Messages import Message, Messages
 
 class Person(Row):
     """
@@ -31,29 +31,46 @@ class Person(Row):
     dict. Commit to the database with sync().
     """
 
+    table_name = 'persons'
+    primary_key = 'person_id'
+    join_tables = ['person_key', 'person_role', 'person_site', 'slice_person', 'person_session', 'peer_person']
     fields = {
-        'person_id': Parameter(int, "Account identifier"),
+        'person_id': Parameter(int, "User identifier"),
         'first_name': Parameter(str, "Given name", max = 128),
         'last_name': Parameter(str, "Surname", max = 128),
-        'title': Parameter(str, "Title", max = 128),
+        'title': Parameter(str, "Title", max = 128, nullok = True),
         'email': Parameter(str, "Primary e-mail address", max = 254),
-        'phone': Parameter(str, "Telephone number", max = 64),
-        'url': Parameter(str, "Home page", max = 254),
-        'bio': Parameter(str, "Biography", max = 254),
+        'phone': Parameter(str, "Telephone number", max = 64, nullok = True),
+        'url': Parameter(str, "Home page", max = 254, nullok = True),
+        'bio': Parameter(str, "Biography", max = 254, nullok = True),
         'enabled': Parameter(bool, "Has been enabled"),
         'password': Parameter(str, "Account password in crypt() form", max = 254),
-        'last_updated': Parameter(str, "Date and time of last update"),
-        'date_created': Parameter(str, "Date and time when account was created"),
+        'verification_key': Parameter(str, "Reset password key", max = 254, nullok = True),
+       'verification_expires': Parameter(int, "Date and time when verification_key expires", nullok = True),
+       'last_updated': Parameter(int, "Date and time of last update", ro = True),
+        'date_created': Parameter(int, "Date and time when account was created", ro = True),
         'role_ids': Parameter([int], "List of role identifiers"),
         'roles': Parameter([str], "List of roles"),
         'site_ids': Parameter([int], "List of site identifiers"),
         'key_ids': Parameter([int], "List of key identifiers"),
         'slice_ids': Parameter([int], "List of slice identifiers"),
+        'peer_id': Parameter(int, "Peer to which this user belongs", nullok = True),
+        'peer_person_id': Parameter(int, "Foreign user identifier at peer", nullok = True),
         }
 
-    def __init__(self, api, fields):
-        Row.__init__(self, fields)
-        self.api = api
+    # for Cache
+    class_key = 'email'
+    foreign_fields = ['first_name', 'last_name', 'title', 'email', 'phone', 'url',
+                     'bio', 'enabled', 'password', ]
+    # forget about these ones, they are read-only anyway
+    # handling them causes Cache to re-sync all over again 
+    # 'last_updated', 'date_created'
+    foreign_xrefs = [
+        {'field' : 'key_ids',  'class': 'Key',  'table' : 'person_key' } ,
+        {'field' : 'site_ids', 'class': 'Site', 'table' : 'person_site'},
+#       xxx this is not handled by Cache yet
+#        'role_ids': Parameter([int], "List of role identifiers"),
+]
 
     def validate_email(self, email):
         """
@@ -77,15 +94,15 @@ class Person(Row):
         rest = email[at_sign+1:]
         domain = rest.split('.')
 
-        # This means local, unqualified addresses, are no allowed
+        # This means local, unqualified addresses, are not allowed
         if not domain:
             raise invalid_email
         if len(domain) < 2:
             raise invalid_email
 
         conflicts = Persons(self.api, [email])
-        for person_id, person in conflicts.iteritems():
-            if 'person_id' not in self or self['person_id'] != person_id:
+        for person in conflicts:
+            if 'person_id' not in self or self['person_id'] != person['person_id']:
                 raise PLCInvalidArgument, "E-mail address already in use"
 
         return email
@@ -107,6 +124,10 @@ class Person(Row):
             salt = md5.md5(salt).hexdigest()[:8] 
             return crypt.crypt(password.encode(self.api.encoding), magic + salt + "$")
 
+    validate_date_created = Row.validate_timestamp
+    validate_last_updated = Row.validate_timestamp
+    validate_verification_expires = Row.validate_timestamp
+
     def can_update(self, person):
         """
         Returns true if we can update the specified person. We can
@@ -155,52 +176,18 @@ class Person(Row):
 
         return False
 
-    def add_role(self, role_id, commit = True):
-        """
-        Add role to existing account.
-        """
-
-        assert 'person_id' in self
-
-        person_id = self['person_id']
-        self.api.db.do("INSERT INTO person_role (person_id, role_id)" \
-                       " VALUES(%(person_id)d, %(role_id)d)",
-                       locals())
-
-        if commit:
-            self.api.db.commit()
-
-        assert 'role_ids' in self
-        if role_id not in self['role_ids']:
-            self['role_ids'].append(role_id)
+    add_role = Row.add_object(Role, 'person_role')
+    remove_role = Row.remove_object(Role, 'person_role')
 
-    def remove_role(self, role_id, commit = True):
-        """
-        Remove role from existing account.
-        """
-
-        assert 'person_id' in self
-
-        person_id = self['person_id']
-        self.api.db.do("DELETE FROM person_role" \
-                       " WHERE person_id = %(person_id)d" \
-                       " AND role_id = %(role_id)d",
-                       locals())
-
-        if commit:
-            self.api.db.commit()
-
-        assert 'role_ids' in self
-        if role_id in self['role_ids']:
-            self['role_ids'].remove(role_id)
+    add_key = Row.add_object(Key, 'person_key')
+    remove_key = Row.remove_object(Key, 'person_key')
 
     def set_primary_site(self, site, commit = True):
         """
-        Set the primary site for an existing account.
+        Set the primary site for an existing user.
         """
 
         assert 'person_id' in self
-        assert isinstance(site, PLC.Sites.Site)
         assert 'site_id' in site
 
         person_id = self['person_id']
@@ -223,65 +210,19 @@ class Person(Row):
         self['site_ids'].remove(site_id)
         self['site_ids'].insert(0, site_id)
 
-    def sync(self, commit = True):
-        """
-        Commit changes back to the database.
-        """
-
-        self.validate()
-
-        # Fetch a new person_id if necessary
-        if 'person_id' not in self:
-            rows = self.api.db.selectall("SELECT NEXTVAL('persons_person_id_seq') AS person_id")
-            if not rows:
-                raise PLCDBError, "Unable to fetch new person_id"
-            self['person_id'] = rows[0]['person_id']
-            insert = True
-        else:
-            insert = False
-
-        # Filter out fields that cannot be set or updated directly
-        persons_fields = self.api.db.fields('persons')
-        fields = dict(filter(lambda (key, value): key in persons_fields,
-                             self.items()))
-        for ro_field in 'date_created', 'last_updated':
-            if ro_field in fields:
-                del fields[ro_field]
-
-        # Parameterize for safety
-        keys = fields.keys()
-        values = [self.api.db.param(key, value) for (key, value) in fields.items()]
-
-        if insert:
-            # Insert new row in persons table
-            sql = "INSERT INTO persons (%s) VALUES (%s)" % \
-                  (", ".join(keys), ", ".join(values))
-        else:
-            # Update existing row in persons table
-            columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
-            sql = "UPDATE persons SET " + \
-                  ", ".join(columns) + \
-                  " WHERE person_id = %(person_id)d"
-
-        self.api.db.do(sql, fields)
-
-        if commit:
-            self.api.db.commit()
-
     def delete(self, commit = True):
         """
-        Delete existing account.
+        Delete existing user.
         """
 
         # Delete all keys
         keys = Keys(self.api, self['key_ids'])
-        for key in keys.values():
+        for key in keys:
             key.delete(commit = False)
 
         # Clean up miscellaneous join tables
-        for table in ['person_role', 'person_site', 'slice_person']:
-            self.api.db.do("DELETE FROM %s" \
-                           " WHERE person_id = %d" % \
+        for table in self.join_tables:
+            self.api.db.do("DELETE FROM %s WHERE person_id = %d" % \
                            (table, self['person_id']))
 
         # Mark as deleted
@@ -291,44 +232,24 @@ class Person(Row):
 class Persons(Table):
     """
     Representation of row(s) from the persons table in the
-    database. Specify deleted and/or enabled to force a match on
-    whether a person is deleted and/or enabled. Default is to match on
-    non-deleted accounts.
+    database.
     """
 
-    def __init__(self, api, person_id_or_email_list = None, fields = Person.fields, enabled = None):
-        self.api = api
+    def __init__(self, api, person_filter = None, columns = None):
+        Table.__init__(self, api, Person, columns)
 
         sql = "SELECT %s FROM view_persons WHERE deleted IS False" % \
-              ", ".join(fields)
-
-        if enabled is not None:
-            sql += " AND enabled IS %(enabled)s"
-
-        if person_id_or_email_list:
-            # Separate the list into integers and strings
-            person_ids = filter(lambda person_id: isinstance(person_id, (int, long)),
-                                person_id_or_email_list)
-            emails = filter(lambda email: isinstance(email, StringTypes),
-                            person_id_or_email_list)
-            sql += " AND (False"
-            if person_ids:
-                sql += " OR person_id IN (%s)" % ", ".join(map(str, person_ids))
-            if emails:
-                # Case insensitive e-mail address comparison
-                sql += " OR email IN (%s)" % ", ".join(api.db.quote(emails)).lower()
-            sql += ")"
-
-        rows = self.api.db.selectall(sql, locals())
-
-        for row in rows:
-            self[row['person_id']] = person = Person(api, row)
-            for aggregate in 'role_ids', 'roles', 'site_ids', 'key_ids', 'slice_ids':
-                if not person.has_key(aggregate) or person[aggregate] is None:
-                    person[aggregate] = []
-                else:
-                    elements = person[aggregate].split(',')
-                    try:
-                        person[aggregate] = map(int, elements)
-                    except ValueError:
-                        person[aggregate] = elements
+              ", ".join(self.columns)
+
+        if person_filter is not None:
+            if isinstance(person_filter, (list, tuple, set)):
+                # Separate the list into integers and strings
+                ints = filter(lambda x: isinstance(x, (int, long)), person_filter)
+                strs = filter(lambda x: isinstance(x, StringTypes), person_filter)
+                person_filter = Filter(Person.fields, {'person_id': ints, 'email': strs})
+                sql += " AND (%s)" % person_filter.sql(api, "OR")
+            elif isinstance(person_filter, dict):
+                person_filter = Filter(Person.fields, person_filter)
+                sql += " AND (%s)" % person_filter.sql(api, "AND")
+
+        self.selectall(sql)