Here's an example of a custom authentication decorator in Django:

from django.contrib.auth.decorators import user_passes_test

def is_employee(user):
    return user.is_authenticated and user.is_employee

def employee_required(view_func):
    decorated_view_func = user_passes_test(
        is_employee,
        login_url='login',
        redirect_field_name=None
    )(view_func)
    return decorated_view_func

In this example, we define a custom authentication decorator called employee_required. This decorator will check if the user is authenticated and also has the is_employee attribute set to True. If the user doesn't meet these criteria, they will be redirected to the login page.

To use this decorator, simply add it above any view function that requires employee authentication:

@employee_required
def employee_dashboard(request):
    # This view requires the user to be authenticated and have is_employee=True
    return render(request, 'employee_dashboard.html')

This way, any user who tries to access the employee_dashboard view will first be checked for authentication and employee status. If they pass the check, they will be able to see the dashboard. If not, they will be redirected to the login page.

Django custom authentication decorator code example

原文地址: https://www.cveoy.top/t/topic/HFo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录