Home > Software design >  How to create custom login decorators in django
How to create custom login decorators in django

Time:02-20

I am creating an app in django where all the authentication like login signup is done by using an exernal rest api so there is no database involved in it. This is why I am saving logged in user data in request.session now the issue is I don't want to show some of the pages if the user is not inside the sessions, what we usually do back in django apps is use @login_required decorator but now as there is no database so what will be the procedure of not showing those pages to not logged in users. thanks

CodePudding user response:

You can define a decorator that will look for a key in the request.sessions:

# app_name/decorators.py

from django.shortcuts import redirect
from functools import wraps

def session_login_required(function=None, session_key='user'):
    def decorator(view_func):
        @wraps(view_func)
        def f(request, *args, **kwargs):
            if session_key in request.session:
                return view_func(request, *args, **kwargs)
            return redirect('name-of-login-view')
        return f
    if function is not None:
        return decorator(function)
    return decorator

here it will thus check if 'user' is a key in the request.session. You can of course change this to a different key.

Then we use the decorator for these views:

# app_name/views.py

from app_name.decorators import session_login_required

@session_login_required
def my_view(request, some, parameters):
    # …
  • Related