(most) all functions now take SessionAuth in addition to PasswordAuth
[plcapi.git] / PLC / Roles.py
1 #
2 # Functions for interacting with the roles table in the database
3 #
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
6 #
7 # $Id: Roles.py,v 1.5 2006/10/20 17:53:54 mlhuang Exp $
8 #
9
10 from types import StringTypes
11 from PLC.Faults import *
12 from PLC.Parameter import Parameter
13 from PLC.Table import Row, Table
14
15 class Role(Row):
16     """
17     Representation of a row in the roles table. To use,
18     instantiate with a dict of values.
19     """
20
21     table_name = 'roles'
22     primary_key = 'role_id'
23     join_tables = ['person_role', ('slice_attribute_types', 'min_role_id')]
24     fields = {
25         'role_id': Parameter(int, "Role identifier"),
26         'name': Parameter(str, "Role", max = 100),
27         }
28
29     def validate_role_id(self, role_id):
30         # Make sure role does not already exist
31         conflicts = Roles(self.api, [role_id])
32         if conflicts:
33             raise PLCInvalidArgument, "Role ID already in use"
34
35         return role_id
36
37     def validate_name(self, name):
38         # Make sure name is not blank
39         if not len(name):
40             raise PLCInvalidArgument, "Role must be specified"
41         
42         # Make sure role does not already exist
43         conflicts = Roles(self.api, [name])
44         if conflicts:
45             raise PLCInvalidArgument, "Role name already in use"
46
47         return name
48
49 class Roles(Table):
50     """
51     Representation of the roles table in the database.
52     """
53
54     def __init__(self, api, role_id_or_name_list = None):
55         sql = "SELECT %s FROM roles" % \
56               ", ".join(Role.fields)
57         
58         if role_id_or_name_list:
59             # Separate the list into integers and strings
60             role_ids = filter(lambda role_id: isinstance(role_id, (int, long)),
61                                    role_id_or_name_list)
62             names = filter(lambda name: isinstance(name, StringTypes),
63                            role_id_or_name_list)
64             sql += " WHERE (False"
65             if role_ids:
66                 sql += " OR role_id IN (%s)" % ", ".join(map(str, role_ids))
67             if names:
68                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
69             sql += ")"
70
71         rows = api.db.selectall(sql)
72
73         for row in rows:
74             self[row['role_id']] = Role(api, row)