4cc08f24ecd7f083d0f4d91591e6a1e0a84cbce1
[plcapi.git] / PLC / Methods / AddRoleToPerson.py
1 # $Id$
2 from PLC.Faults import *
3 from PLC.Method import Method
4 from PLC.Parameter import Parameter, Mixed
5 from PLC.Persons import Person, Persons
6 from PLC.Auth import Auth
7 from PLC.Roles import Role, Roles
8
9 class AddRoleToPerson(Method):
10     """
11     Grants the specified role to the person.
12     
13     PIs can only grant the tech and user roles to users and techs at
14     their sites. Admins can grant any role to any user.
15
16     Returns 1 if successful, faults otherwise.
17     """
18
19     roles = ['admin', 'pi']
20
21     accepts = [
22         Auth(),
23         Mixed(Role.fields['role_id'],
24               Role.fields['name']),
25         Mixed(Person.fields['person_id'],
26               Person.fields['email']),
27         ]
28
29     returns = Parameter(int, '1 if successful')
30
31     def call(self, auth, role_id_or_name, person_id_or_email):
32         # Get role
33         roles = Roles(self.api, [role_id_or_name])
34         if not roles:
35             raise PLCInvalidArgument, "Invalid role '%s'" % unicode(role_id_or_name)
36         role = roles[0]
37
38         # Get account information
39         persons = Persons(self.api, [person_id_or_email])
40         if not persons:
41             raise PLCInvalidArgument, "No such account"
42         person = persons[0]
43
44         if person['peer_id'] is not None:
45             raise PLCInvalidArgument, "Not a local account"
46
47         # Authenticated function
48         assert self.caller is not None
49
50         # Check if we can update this account
51         if not self.caller.can_update(person):
52             raise PLCPermissionDenied, "Not allowed to update specified account"
53
54         # Can only grant lesser (higher) roles to others
55         if 'admin' not in self.caller['roles'] and \
56            role['role_id'] <= min(self.caller['role_ids']):
57             raise PLCInvalidArgument, "Not allowed to grant that role"
58
59         if role['role_id'] not in person['role_ids']:
60             person.add_role(role)
61
62         self.event_objects = {'Person': [person['person_id']],
63                               'Role': [role['role_id']]}
64         self.message = "Role %d granted to person %d" % \
65                        (role['role_id'], person['person_id'])
66
67         return 1