a slightly clearer version of GetSliceFamily
[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     def call(self, auth, role_id_or_name, person_id_or_email):
31         # Get role
32         roles = Roles(self.api, [role_id_or_name])
33         if not roles:
34             raise PLCInvalidArgument, "Invalid role '%s'" % unicode(role_id_or_name)
35         role = roles[0]
36
37         # Get account information
38         persons = Persons(self.api, [person_id_or_email])
39         if not persons:
40             raise PLCInvalidArgument, "No such account"
41         person = persons[0]
42
43         if person['peer_id'] is not None:
44             raise PLCInvalidArgument, "Not a local account"
45
46         # Authenticated function
47         assert self.caller is not None
48
49         # Check if we can update this account
50         if not self.caller.can_update(person):
51             raise PLCPermissionDenied, "Not allowed to update specified account"
52
53         # Can only grant lesser (higher) roles to others
54         if 'admin' not in self.caller['roles'] and \
55            role['role_id'] <= min(self.caller['role_ids']):
56             raise PLCInvalidArgument, "Not allowed to grant that role"
57
58         if role['role_id'] not in person['role_ids']:
59             person.add_role(role)
60
61         self.event_objects = {'Person': [person['person_id']],
62                               'Role': [role['role_id']]}
63         self.message = "Role %d granted to person %d" % \
64                        (role['role_id'], person['person_id'])
65
66         return 1