Within Python, I have created a User
class that may have one of two UserType
's, Regular
or Admin
. The User
class has multiple methods, and I want some of them to only be accessible by an admin.
Currently, I have this code:
from enum import Enum
class AuthorizationError(Exception):
"""Raised when a user attempts an admin-restricted task"""
class UserType(Enum):
Regular = 0
Admin = 1
class User:
def __init__(self, username, user_type):
self.username = username
self.user_type = user_type
def admin_required(self, func):
def wrapper(*args, **kwargs):
if self.user_type is UserType.Admin:
return func(*args, **kwargs)
else:
raise AuthorizationError(f"User must be an admin to use {func.__name__}.")
return wrapper
def do_something_regular(self):
print(f"{self.username} is doing something any regular user can do.")
@admin_required
def do_something_admin(self):
print(f"{self.username} is doing something only an admin can do.")
me = User("MyUsername", UserType.Admin)
me.do_something_regular()
me.do_something_admin()
Which yields the following error:
Traceback (most recent call last):
File "example.py", line 13, in <module>
class User:
File "example.py", line 31, in User
@admin_required
TypeError: admin_required() missing 1 required positional argument: 'func'
I understand I can probably create a subclass for an admin, but the goal is to use a decorator within the User
class to check for admin privileges.
I think the problem is that when I wrap the do_something_admin
function, do_something_admin
is passed to the self
argument instead of self
being passed as the instance of the class.
I have not been able to solve this problem. Keep in mind, I want to use a decorator in the solution. Thank you!