25b54e22908e5366157237d4e04b57f229ef03d3
[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 PasswordAuth
6 from PLC.Roles import 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. ins 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         PasswordAuth(),
22         Mixed(Person.fields['person_id'],
23               Person.fields['email']),
24         Mixed(Parameter(int, "Role identifier"),
25               Parameter(str, "Role name"))
26         ]
27
28     returns = Parameter(int, '1 if successful')
29
30     def call(self, auth, person_id_or_email, role_id_or_name):
31         # Get all roles
32         roles = Roles(self.api)
33         if role_id_or_name not in roles:
34             raise PLCInvalidArgument, "Invalid role identifier or name"
35
36         if isinstance(role_id_or_name, int):
37             role_id = role_id_or_name
38         else:
39             role_id = roles[role_id_or_name]
40
41         # Get account information
42         persons = Persons(self.api, [person_id_or_email])
43         if not persons:
44             raise PLCInvalidArgument, "No such account"
45
46         person = persons.values()[0]
47
48         # Authenticated function
49         assert self.caller is not None
50
51         # Check if we can update this account
52         if not self.caller.can_update(person):
53             raise PLCPermissionDenied, "Not allowed to update specified account"
54
55         # Can only grant lesser (higher) roles to others
56         if 'admin' not in self.caller['roles'] and \
57            role_id <= min(self.caller['role_ids']):
58             raise PLCInvalidArgument, "Not allowed to grant that role"
59
60         if role_id not in person['role_ids']:
61             person.add_role(role_id)
62
63         return 1