This commit was manufactured by cvs2svn to create branch
[plcapi.git] / PLC / Persons.py
index c61e8bd..7a2e635 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.17 2006/11/08 22:45:20 mlhuang Exp $
+# $Id$
 #
 
 from types import StringTypes
@@ -16,11 +16,13 @@ import re
 import crypt
 
 from PLC.Faults import *
+from PLC.Debug import log
 from PLC.Parameter import Parameter
 from PLC.Filter import Filter
 from PLC.Table import Row, Table
+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,9 +33,9 @@ class Person(Row):
 
     table_name = 'persons'
     primary_key = 'person_id'
-    join_tables = ['person_role', 'person_site', 'slice_person', 'person_session']
+    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, nullok = True),
@@ -43,15 +45,33 @@ class Person(Row):
         '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(int, "Date and time of last update", ro = True),
+        '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),
         }
 
+    # 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):
         """
         Validate email address. Stolen from Mailman.
@@ -74,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
@@ -104,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
@@ -152,97 +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']
-
-        if role_id not in self['role_ids']:
-            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()
-
-            self['role_ids'].append(role_id)
-
-    def remove_role(self, role_id, commit = True):
-        """
-        Remove role from existing account.
-        """
-
-        assert 'person_id' in self
-
-        person_id = self['person_id']
-
-        if role_id in self['role_ids']:
-            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()
-
-            self['role_ids'].remove(role_id)
-    def add_key(self, key, commit = True):
-        """
-        Add key to existing account.
-        """
-
-        assert 'person_id' in self
-        assert isinstance(key, Key)
-        assert 'key_id' in key
-
-        person_id = self['person_id']
-        key_id = key['key_id']
+    add_role = Row.add_object(Role, 'person_role')
+    remove_role = Row.remove_object(Role, 'person_role')
 
-        if key_id not in self['key_ids']:
-            self.api.db.do("INSERT INTO person_key (person_id, key_id)" \
-                           " VALUES(%(person_id)d, %(key_id)d)",
-                           locals())
-
-            if commit:
-                self.api.db.commit()
-
-            self['key_ids'].append(key_id)
-
-    def remove_key(self, key, commit = True):
-        """
-        Remove key from existing account.
-        """
-
-        assert 'person_id' in self
-        assert isinstance(key, Key)
-        assert 'key_id' in key
-
-        person_id = self['person_id']
-        key_id = key['key_id']
-
-        if key_id in self['key_ids']:
-            self.api.db.do("DELETE FROM person_key" \
-                           " WHERE person_id = %(person_id)d" \
-                           " AND key_id = %(key_id)d",
-                           locals())
-
-            if commit:
-                self.api.db.commit()
-
-            self['key_ids'].remove(key_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']
@@ -267,12 +212,12 @@ class Person(Row):
 
     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
@@ -290,12 +235,68 @@ class Persons(Table):
     database.
     """
 
-    def __init__(self, api, person_filter = None):
-        Table.__init__(self, api, Person)
-
-        sql = "SELECT %s FROM view_persons WHERE deleted IS False" % \
-              ", ".join(Person.fields)
-
+    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(self.columns)
+       foreign_fields = {'role_ids': ('role_id', 'person_role'),
+                         'roles': ('name', 'roles'),
+                          'site_ids': ('site_id', 'person_site'),
+                          'key_ids': ('key_id', 'person_key'),
+                          'slice_ids': ('slice_id', 'slice_person')
+                          }
+       foreign_keys = {}
+       db_fields = filter(lambda field: field not in foreign_fields.keys(), Person.fields.keys())
+       all_fields = db_fields + [value[0] for value in foreign_fields.values()]
+       fields = []
+       _select = "SELECT "
+       _from = " FROM persons "
+       _join = " LEFT JOIN peer_person USING (person_id) "  
+       _where = " WHERE deleted IS False "
+
+       if not columns:
+           # include all columns       
+           fields = all_fields
+           tables = [value[1] for value in foreign_fields.values()]
+           tables.sort()
+           for key in foreign_fields.keys():
+               foreign_keys[foreign_fields[key][0]] = key  
+           for table in tables:
+               if table in ['roles']:
+                   _join += " LEFT JOIN roles USING(role_id) "
+               else:   
+                   _join += " LEFT JOIN %s USING (person_id) " % (table)
+       else: 
+           tables = set()
+           columns = filter(lambda column: column in db_fields+foreign_fields.keys(), columns)
+           columns.sort()
+           for column in columns: 
+               if column in foreign_fields.keys():
+                   (field, table) = foreign_fields[column]
+                   foreign_keys[field] = column
+                   fields += [field]
+                   tables.add(table)
+                   if column in ['roles']:
+                       _join += " LEFT JOIN roles USING(role_id) "
+                   else:
+                       _join += " LEFT JOIN %s USING (person_id)" % \
+                               (foreign_fields[column][1])
+               
+               else:
+                   fields += [column]  
+       
+       # postgres will return timestamps as datetime objects. 
+       # XMLPRC cannot marshal datetime so convert to int
+       timestamps = ['date_created', 'last_updated', 'verification_expires']
+       for field in fields:
+           if field in timestamps:
+               fields[fields.index(field)] = \
+                "CAST(date_part('epoch', %s) AS bigint) AS %s" % (field, field)
+
+       _select += ", ".join(fields)
+       sql = _select + _from + _join + _where
+
+       # deal with filter                      
         if person_filter is not None:
             if isinstance(person_filter, (list, tuple, set)):
                 # Separate the list into integers and strings
@@ -307,4 +308,29 @@ class Persons(Table):
                 person_filter = Filter(Person.fields, person_filter)
                 sql += " AND (%s)" % person_filter.sql(api, "AND")
 
-        self.selectall(sql)
+       # aggregate data
+       all_persons = {}
+       for row in self.api.db.selectall(sql):
+           person_id = row['person_id']
+
+           if all_persons.has_key(person_id):
+               for (key, key_list) in foreign_keys.items():
+                   data = row.pop(key)
+                   row[key_list] = [data]
+                   if data and data not in all_persons[person_id][key_list]:
+                       all_persons[person_id][key_list].append(data)
+            else:
+               for key in foreign_keys.keys():
+                    value = row.pop(key)
+                   if value:   
+                       row[foreign_keys[key]] = [value]
+                   else:
+                       row[foreign_keys[key]] = []
+               if row: 
+                   all_persons[person_id] = row
+               
+       # populate self
+       for row in all_persons.values():
+           obj = self.classobj(self.api, row)
+            self.append(obj)
+