"""Decorators that restrict views to certain types of users."""importtimefromdjango.confimportsettingsfromdjango.contribimportmessagesfromdjango.contrib.auth.decoratorsimportuser_passes_testfromdjango.shortcutsimportredirectfromdjango.urlsimportreverse
[docs]defadmin_required(group):"""Decorator that requires the user to be in a certain admin group. For example, @admin_required("polls") would check whether a user is in the "admin_polls" group or in the "admin_all" group. """defin_admin_group(user):returnuser.is_authenticatedanduser.has_admin_permission(group)returnuser_passes_test(in_admin_group)
#: Restrict the wrapped view to eighth adminseighth_admin_required=admin_required("eighth")#: Restrict the wrapped view to announcements adminsannouncements_admin_required=admin_required("announcements")#: Restrict the wrapped view to events adminsevents_admin_required=admin_required("events")#: Restrict the wrapped view to board adminsboard_admin_required=admin_required("board")#: Restrict the wrapped view to users who can take attendanceattendance_taker_required=user_passes_test(lambdau:notu.is_anonymousandu.is_attendance_taker)
[docs]defdeny_restricted(wrapped):definner(*args,**kwargs):request=args[0]# request is the first argument in a viewifnotrequest.user.is_anonymousandnotrequest.user.is_restricted:returnwrapped(*args,**kwargs)else:messages.error(request,"You are not authorized to access that page.")returnredirect("index")returninner
[docs]defreauthentication_required(wrapped):definner(*args,**kwargs):request=args[0]# request is the first argument in a viewif(isinstance(request.session.get("reauthenticated_at",None),float)and0<=(time.time()-request.session["reauthenticated_at"])<=settings.REAUTHENTICATION_EXPIRE_TIMEOUT):returnwrapped(*args,**kwargs)else:returnredirect("{}?next={}".format(reverse("reauth"),request.path))returninner