61e60720e6a3badce3815940458419d6917848b2
[pixelated-user-agent.git] / service / 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 class SetEncoder(json.JSONEncoder):
32     def default(self, obj):
33         if isinstance(obj, set):
34             return list(obj)
35         return super(SetEncoder, self).default(obj)
36
37
38 def respond_json(entity, request, status_code=200):
39     json_response = json.dumps(entity, cls=SetEncoder)
40     request.responseHeaders.setRawHeaders(b"content-type", [b"application/json"])
41     request.code = status_code
42     return json_response
43
44
45 def respond_json_deferred(entity, request, status_code=200):
46     json_response = json.dumps(entity, cls=SetEncoder)
47     request.responseHeaders.setRawHeaders(b"content-type", [b"application/json"])
48     request.code = status_code
49     request.write(json_response)
50     request.finish()
51
52
53 def handle_error_deferred(e, request):
54     log.error(e)
55     request.setResponseCode(INTERNAL_SERVER_ERROR)
56     request.write('Something went wrong!')
57     request.finish()
58
59
60 def get_protected_static_folder():
61     return os.path.join(_get_static_folder(), 'protected')
62
63
64 def get_public_static_folder():
65     return os.path.join(_get_static_folder(), 'public')
66
67
68 def _get_static_folder():
69     static_folder = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", "..", "..", "web-ui", "dist"))
70     if not os.path.exists(static_folder):
71         static_folder = os.path.join('/', 'usr', 'share', 'pixelated-user-agent')
72     return static_folder
73
74
75 class BaseResource(Resource):
76
77     def __init__(self, services_factory):
78         Resource.__init__(self)
79         self._services_factory = services_factory
80
81     def _get_user_id_from_request(self, request):
82         if self._services_factory.mode.is_single_user:
83             return None  # it doesn't matter
84         session = self.get_session(request)
85         if session.is_logged_in():
86             return session.user_uuid
87         raise ValueError('Not logged in')
88
89     def is_logged_in(self, request):
90         session = self.get_session(request)
91         return session.is_logged_in() and self._services_factory.has_session(session.user_uuid)
92
93     def get_session(self, request):
94         return IPixelatedSession(request.getSession())
95
96     def is_admin(self, request):
97         services = self._services(request)
98         return services._leap_session.user_auth.is_admin()
99
100     def _services(self, request):
101         user_id = self._get_user_id_from_request(request)
102         return self._services_factory.services(user_id)
103
104     def _service(self, request, attribute):
105         return getattr(self._services(request), attribute)
106
107     def keymanager(self, request):
108         return self._service(request, 'keymanager')
109
110     def mail_service(self, request):
111         return self._service(request, 'mail_service')
112
113     def search_engine(self, request):
114         return self._service(request, 'search_engine')
115
116     def draft_service(self, request):
117         return self._service(request, 'draft_service')
118
119     def feedback_service(self, request):
120         return self._service(request, 'feedback_service')
121
122     def soledad(self, request):
123         return self._service(request, '_leap_session').soledad
124
125
126 class UnAuthorizedResource(Resource):
127
128     def __init__(self):
129         Resource.__init__(self)
130
131     def render_GET(self, request):
132         request.setResponseCode(UNAUTHORIZED)
133         return "Unauthorized!"
134
135     def render_POST(self, request):
136         request.setResponseCode(UNAUTHORIZED)
137         return "Unauthorized!"
138
139
140 class UnavailableResource(Resource):
141     def __init__(self):
142         Resource.__init__(self)
143
144     def render(self, request):
145         request.setResponseCode(SERVICE_UNAVAILABLE)
146         return "Service Unavailable"