Django user authentication part 1

Firrst Create a decorators.py file in your app and import this file in views.py file..

from django.http import HttpResponse
from django.shortcuts import redirect

def unauthenticated_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('/')
        else:
            return view_func(request, *args, **kwargs)

    return wrapper_func

def allowed_users(allowed_roles=[]):
    def decorator(view_func):
        def wrapper_func(request, *args, **kwargs):

            group = None

            if request.user.groups.exists():
                group = request.user.groups.all()[0].name
            if group in allowed_roles:
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponse('You are not authorised to view this page')
        return wrapper_func
    return decorator

def admin_only(view_func):
    def wrapper_func(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group == 'customer':
            return HttpResponse('You are Customer')

        if group == 'admin':
            return view_func(request, *args, **kwargs)

    return wrapper_func

Note: Create two groups (Admin and customer) from your Django admin panels and assign the roles to users which is registered in your website, Please visit on Part-1 for more info.

LEAVE A REPLY

Please enter your comment!
Please enter your name here