Merge branch 'release-0.9.6'
[Sone.git] / src / main / java / net / pterodactylus / sone / web / ajax / JsonPage.java
1 /*
2  * Sone - JsonPage.java - Copyright © 2010–2016 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU 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  * This program 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 General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web.ajax;
19
20 import static java.util.logging.Logger.getLogger;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.net.URI;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.web.WebInterface;
32 import net.pterodactylus.sone.web.page.FreenetPage;
33 import net.pterodactylus.sone.web.page.FreenetRequest;
34 import net.pterodactylus.util.io.Closer;
35 import net.pterodactylus.util.web.Page;
36 import net.pterodactylus.util.web.Response;
37
38 import com.fasterxml.jackson.databind.ObjectMapper;
39 import freenet.clients.http.SessionManager.Session;
40 import freenet.clients.http.ToadletContext;
41
42 /**
43  * A JSON page is a specialized {@link Page} that will always return a JSON
44  * object to the browser, e.g. for use with AJAX or other scripting frameworks.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public abstract class JsonPage implements FreenetPage {
49
50         /** The logger. */
51         private static final Logger logger = getLogger(JsonPage.class.getName());
52
53         /** The JSON serializer. */
54         private static final ObjectMapper objectMapper = new ObjectMapper();
55
56         /** The path of the page. */
57         private final String path;
58
59         /** The Sone web interface. */
60         protected final WebInterface webInterface;
61
62         /**
63          * Creates a new JSON page at the given path.
64          *
65          * @param path
66          *            The path of the page
67          * @param webInterface
68          *            The Sone web interface
69          */
70         public JsonPage(String path, WebInterface webInterface) {
71                 this.path = path;
72                 this.webInterface = webInterface;
73         }
74
75         //
76         // ACCESSORS
77         //
78
79         /**
80          * Returns the current session, creating a new session if there is no
81          * current session.
82          *
83          * @param toadletContenxt
84          *            The toadlet context
85          * @return The current session, or {@code null} if there is no current
86          *         session
87          */
88         protected Session getCurrentSession(ToadletContext toadletContenxt) {
89                 return webInterface.getCurrentSession(toadletContenxt);
90         }
91
92         /**
93          * Returns the current session, creating a new session if there is no
94          * current session and {@code create} is {@code true}.
95          *
96          * @param toadletContenxt
97          *            The toadlet context
98          * @param create
99          *            {@code true} to create a new session if there is no current
100          *            session, {@code false} otherwise
101          * @return The current session, or {@code null} if there is no current
102          *         session
103          */
104         protected Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
105                 return webInterface.getCurrentSession(toadletContenxt, create);
106         }
107
108         /**
109          * Returns the currently logged in Sone.
110          *
111          * @param toadletContext
112          *            The toadlet context
113          * @return The currently logged in Sone, or {@code null} if no Sone is
114          *         currently logged in
115          */
116         protected Sone getCurrentSone(ToadletContext toadletContext) {
117                 return webInterface.getCurrentSone(toadletContext);
118         }
119
120         /**
121          * Returns the currently logged in Sone.
122          *
123          * @param toadletContext
124          *            The toadlet context
125          * @param create
126          *            {@code true} to create a new session if no session exists,
127          *            {@code false} to not create a new session
128          * @return The currently logged in Sone, or {@code null} if no Sone is
129          *         currently logged in
130          */
131         protected Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
132                 return webInterface.getCurrentSone(toadletContext, create);
133         }
134
135         //
136         // METHODS FOR SUBCLASSES TO OVERRIDE
137         //
138
139         /**
140          * This method is called to create the JSON object that is returned back to
141          * the browser.
142          *
143          * @param request
144          *            The request to handle
145          * @return The created JSON object
146          */
147         protected abstract JsonReturnObject createJsonObject(FreenetRequest request);
148
149         /**
150          * Returns whether this command needs the form password for authentication
151          * and to prevent abuse.
152          *
153          * @return {@code true} if the form password (given as “formPassword”) is
154          *         required, {@code false} otherwise
155          */
156         @SuppressWarnings("static-method")
157         protected boolean needsFormPassword() {
158                 return true;
159         }
160
161         /**
162          * Returns whether this page requires the user to be logged in.
163          *
164          * @return {@code true} if the user needs to be logged in to use this page,
165          *         {@code false} otherwise
166          */
167         @SuppressWarnings("static-method")
168         protected boolean requiresLogin() {
169                 return true;
170         }
171
172         //
173         // PROTECTED METHODS
174         //
175
176         /**
177          * Creates a success reply.
178          *
179          * @return A reply signaling success
180          */
181         protected static JsonReturnObject createSuccessJsonObject() {
182                 return new JsonReturnObject(true);
183         }
184
185         /**
186          * Creates an error reply.
187          *
188          * @param error
189          *            The error that has occured
190          * @return The JSON object, signalling failure and the error code
191          */
192         protected static JsonReturnObject createErrorJsonObject(String error) {
193                 return new JsonErrorReturnObject(error);
194         }
195
196         //
197         // PAGE METHODS
198         //
199
200         /**
201          * {@inheritDoc}
202          */
203         @Override
204         public String getPath() {
205                 return path;
206         }
207
208         /**
209          * {@inheritDoc}
210          */
211         @Override
212         public boolean isPrefixPage() {
213                 return false;
214         }
215
216         /**
217          * {@inheritDoc}
218          */
219         @Override
220         public Response handleRequest(FreenetRequest request, Response response) throws IOException {
221                 if (webInterface.getCore().getPreferences().isRequireFullAccess() && !request.getToadletContext().isAllowedFullAccess()) {
222                         return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
223                 }
224                 if (needsFormPassword()) {
225                         String formPassword = request.getHttpRequest().getParam("formPassword");
226                         if (!webInterface.getFormPassword().equals(formPassword)) {
227                                 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
228                         }
229                 }
230                 if (requiresLogin()) {
231                         if (getCurrentSone(request.getToadletContext(), false) == null) {
232                                 return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(objectMapper.writeValueAsString(new JsonErrorReturnObject("auth-required")));
233                         }
234                 }
235                 try {
236                         JsonReturnObject jsonObject = createJsonObject(request);
237                         return response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(objectMapper.writeValueAsString(jsonObject));
238                 } catch (Exception e1) {
239                         logger.log(Level.WARNING, "Error executing JSON page!", e1);
240                         return response.setStatusCode(500).setStatusText(e1.getMessage()).setContentType("text/plain").write(dumpStackTrace(e1));
241                 }
242         }
243
244         /**
245          * {@inheritDoc}
246          */
247         @Override
248         public boolean isLinkExcepted(URI link) {
249                 return false;
250         }
251
252         //
253         // PRIVATE METHODS
254         //
255
256         /**
257          * Returns a byte array containing the stack trace of the given throwable.
258          *
259          * @param t
260          *            The throwable whose stack trace to dump into an array
261          * @return The array with the stack trace, or an empty array if the stack
262          *         trace could not be dumped
263          */
264         private static byte[] dumpStackTrace(Throwable t) {
265                 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
266                 OutputStreamWriter writer = null;
267                 PrintWriter printWriter = null;
268                 try {
269                         writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8");
270                         printWriter = new PrintWriter(writer);
271                         t.printStackTrace(printWriter);
272                         byteArrayOutputStream.flush();
273                         return byteArrayOutputStream.toByteArray();
274                 } catch (IOException ioe1) {
275                         /* quite not possible. */
276                         return new byte[0];
277                 } finally {
278                         Closer.close(printWriter);
279                         Closer.close(writer);
280                         Closer.close(byteArrayOutputStream);
281                 }
282         }
283
284 }