Initial checkin of new API implementation
[plcapi.git] / PLC / Methods / AdmSetPersonPrimarySite.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.Sites import Site, Sites
6 from PLC.Auth import PasswordAuth
7
8 class AdmSetPersonPrimarySite(Method):
9     """
10     Makes the specified site the person's primary site. The person
11     must already be a member of the site.
12
13     Admins may update anyone. All others may only update themselves.
14     """
15
16     roles = ['admin', 'pi', 'user', 'tech']
17
18     accepts = [
19         PasswordAuth(),
20         Mixed(Person.fields['person_id'],
21               Person.fields['email']),
22         Mixed(Site.fields['site_id'],
23               Site.fields['login_base'])
24         ]
25
26     returns = Parameter(int, '1 if successful')
27
28     def call(self, auth, person_id_or_email, site_id_or_login_base):
29         # Get account information
30         persons = Persons(self.api, [person_id_or_email])
31         if not persons:
32             raise PLCInvalidArgument, "No such account"
33
34         person = persons.values()[0]
35
36         # Authenticated function
37         assert self.caller is not None
38
39         # Non-admins can only update their own primary site
40         if 'admin' not in self.caller['roles'] and \
41            self.caller['person_id'] != person['person_id']:
42             raise PLCPermissionDenied, "Not allowed to update specified account"
43
44         # Get site information
45         sites = Sites(self.api, [site_id_or_login_base])
46         if not sites:
47             raise PLCInvalidArgument, "No such site"
48
49         site = sites.values()[0]
50
51         if site['site_id'] not in person['site_ids']:
52             raise PLCInvalidArgument, "Not a member of the specified site"
53
54         person_id = person['person_id']
55         site_id = site['site_id']
56         self.api.db.do("UPDATE person_site SET is_primary = False" \
57                        " WHERE person_id = %(person_id)d",
58                        locals())
59         self.api.db.do("UPDATE person_site SET is_primary = True" \
60                        " WHERE person_id = %(person_id)d" \
61                        " AND site_id = %(site_id)d",
62                        locals())
63
64         return 1