Initial checkin of new API implementation
[plcapi.git] / PLC / Methods / AdmGrantRoleToPerson.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 AdmGrantRoleToPerson(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         PasswordAuth(),
22         Mixed(Person.fields['person_id'],
23               Person.fields['email']),
24         Roles.fields['role_id']
25         ]
26
27     returns = Parameter(int, '1 if successful')
28
29     def call(self, auth, person_id_or_email, role_id):
30         # Get all roles
31         roles = Roles(self.api)
32         if role_id not in roles:
33             raise PLCInvalidArgument, "Invalid role ID"
34
35         # Get account information
36         persons = Persons(self.api, [person_id_or_email])
37         if not persons:
38             raise PLCInvalidArgument, "No such account"
39
40         person = persons.values()[0]
41
42         # Authenticated function
43         assert self.caller is not None
44
45         # Check if we can update this account
46         if not self.caller.can_update(person):
47             raise PLCPermissionDenied, "Not allowed to update specified account"
48
49         # Can only grant lesser (higher) roles to others
50         if 'admin' not in self.caller['roles'] and \
51            role_id <= min(self.caller['role_ids']):
52             raise PLCInvalidArgument, "Not allowed to grant that role"
53
54         if role_id not in person['role_ids']:
55             person_id = person['person_id']
56             self.api.db.do("INSERT INTO person_roles (person_id, role_id)" \
57                            " VALUES(%(person_id)d, %(role_id)d)",
58                            locals())
59
60         return 1