Restricting All The Views To Authenticated Users In Django
I'm new to Django and I'm working on a project which has a login page as its index and a signup page. The rest of the pages all must be restricted to logged in users and if an unau
Solution 1:
You can write a middleware:
from django.contrib.auth.decorators import login_required
def login_exempt(view):
view.login_exempt = True
return view
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(view_func, 'login_exempt', False):
return
if request.user.is_authenticated:
return
# You probably want to exclude the login/logout views, etc.
return login_required(view_func)(request, *view_args, **view_kwargs)
You add the middleware to your MIDDLEWARES
list and decorate the views you don't want authenticated with login_exempt
.
Solution 2:
...is there a better way to make all the views restricted and only a few available to unauthenticated users?
Yes. It's time for you to learn class based views. Define a base class which requires login, and make any authenticated endpoints inherit this base class, rather than using function-based views with decoration on each function.
A popular design pattern in the implementation is to use a mixin class:
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
If a view uses this mixin, all requests by non-authenticated users will be redirected to the login page.
Post a Comment for "Restricting All The Views To Authenticated Users In Django"