Coverage for webapp/decorators.py: 90%

42 statements  

« 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 

5 

6# Third party packages 

7import flask 

8from webapp import authentication 

9from webapp.helpers import param_redirect_capture, param_redirect_exec 

10 

11 

12def cached_redirect(func): 

13 """ 

14 Decorator that check for a param_redirect cookie and redirects 

15 to the appropriate URL. 

16 """ 

17 

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) 

28 

29 return param_redirect 

30 

31 

32def login_required(func): 

33 """ 

34 Decorator that checks if a user is logged in, and redirects 

35 to login page if not. 

36 """ 

37 

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 ) 

44 

45 response = param_redirect_capture(flask.request, response) 

46 

47 return response 

48 

49 return func(*args, **kwargs) 

50 

51 return is_user_logged_in 

52 

53 

54def store_maintenance(func): 

55 """ 

56 Decorator that checks if the maintence mode is enabled 

57 """ 

58 

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") 

65 

66 return func(*args, **kwargs) 

67 

68 return is_store_in_maintenance 

69 

70 

71def redirect_uppercase_to_lowercase(func): 

72 """ 

73 Decorator that redirect package names containing upper case 

74 to the lower case URL 

75 

76 The route must have the entity_name parameter 

77 """ 

78 

79 @functools.wraps(func) 

80 def is_uppercase(*args, **kwargs): 

81 name = kwargs["entity_name"] 

82 

83 ENV = os.getenv("ENVIRONMENT", "devel").strip() 

84 redirect = flask.request.url.lower() 

85 

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) 

101 

102 return func(*args, **kwargs) 

103 

104 return is_uppercase