From 0b4e522088f896ec5fd57add68db30a8b0674fce Mon Sep 17 00:00:00 2001 From: Arne Gudermann Date: Fri, 7 Jun 2024 12:04:34 +0200 Subject: [PATCH] Add redirect map and handler --- src/viur/core/config.py | 6 ++++++ src/viur/core/request.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/viur/core/config.py b/src/viur/core/config.py index 043d63c0f..8f5714671 100644 --- a/src/viur/core/config.py +++ b/src/viur/core/config.py @@ -701,6 +701,12 @@ class Conf(ConfigType): } """Describing the Script module""" + redirect_map = {} + """Map for redirect Urls""" + + redirect_map_advanced_mode = False + """If True the fnmatch is activated for key match""" + render_html_download_url_expiration: t.Optional[float | int] = None """The default duration, for which downloadURLs generated by the html renderer will stay valid""" diff --git a/src/viur/core/request.py b/src/viur/core/request.py index 916a850b0..87546b5c5 100644 --- a/src/viur/core/request.py +++ b/src/viur/core/request.py @@ -83,6 +83,7 @@ class Router: The basic control flow is - Setting up internal variables - Running the Request validators + - Check the Redirect Map - Emitting the headers (especially the security related ones) - Run the TLS check (ensure it's a secure connection or check if the URL is whitelisted) - Load or initialize a new session @@ -227,6 +228,21 @@ def _process(self): path = self.request.path + if conf.redirect_map: + if conf.redirect_map_advanced_mode: + for k in conf.redirect_map.keys(): + if fnmatch.fnmatch(path, k): + self.response.status = "302 Redirect" + self.response.headers['Location'] = conf.redirect_map[k] + self.response.write("Redirect") + return + + if redirect_url := conf.redirect_map.get(path): + self.response.status = "302 Redirect" + self.response.headers['Location'] = redirect_url + self.response.write("Redirect") + return + # Add CSP headers early (if any) if conf.security.content_security_policy and conf.security.content_security_policy["_headerCache"]: for k, v in conf.security.content_security_policy["_headerCache"].items():