662250cfc7d5bc5c19108cabbfcd60d63c5782e7
[plcapi.git] / PLC / Methods / AddSiteAddress.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Addresses import Address, Addresses
5 from PLC.Auth import PasswordAuth
6 from PLC.Sites import Site, Sites
7
8 can_update = lambda (field, value): field in \
9              ['line1', 'line2', 'line3',
10               'city', 'state', 'postalcode', 'country']
11
12 class AddSiteAddress(Method):
13     """
14     Adds a new address to a site. Fields specified in
15     address_fields are used; some are not optional.
16
17     PIs may only add addresses to their own sites.
18
19     Returns the new address_id (> 0) if successful, faults otherwise.
20     """
21
22     roles = ['admin', 'pi']
23
24     update_fields = dict(filter(can_update, Address.fields.items()))
25
26     accepts = [
27         PasswordAuth(),
28         Mixed(Site.fields['site_id'],
29               Site.fields['login_base']),
30         update_fields
31         ]
32
33     returns = Parameter(int, 'New address_id (> 0) if successful')
34
35     event_type = 'Add'
36     object_type = 'Address'
37     object_ids = []
38
39     def call(self, auth, site_id_or_login_base, address_fields = {}):
40         address_fields = dict(filter(can_update, address_fields.items()))
41
42         # Get associated site details
43         sites = Sites(self.api, [site_id_or_login_base]).values()
44         if not sites:
45             raise PLCInvalidArgument, "No such site"
46         site = sites[0]
47
48         if 'admin' not in self.caller['roles']:
49             if site['site_id'] not in self.caller['site_ids']:
50                 raise PLCPermissionDenied, "Address must be associated with one of your sites"
51
52         address = Address(self.api, address_fields)
53         address['site_id'] = site['site_id']
54         address.sync()
55         self.object_ids = [address['address_id']]
56
57         return address['address_id']