pam: use a pam object method instead of pam module function
[cascardo/ipsilon.git] / ipsilon / rest / common.py
1 # Copyright (C) 2015 Ipsilon project Contributors, for license see COPYING
2
3 import cherrypy
4 import json
5 import logging
6 from functools import wraps
7 from ipsilon.util.endpoint import Endpoint
8
9
10 def jsonout(func):
11     """
12     JSON output decorator. Does not handle binary data.
13     """
14     @wraps(func)
15     def wrapper(*args, **kw):
16         value = func(*args, **kw)
17         cherrypy.response.headers["Content-Type"] = \
18             "application/json;charset=utf-8"
19         return json.dumps(value, sort_keys=True, indent=2)
20
21     return wrapper
22
23
24 def rest_error(status=500, message=''):
25     """
26     Create a REST error response.
27
28     The assumption is that the jsonout wrapper will handle converting
29     the response to JSON.
30     """
31     cherrypy.response.status = status
32     cherrypy.response.headers['Content-Type'] = 'application/json'
33     return {'status': status, 'message': message}
34
35
36 class RestPage(Endpoint):
37
38     def __init__(self, *args, **kwargs):
39         super(RestPage, self).__init__(*args, **kwargs)
40         self.auth_protect = True
41
42
43 class RestPlugins(RestPage):
44     def __init__(self, name, site, parent, facility, ordered=True):
45         super(RestPlugins, self).__init__(site)
46         self._master = parent
47         self.name = name
48         self.title = '%s plugins' % name
49         self.url = '%s/%s' % (parent.url, name)
50         self.facility = facility
51         self.template = None
52         self.order = None
53         parent.add_subtree(name, self)
54
55         for plugin in self._site[facility].available:
56             obj = self._site[facility].available[plugin]
57             if hasattr(obj, 'rest'):
58                 cherrypy.log.error('Rest plugin: %s' % plugin,
59                                    severity=logging.DEBUG)
60                 obj.rest.mount(self)
61
62     def root_with_msg(self, message=None, message_type=None, changed=None):
63         return None
64
65     def root(self, *args, **kwargs):
66         return self.root_with_msg()
67
68
69 class Rest(RestPage):
70
71     def __init__(self, site, mount):
72         super(Rest, self).__init__(site)
73         self.title = None
74         self.mount = mount
75         self.url = '%s/%s' % (self.basepath, mount)
76         self.menu = [self]
77
78     @jsonout
79     def root(self, *args, **kwargs):
80         return rest_error(404, 'Not Found')
81
82     def add_subtree(self, name, page):
83         self.__dict__[name] = page
84
85     def del_subtree(self, name):
86         del self.__dict__[name]