def group_required(group_name, login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user belongs to a particular
group, redirecting to the log-in page if necessary.
If the raise_exception parameter is given the PermissionDenied exception
is raised.
"""
def check_group(user):
# First check if the user belongs to the group
if user.groups.filter(name=group_name).exists():
return True
# In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form
return False
return user_passes_test(check_group, login_url=login_url)
python类user_passes_test()的实例源码
def permission_required(perm, login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if neccesary.
If the raise_exception parameter is given the PermissionDenied exception
is raised.
"""
def check_perms(user):
# First check if the user has the permission (even anon users)
if user.has_perm(perm):
return True
# In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form
return False
return user_passes_test(check_perms, login_url=login_url)
def login_if_required_for_dashboard(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary -
but only if REQUIRE_LOGIN_FOR_DASHBOARD is set True in Constance.
"""
def authenticated_test(u):
if config.REQUIRE_LOGIN_FOR_DASHBOARD:
return u.is_authenticated
else:
return True
actual_decorator = user_passes_test(
authenticated_test,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def kml_upload(request):
context_data = {}
if request.method == 'POST':
form = KMLUpload(request.POST or None,request.FILES)
if form.is_valid():
docFile = request.FILES['kml_file'].read()
objKML = KMLParser(docFile, form.cleaned_data['slum_name'], form.cleaned_data['delete_flag'])
try:
parsed_data = objKML.other_components()
context_data['parsed'] = [k for k,v in parsed_data.items() if v==True]
context_data['unparsed'] = [k for k,v in parsed_data.items() if v==False]
messages.success(request,'KML uploaded successfully')
except Exception as e:
messages.error(request, 'Some error occurred while parsing. KML file is not in the required format ('+str(e)+')')
else:
form = KMLUpload()
metadata_component = Metadata.objects.filter(type='C').values_list('code', flat=True)
context_data['component'] = metadata_component
context_data['form'] = form
return render(request, 'kml_upload.html', context_data)
#@user_passes_test(lambda u: u.is_superuser)
def get_kobo_RHS_data(request, slum_id,house_num):
output = {}
slum = get_object_or_404(Slum, pk=slum_id)
project_details = False
if request.user.is_superuser or request.user.groups.filter(name='ulb').exists():
project_details = True
output = get_kobo_RHS_list(slum.electoral_ward.administrative_ward.city.id, slum.shelter_slum_code, house_num)
elif request.user.groups.filter(name='sponsor').exists():
project_details = SponsorProjectDetails.objects.filter(slum=slum, sponsor__user=request.user, household_code__contains=int(house_num)).exists()
if request.user.groups.filter(name='ulb').exists():
project_details = False
#if 'admin_ward' in output:
output['admin_ward'] = slum.electoral_ward.administrative_ward.name
output['slum_name'] = slum.name
output['house_no'] = house_num
output['FFReport'] = project_details
return HttpResponse(json.dumps(output),content_type='application/json')
#@user_passes_test(lambda u: u.is_superuser)
def get_kobo_RIM_report_data(request, slum_id):
try:
slum = Slum.objects.filter(shelter_slum_code=slum_id)
except:
slum = None
try:
rim_image = Rapid_Slum_Appraisal.objects.filter(slum_name=slum[0]).values()
except:
rim_image = []
output = {"status":False, "image":False}
if slum and len(slum)>0:
output = get_kobo_RIM_report_detail(slum[0].electoral_ward.administrative_ward.city.id, slum[0].shelter_slum_code)
output["status"] = False
if len(output.keys()) > 1:
output['status'] = True
output['admin_ward'] = slum[0].electoral_ward.administrative_ward.name
output['electoral_ward'] = slum[0].electoral_ward.name
output['slum_name'] = slum[0].name
if rim_image and len(rim_image) > 0:
output.update(rim_image[0])
output['image'] = True
return HttpResponse(json.dumps(output),content_type='application/json')
#@user_passes_test(lambda u: u.is_superuser)
def report_view(title, form_type=None):
''' Decorator that converts a report view function into something that
displays a Report.
Arguments:
title (str):
The title of the report.
form_type (Optional[forms.Form]):
A form class that can make this report display things. If not
supplied, no form will be displayed.
'''
# Create & return view
def _report(view):
report_view = ReportView(view, title, form_type)
report_view = user_passes_test(views._staff_only)(report_view)
report_view = wraps(view)(report_view)
# Add this report to the list of reports.
_all_report_views.append(report_view)
return report_view
return _report
def staff_member_required(login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user is staff,
redirecting to the log-in page if neccesary.
If the raise_exception parameter is given the PermissionDenied exception
is raised.
"""
def check_staff(user):
if user.is_staff:
return True
# In case the 403 handler should be called raise the exception
if user.is_authenticated() and raise_exception:
raise PermissionDenied()
# As the last resort, show the login form
return False
return user_passes_test(check_staff, login_url=login_url)
def staff_login_required(function=None,
redirect_field_name=REDIRECT_FIELD_NAME,
login_url=None):
'''
Decorator to check that the user accessing the decorated view has their
is_staff flag set to True.
It will first redirect to login_url or the default login url if the user is
not authenticated. If the user is authenticated but is not staff, then
a PermissionDenied exception will be raised.
'''
# Based off code from the Django project
# License: https://github.com/django/django/blob/c1aec0feda73ede09503192a66f973598aef901d/LICENSE # NOQA
# Code reference: https://github.com/django/django/blob/c1aec0feda73ede09503192a66f973598aef901d/django/contrib/auth/decorators.py#L40 # NOQA
def check_if_staff(user):
if not user.is_authenticated():
# returning False will cause the user_passes_test decorator
# to redirect to the login flow
return False
if user.is_staff:
# then all good
return True
# otherwise the user is authenticated but isn't staff, so
# they do not have the correct permissions and should be directed
# to the 403 page
raise PermissionDenied
actual_decorator = decorators.user_passes_test(
check_if_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def mala_staff_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='staff:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
return user_passes_test(
is_manager,
login_url=login_url,
redirect_field_name=redirect_field_name
)(view_func)
def mala_lecturer_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='lecturer:login'):
"""
Decorator for views that checks that the user is logged in and is a lecturer,
displaying the login page if necessary.
"""
return user_passes_test(
is_lecturer,
login_url=login_url,
redirect_field_name=redirect_field_name
)(view_func)
def setSidebarContent(self, teacher, context):
side_bar_content = SideBarContent(teacher)
side_bar_content(context)
# @method_decorator(user_passes_test(is_teacher_logined, login_url=LOGIN_URL))
def handle_get(self, request, user, teacher, *args, **kwargs):
raise Exception("get not implement")
# @method_decorator(user_passes_test(is_teacher_logined, login_url=LOGIN_URL))
def mala_staff_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='import_:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
return user_passes_test(
is_manager,
login_url=login_url,
redirect_field_name=redirect_field_name
)(view_func)
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def super_user_required(login_url=None):
# return user_passes_test(lambda u: u.is_staff, login_url='/error_403')
return user_passes_test(lambda u: u.is_superuser, login_url='/error_403')
def super_user_required(login_url=None):
# return user_passes_test(lambda u: u.is_staff, login_url='/error_403')
return user_passes_test(lambda u: u.is_superuser, login_url='/error_403')
def super_user_required(login_url=None):
# return user_passes_test(lambda u: u.is_staff, login_url='/error_403')
return user_passes_test(lambda u: u.is_superuser, login_url='/error_403')
def user_is_project_admin(view_func):
"""Projet admin view decorator.
Checks that the user is an admin, moderator or initiator of any project.
"""
return user_passes_test(
_user_is_project_admin,
)(view_func)
def not_guest_required(function=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: not u.is_guest(),
# TODO: make lazy with new django
# https://code.djangoproject.com/ticket/5925
login_url='/login/',
)
if function:
return actual_decorator(function)
return actual_decorator
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
return user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)(view_func)
def user_is_staff(func):
return user_passes_test(lambda u: u.is_staff)(login_required(func))
def user_is_finance(func):
return user_passes_test(lambda u: u.is_staff and u.groups.filter(name="finance"))(login_required(func))
def user_flag_required(*flags):
def check(user):
return any(getattr(user.profile, f, False) for f in flags)
return user_passes_test(check)
def user_group_required(*groups):
return user_passes_test(lambda u: u.groups.filter(name__in=groups).exists())
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, redirecting to the login page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if view_func:
return actual_decorator(view_func)
return actual_decorator