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