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