Enhance JSON page to optionally require a form password.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / ajax / JsonPage.java
index 20ddfc6..6b5d614 100644 (file)
@@ -17,6 +17,7 @@
 
 package net.pterodactylus.sone.web.ajax;
 
+import net.pterodactylus.sone.web.WebInterface;
 import net.pterodactylus.sone.web.page.Page;
 import net.pterodactylus.util.json.JsonObject;
 import net.pterodactylus.util.json.JsonUtils;
@@ -32,14 +33,20 @@ public abstract class JsonPage implements Page {
        /** The path of the page. */
        private final String path;
 
+       /** The Sone web interface. */
+       protected final WebInterface webInterface;
+
        /**
         * Creates a new JSON page at the given path.
         *
         * @param path
         *            The path of the page
+        * @param webInterface
+        *            The Sone web interface
         */
-       public JsonPage(String path) {
+       public JsonPage(String path, WebInterface webInterface) {
                this.path = path;
+               this.webInterface = webInterface;
        }
 
        //
@@ -56,6 +63,17 @@ public abstract class JsonPage implements Page {
         */
        protected abstract JsonObject createJsonObject(Request request);
 
+       /**
+        * Returns whether this command needs the form password for authentication
+        * and to prevent abuse.
+        *
+        * @return {@code true} if the form password (given as “formPassword”) is
+        *         required, {@code false} otherwise
+        */
+       protected boolean needsFormPassword() {
+               return true;
+       }
+
        //
        // PAGE METHODS
        //
@@ -73,6 +91,12 @@ public abstract class JsonPage implements Page {
         */
        @Override
        public Response handleRequest(Request request) {
+               if (needsFormPassword()) {
+                       String formPassword = request.getHttpRequest().getParam("formPassword");
+                       if (!webInterface.formPassword().equals(formPassword)) {
+                               return new Response(401, "Not authorized", "application/json", JsonUtils.format(new JsonObject().put("success", false)));
+                       }
+               }
                JsonObject jsonObject = createJsonObject(request);
                return new Response(200, "OK", "application/json", JsonUtils.format(jsonObject));
        }