[pkg] packaging and path changes
[pixelated-user-agent.git] / service / src / pixelated / resources / __init__.py
1 #
2 # Copyright (c) 2014 ThoughtWorks, Inc.
3 #
4 # Pixelated is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # Pixelated is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
16
17 import json
18 import os
19
20 from twisted.web.http import UNAUTHORIZED
21 from twisted.web.resource import Resource
22 from twisted.logger import Logger
23
24 from pixelated.resources.session import IPixelatedSession
25
26 from twisted.web.http import INTERNAL_SERVER_ERROR, SERVICE_UNAVAILABLE
27
28 log = Logger()
29
30
31 STATIC = None
32
33
34 class SetEncoder(json.JSONEncoder):
35     def default(self, obj):
36         if isinstance(obj, set):
37             return list(obj)
38         return super(SetEncoder, self).default(obj)
39
40
41 def respond_json(entity, request, status_code=200):
42     json_response = json.dumps(entity, cls=SetEncoder)
43     request.responseHeaders.setRawHeaders(b"content-type", [b"application/json"])
44     request.code = status_code
45     return json_response
46
47
48 def respond_json_deferred(entity, request, status_code=200):
49     json_response = json.dumps(entity, cls=SetEncoder)
50     request.responseHeaders.setRawHeaders(b"content-type", [b"application/json"])
51     request.code = status_code
52     request.write(json_response)
53     request.finish()
54
55
56 def handle_error_deferred(e, request):
57     log.error(e)
58     request.setResponseCode(INTERNAL_SERVER_ERROR)
59     request.write('Something went wrong!')
60     request.finish()
61
62
63 def set_static_folder(static_folder):
64     global STATIC
65     STATIC = static_folder
66
67
68 def get_protected_static_folder(static_folder=None):
69     static = static_folder or _get_static_folder()
70     return os.path.join(static, 'protected')
71
72
73 def get_public_static_folder(static_folder=None):
74     static = static_folder or _get_static_folder()
75     return os.path.join(static, 'public')
76
77
78 def _get_static_folder():
79     if not STATIC:
80         static_folder = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", "..", "..", "web-ui", "dist"))
81         if not os.path.exists(static_folder):
82             static_folder = os.path.join('/', 'usr', 'share', 'pixelated-user-agent')
83     else:
84         static_folder = STATIC
85     return static_folder
86
87
88 class BaseResource(Resource):
89
90     def __init__(self, services_factory):
91         Resource.__init__(self)
92         self._services_factory = services_factory
93
94     def _get_user_id_from_request(self, request):
95         if self._services_factory.mode.is_single_user:
96             return None  # it doesn't matter
97         session = self.get_session(request)
98         if session.is_logged_in():
99             return session.user_uuid
100         raise ValueError('Not logged in')
101
102     def is_logged_in(self, request):
103         session = self.get_session(request)
104         return session.is_logged_in() and self._services_factory.has_session(session.user_uuid)
105
106     def get_session(self, request):
107         return IPixelatedSession(request.getSession())
108
109     def is_admin(self, request):
110         services = self._services(request)
111         return services._leap_session.user_auth.is_admin()
112
113     def _services(self, request):
114         user_id = self._get_user_id_from_request(request)
115         return self._services_factory.services(user_id)
116
117     def _service(self, request, attribute):
118         return getattr(self._services(request), attribute)
119
120     def keymanager(self, request):
121         return self._service(request, 'keymanager')
122
123     def mail_service(self, request):
124         return self._service(request, 'mail_service')
125
126     def search_engine(self, request):
127         return self._service(request, 'search_engine')
128
129     def draft_service(self, request):
130         return self._service(request, 'draft_service')
131
132     def feedback_service(self, request):
133         return self._service(request, 'feedback_service')
134
135     def soledad(self, request):
136         return self._service(request, '_leap_session').soledad
137
138
139 class UnAuthorizedResource(Resource):
140
141     def __init__(self):
142         Resource.__init__(self)
143
144     def render_GET(self, request):
145         request.setResponseCode(UNAUTHORIZED)
146         return "Unauthorized!"
147
148     def render_POST(self, request):
149         request.setResponseCode(UNAUTHORIZED)
150         return "Unauthorized!"
151
152
153 class UnavailableResource(Resource):
154     def __init__(self):
155         Resource.__init__(self)
156
157     def render(self, request):
158         request.setResponseCode(SERVICE_UNAVAILABLE)
159         return "Service Unavailable"