Debug School

rakesh kumar
rakesh kumar

Posted on

Multiple Authentication In Django

To implement different dashboards based on user roles after login in Django, you can follow these steps:

Step 1: Define Role-Based Dashboard Views
Create separate views for each dashboard based on user roles. For example, create AdminDashboardView, ManagerDashboardView, and UserDashboardView views. Each view should render the respective dashboard template. Here's an example:


from django.shortcuts import render

def admin_dashboard(request):
    return render(request, 'admin_dashboard.html')

def manager_dashboard(request):
    return render(request, 'manager_dashboard.html')

def user_dashboard(request):
    return render(request, 'user_dashboard.html')
Enter fullscreen mode Exit fullscreen mode

Step 2: Define URL Patterns
Create URL patterns for the dashboard views in your urls.py file. Here's an example:

from django.urls import path
from .views import admin_dashboard, manager_dashboard, user_dashboard

urlpatterns = [
    path('dashboard/admin/', admin_dashboard, name='admin_dashboard'),
    path('dashboard/manager/', manager_dashboard, name='manager_dashboard'),
    path('dashboard/user/', user_dashboard, name='user_dashboard'),
    # Other URLs
]
Enter fullscreen mode Exit fullscreen mode

Step 3: Define the Custom User Model
In your Django app, create a file called models.py and define your custom user model. Here's an example:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    ROLE_CHOICES = (
        ('admin', 'Admin'),
        ('manager', 'Manager'),
        ('user', 'User'),
    )
    role = models.CharField(max_length=20, choices=ROLE_CHOICES)
Enter fullscreen mode Exit fullscreen mode

Step 4: Update the Authentication Backend
In your settings.py file, specify the custom user model and authentication backend:

AUTH_USER_MODEL = 'yourapp.CustomUser'
AUTHENTICATION_BACKENDS = [
    'yourapp.backends.CustomUserBackend',
    # Other backends if any
]
Enter fullscreen mode Exit fullscreen mode

Step 5: Define the Authentication Backend
Create a file called backends.py in your Django app and define the authentication backend to handle the authentication logic:

from django.contrib.auth.backends import ModelBackend
from .models import CustomUser

class CustomUserBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = CustomUser.objects.get(username=username)
            if user.check_password(password):
                return user
        except CustomUser.DoesNotExist:
            return None
Enter fullscreen mode Exit fullscreen mode

Step 6: Update the Login View
In your login view, after the user is authenticated, redirect them to the appropriate dashboard based on their role. Here's an example:

from django.shortcuts import redirect
from django.contrib.auth import authenticate, login

def login_view(request):
    # Your login logic to authenticate the user
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(request, username=username, password=password)

    if user is not None:
        login(request, user)
        role = user.role  # Assuming you have a 'role' attribute in your user model
        if role == 'admin':
            return redirect('admin_dashboard')
        elif role == 'manager':
            return redirect('manager_dashboard')
        elif role == 'user':
            return redirect('user_dashboard')
        else:
            # Handle unrecognized or anonymous user
            return redirect('login')

    # Handle invalid credentials or other login failure scenarios
    return redirect('login')
Enter fullscreen mode Exit fullscreen mode

Step 7: Update Template Links
In your templates, update the links to the dashboards based on the user's role. For example:

<!-- Template for the login page -->
<a href="{% url 'admin_dashboard' %}">Admin Dashboard</a>
<a href="{% url 'manager_dashboard' %}">Manager Dashboard</a>
<a href="{% url 'user_dashboard' %}">User Dashboard</a>
Enter fullscreen mode Exit fullscreen mode

That's it! Now, when a user logs in, they will be redirected to the appropriate dashboard based on their role. Ensure you have set up the necessary authentication and user models according to your requirements.

Top comments (0)