Coverage for webapp/decorators.py: 90%
42 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-27 22:07 +0000
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-27 22:07 +0000
1# Core packages
2import os
3import functools
4from distutils.util import strtobool
6# Third party packages
7import flask
8from webapp import authentication
9from webapp.helpers import param_redirect_capture, param_redirect_exec
12def cached_redirect(func):
13 """
14 Decorator that check for a param_redirect cookie and redirects
15 to the appropriate URL.
16 """
18 @functools.wraps(func)
19 def param_redirect(*args, **kwargs):
20 resp = param_redirect_exec(
21 req=flask.request,
22 make_response=flask.make_response,
23 redirect=flask.redirect,
24 )
25 if resp:
26 return resp
27 return func(*args, **kwargs)
29 return param_redirect
32def login_required(func):
33 """
34 Decorator that checks if a user is logged in, and redirects
35 to login page if not.
36 """
38 @functools.wraps(func)
39 def is_user_logged_in(*args, **kwargs):
40 if not authentication.is_authenticated(flask.session):
41 response = flask.make_response(
42 flask.redirect("/login?next=" + flask.request.path)
43 )
45 response = param_redirect_capture(flask.request, response)
47 return response
49 return func(*args, **kwargs)
51 return is_user_logged_in
54def store_maintenance(func):
55 """
56 Decorator that checks if the maintence mode is enabled
57 """
59 @functools.wraps(func)
60 def is_store_in_maintenance(*args, **kwargs):
61 # TODO: this will be a config option for the charm
62 # or used from the app config using from_prefexed_env
63 if strtobool(os.getenv("MAINTENANCE", "false")):
64 return flask.render_template("maintenance.html")
66 return func(*args, **kwargs)
68 return is_store_in_maintenance
71def redirect_uppercase_to_lowercase(func):
72 """
73 Decorator that redirect package names containing upper case
74 to the lower case URL
76 The route must have the entity_name parameter
77 """
79 @functools.wraps(func)
80 def is_uppercase(*args, **kwargs):
81 name = kwargs["entity_name"]
83 ENV = os.getenv("ENVIRONMENT", "devel").strip()
84 redirect = flask.request.url.lower()
86 if any(char.isupper() for char in name):
87 if (
88 (ENV == "devel" and redirect.startswith("http://localhost:"))
89 or (
90 ENV == "production"
91 and redirect.startswith("https://charmhub.io/")
92 )
93 or (
94 ENV == "staging"
95 and redirect.startswith("https://staging.charmhub.io/")
96 )
97 ):
98 return flask.redirect(redirect)
99 else:
100 flask.abort(404)
102 return func(*args, **kwargs)
104 return is_uppercase