我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.auth.decorators.user_passes_test()。
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)
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 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 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, 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 super_user_required(login_url='/error_403'): """ check permission :param login_url: :return: """ return user_passes_test(lambda u: u.is_superuser, login_url=login_url)
def administrator_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in and an administrator """ actual_decorator = user_passes_test( lambda u: u.administrator, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
def login_required(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. Based on django.contrib.auth.decorators.login_required """ actual_decorator = user_passes_test( lambda u: u.is_authenticated() and u.is_email_confirmed, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
def staff_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is staff, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
def bsd_login_required(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. """ actual_decorator = user_passes_test( lambda u: isinstance(u, Constituent), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator
def player_required(view_func): """ Decorator that ensures logged user is a player """ player_decorator = user_passes_test( lambda u: hasattr(u, 'player'), ) return player_decorator(view_func)
def team_required(view_func): """ Decorator that ensures logged player has its own team -> request.team != None. User must be logged in (if not, redirect to login_url), and have a team (if not, redirect to core.team) """ team_decorator = user_passes_test( lambda u: u.player.team is not None, login_url='/team/create/' ) return player_required(team_decorator(view_func))
def login_required(login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): # FIXME: Ugly hack to extract process when django's user_passes_test. return user_passes_test( lambda u: False, login_url=login_url, redirect_field_name=redirect_field_name, )(lambda r: "dummy")
def has_management_permission(user): """ Replacing with ManagementPermissionMixin used in def index (not as decorator) used in def manage_territory used in def add_master_list_select used in def add_personal_list_select used in def create_selection_widget used in def delete_master_list_select used in def delete_personal_list_select used in def load_staff_category_selects used in def load_staff_member_selects used in def update_user_assignments To be called by textdecorator @user_passes_test Also, any time you need to check if user has management permissions """ if user.groups.filter(name='db_admin').exists(): return True if user.groups.filter(name='management').exists(): return True if user.is_superuser: return True return False ################## # MAIN FUNCTIONS ##################
def group_required(*group_names): def in_groups(u): if u.is_authenticated(): if bool(u.groups.filter(name__in=group_names)) | u.is_superuser: return True return False return user_passes_test(in_groups, login_url='/error/')