- make Add() calling convention consistent among all functions that
[plcapi.git] / PLC / Persons.py
index 01ba822..970e6e0 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.3 2006/09/08 19:45:46 mlhuang Exp $
+# $Id: Persons.py,v 1.12 2006/10/20 17:52:24 mlhuang Exp $
 #
 
 from types import StringTypes
@@ -19,8 +19,6 @@ from PLC.Faults import *
 from PLC.Parameter import Parameter
 from PLC.Debug import profile
 from PLC.Table import Row, Table
-from PLC.Roles import Roles
-from PLC.Addresses import Address, Addresses
 from PLC.Keys import Key, Keys
 import PLC.Sites
 
@@ -31,32 +29,28 @@ class Person(Row):
     dict. Commit to the database with sync().
     """
 
+    table_name = 'persons'
+    primary_key = 'person_id'
     fields = {
         'person_id': Parameter(int, "Account identifier"),
-        'first_name': Parameter(str, "Given name", max = 128),
-        'last_name': Parameter(str, "Surname", max = 128),
+        'first_name': Parameter(str, "Given name", max = 128, optional = False),
+        'last_name': Parameter(str, "Surname", max = 128, optional = False),
         'title': Parameter(str, "Title", max = 128),
-        'email': Parameter(str, "Primary e-mail address", max = 254),
+        'email': Parameter(str, "Primary e-mail address", max = 254, optional = False),
         'phone': Parameter(str, "Telephone number", max = 64),
         'url': Parameter(str, "Home page", max = 254),
         'bio': Parameter(str, "Biography", max = 254),
         'enabled': Parameter(bool, "Has been enabled"),
-        'deleted': Parameter(bool, "Has been deleted"),
-        '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"),
-        'role_ids': Parameter([int], "List of role identifiers"),
-        'roles': Parameter([str], "List of roles"),
-        'site_ids': Parameter([int], "List of site identifiers"),
-        'address_ids': Parameter([int], "List of address identifiers"),
-        'key_ids': Parameter([int], "List of key identifiers"),
-        # 'slice_ids': Parameter([int], "List of slice identifiers"),
+        'password': Parameter(str, "Account password in crypt() form", max = 254, optional = False),
+        'last_updated': Parameter(str, "Date and time of last update", ro = True),
+        'date_created': Parameter(str, "Date and time when account was created", ro = True),
+        'role_ids': Parameter([int], "List of role identifiers", ro = True),
+        'roles': Parameter([str], "List of roles", ro = True),
+        'site_ids': Parameter([int], "List of site identifiers", ro = True),
+        'key_ids': Parameter([int], "List of key identifiers", ro = True),
+        'slice_ids': Parameter([int], "List of slice identifiers", ro = True),
         }
 
-    def __init__(self, api, fields):
-        Row.__init__(self, fields)
-        self.api = api
-
     def validate_email(self, email):
         """
         Validate email address. Stolen from Mailman.
@@ -87,7 +81,7 @@ class Person(Row):
 
         conflicts = Persons(self.api, [email])
         for person_id, person in conflicts.iteritems():
-            if not person['deleted'] and ('person_id' not in self or self['person_id'] != person_id):
+            if 'person_id' not in self or self['person_id'] != person_id:
                 raise PLCInvalidArgument, "E-mail address already in use"
 
         return email
@@ -165,15 +159,15 @@ class Person(Row):
         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.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):
@@ -184,17 +178,62 @@ class Person(Row):
         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.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']
+
+        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)
 
     def set_primary_site(self, site, commit = True):
         """
@@ -225,65 +264,18 @@ 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()))
-
-        # 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 all addresses
-        addresses = Addresses(self.api, self['address_ids'])
-        for address in addresses.values():
-            address.delete(commit = False)
-
         # Delete all keys
         keys = Keys(self.api, self['key_ids'])
         for key in keys.values():
             key.delete(commit = False)
 
         # Clean up miscellaneous join tables
-        for table in ['person_role', 'person_site']:
+        for table in ['person_role', 'person_site', 'slice_person']:
             self.api.db.do("DELETE FROM %s" \
                            " WHERE person_id = %d" % \
                            (table, self['person_id']))
@@ -300,14 +292,11 @@ class Persons(Table):
     non-deleted accounts.
     """
 
-    def __init__(self, api, person_id_or_email_list = None, fields = Person.fields, deleted = False, enabled = None):
+    def __init__(self, api, person_id_or_email_list = None, enabled = None):
         self.api = api
 
-        sql = "SELECT %s FROM view_persons WHERE TRUE" % \
-              ", ".join(fields)
-
-        if deleted is not None:
-            sql += " AND deleted IS %(deleted)s"
+        sql = "SELECT %s FROM view_persons WHERE deleted IS False" % \
+              ", ".join(Person.fields)
 
         if enabled is not None:
             sql += " AND enabled IS %(enabled)s"
@@ -323,14 +312,14 @@ class Persons(Table):
                 sql += " OR person_id IN (%s)" % ", ".join(map(str, person_ids))
             if emails:
                 # Case insensitive e-mail address comparison
-                sql += " OR lower(email) IN (%s)" % ", ".join(api.db.quote(emails)).lower()
+                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', 'address_ids', 'key_ids':
+            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: