Merge branch 'weblate-gnu-mailman-postorius' into 'master'
[mailman-postorious.git] / src / postorius / auth / decorators.py
bloba5fa29bf027ccc304fbde981ea14ec5939b4283c
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 1998-2023 by the Free Software Foundation, Inc.
4 # This file is part of Postorius.
6 # Postorius is free software: you can redistribute it and/or modify it under
7 # the terms of the GNU General Public License as published by the Free
8 # Software Foundation, either version 3 of the License, or (at your option)
9 # any later version.
11 # Postorius is distributed in the hope that it will be useful, but WITHOUT
12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 # more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Postorius. If not, see <http://www.gnu.org/licenses/>.
19 """Postorius view decorators."""
20 from functools import wraps
22 from django.core.exceptions import PermissionDenied
24 from postorius.auth.utils import set_list_access_props
27 def list_owner_required(fn):
28 """Check if the logged in user is the list owner of the given list.
29 Assumes that the request object is the first arg and that list_id
30 is present in kwargs.
31 """
33 @wraps(fn)
34 def wrapper(*args, **kwargs):
35 user = args[0].user
36 list_id = kwargs['list_id']
37 if not user.is_authenticated:
38 raise PermissionDenied
39 if user.is_superuser:
40 return fn(*args, **kwargs)
41 set_list_access_props(user, list_id, moderator=False)
42 if user.is_list_owner:
43 return fn(*args, **kwargs)
44 else:
45 raise PermissionDenied(f'User {user} is not Owner of {list_id}')
47 return wrapper
50 def list_moderator_required(fn):
51 """Check if the logged in user is a moderator of the given list.
52 Assumes that the request object is the first arg and that list_id
53 is present in kwargs.
54 """
56 @wraps(fn)
57 def wrapper(*args, **kwargs):
58 user = args[0].user
59 list_id = kwargs['list_id']
60 if not user.is_authenticated:
61 raise PermissionDenied
62 if user.is_superuser:
63 return fn(*args, **kwargs)
64 set_list_access_props(user, list_id)
65 if user.is_list_owner or user.is_list_moderator:
66 return fn(*args, **kwargs)
67 else:
68 raise PermissionDenied(
69 f'User {user} is not Owner or Moderator of {list_id}'
72 return wrapper
75 def superuser_required(fn):
76 """Make sure that the logged in user is a superuser or otherwise raise
77 PermissionDenied.
78 Assumes the request object to be the first arg."""
80 @wraps(fn)
81 def wrapper(*args, **kwargs):
82 user = args[0].user
83 if not user.is_superuser:
84 raise PermissionDenied
85 return fn(*args, **kwargs)
87 return wrapper