Skip to content

Instantly share code, notes, and snippets.

@Pradip-p
Last active September 9, 2021 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pradip-p/b398a4a026ba4e29714a8c22914f028f to your computer and use it in GitHub Desktop.
Save Pradip-p/b398a4a026ba4e29714a8c22914f028f to your computer and use it in GitHub Desktop.
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2021 - present Theragen Genome Care
"""
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import redirect
def admin_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
'''
Decorator for views that checks that the logged in user is a admin,
redirects to the log-in page if necessary.
'''
actual_decorator = user_passes_test(
lambda u: (u.is_active and u.is_admin) or u.is_superuser,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def user_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
'''
Decorator for views that checks that the logged in user is a staff,
redirects to the log-in page if necessary.
'''
actual_decorator = user_passes_test(
lambda u: (u.is_active and u.is_user) or u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def doctor_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
'''
Decorator for views that checks that the logged in user is a doctor,
redirects to the log-in page if necessary.
'''
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_doctor,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def unauthenticated(view_func):
'''
Decorator for views that checks that the authenticated user is accessn right page,
redirects to the roledefine page if necessary.
'''
def wrapper_fun(request,*args,**kwargs):
if request.user.is_authenticated and request.user.is_admin:
return redirect('/roleadmin')
elif request.user.is_authenticated and request.user.is_user:
return redirect('/staff')
elif request.user.is_authenticated and request.user.is_doctor:
return redirect('/doctor')
else:
return view_func(request,*args,**kwargs)
return wrapper_fun
def update(view_func):
'''
Decorator for views that checks that the logged in user is a update the personal information,
redirects to the update_profile page if necessary.
'''
def wrapper_fun(request,*args,**kwargs):
if len(request.user.first_name) == 0:
return redirect('/staff/update_profile')
else:
return view_func(request,*args,**kwargs)
return wrapper_fun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment