Some minor housekeeping fixes.
[mailman-postorious.git] / src / postorius / auth / decorators.py
blob14e17449e62fc953ac1657e3433df6bd15cfb7bd
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 1998-2021 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 """
32 @wraps(fn)
33 def wrapper(*args, **kwargs):
34 user = args[0].user
35 list_id = kwargs['list_id']
36 if not user.is_authenticated:
37 raise PermissionDenied
38 if user.is_superuser:
39 return fn(*args, **kwargs)
40 set_list_access_props(user, list_id, moderator=False)
41 if user.is_list_owner:
42 return fn(*args, **kwargs)
43 else:
44 raise PermissionDenied(f'User {user} is not Owner of {list_id}')
45 return wrapper
48 def list_moderator_required(fn):
49 """Check if the logged in user is a moderator of the given list.
50 Assumes that the request object is the first arg and that list_id
51 is present in kwargs.
52 """
53 @wraps(fn)
54 def wrapper(*args, **kwargs):
55 user = args[0].user
56 list_id = kwargs['list_id']
57 if not user.is_authenticated:
58 raise PermissionDenied
59 if user.is_superuser:
60 return fn(*args, **kwargs)
61 set_list_access_props(user, list_id)
62 if user.is_list_owner or user.is_list_moderator:
63 return fn(*args, **kwargs)
64 else:
65 raise PermissionDenied(
66 f'User {user} is not Owner or Moderator of {list_id}')
67 return wrapper
70 def superuser_required(fn):
71 """Make sure that the logged in user is a superuser or otherwise raise
72 PermissionDenied.
73 Assumes the request object to be the first arg."""
74 @wraps(fn)
75 def wrapper(*args, **kwargs):
76 user = args[0].user
77 if not user.is_superuser:
78 raise PermissionDenied
79 return fn(*args, **kwargs)
80 return wrapper