diff libervia/server/pages.py @ 1283:436ef2ad92af

pages: moved CSRF checking code to a separate method: `checkCSRF` can now be used to check CSRF, and the token can be put in `X-Csrf-Token` header.
author Goffi <goffi@goffi.org>
date Fri, 19 Jun 2020 16:47:51 +0200
parents 0e4e413eb8db
children 65c43eec15ad
line wrap: on
line diff
--- a/libervia/server/pages.py	Fri Jun 19 16:47:51 2020 +0200
+++ b/libervia/server/pages.py	Fri Jun 19 16:47:51 2020 +0200
@@ -521,6 +521,24 @@
                 else:
                     log.info(_("{page} reloaded").format(page=resource))
 
+    def checkCSRF(self, request):
+        csrf_token = self.host.getSessionData(
+            request, session_iface.ISATSession
+        ).csrf_token
+        given_csrf = request.getHeader("X-Csrf-Token")
+        if given_csrf is None:
+            try:
+                given_csrf = self.getPostedData(request, "csrf_token")
+            except KeyError:
+                pass
+        if given_csrf is None or given_csrf != csrf_token:
+            log.warning(
+                _("invalid CSRF token, hack attempt? URL: {url}, IP: {ip}").format(
+                    url=request.uri, ip=request.getClientIP()
+                )
+            )
+            self.pageError(request, C.HTTP_FORBIDDEN)
+
     def registerURI(self, uri_tuple, get_uri_cb):
         """Register a URI handler
 
@@ -1410,20 +1428,7 @@
         raise failure.Failure(exceptions.CancelError("Post/Redirect/Get is used"))
 
     async def _on_data_post(self, request):
-        csrf_token = self.host.getSessionData(
-            request, session_iface.ISATSession
-        ).csrf_token
-        try:
-            given_csrf = self.getPostedData(request, "csrf_token")
-        except KeyError:
-            given_csrf = None
-        if given_csrf is None or given_csrf != csrf_token:
-            log.warning(
-                _("invalid CSRF token, hack attempt? URL: {url}, IP: {ip}").format(
-                    url=request.uri, ip=request.getClientIP()
-                )
-            )
-            self.pageError(request, C.HTTP_FORBIDDEN)
+        self.checkCSRF(request)
         try:
             ret = await asDeferred(self.on_data_post, self, request)
         except exceptions.DataError as e: