Authentication in Django-2 Roles added

Django Authentication with MySQL and Roles

🔐 Django Authentication with Roles (Admin, Seller, Customer)

This is a continuation of our previous post on Django authentication. We now add user roles using Django’s Group system. You’ll learn how to assign roles during user registration and restrict access based on them.

📁 Step 1: Create Groups in Django Admin

Start your server and visit the admin site at /admin. Login and do the following:

  1. Click Groups
  2. Create 2 groups: Seller and Customer

You can also do this via Python shell:

python manage.py shell
from django.contrib.auth.models import Group
Group.objects.get_or_create(name='Seller')
Group.objects.get_or_create(name='Customer')

📝 Step 2: Add Role Selection in Registration Form

register.html:

<form method="post">
  {% csrf_token %}
  <input name="username" placeholder="Username"><br>
  <input name="password" type="password" placeholder="Password"><br>
  <select name="role">
    <option value="Customer">Customer</option>
    <option value="Seller">Seller</option>
  </select><br>
  <button type="submit">Register</button>
</form>

🔧 Step 3: Modify Register View to Assign Role

views.py:

from django.contrib.auth.models import Group

def register_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        role = request.POST['role']
        user = User.objects.create_user(username=username, password=password)

        group = Group.objects.get(name=role)
        user.groups.add(group)
        return redirect('login')
    return render(request, 'register.html')

🚫 Step 4: Restrict Views by Role

Add this decorator function in views.py:

from django.http import HttpResponseForbidden

def group_required(group_name):
    def decorator(view_func):
        def wrapper(request, *args, **kwargs):
            if request.user.groups.filter(name=group_name).exists():
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponseForbidden("Access Denied: You are not a " + group_name)
        return wrapper
    return decorator

Now you can protect views like this:

@login_required
@group_required('Seller')
def seller_dashboard(request):
    return HttpResponse("Welcome, Seller!")
@login_required
@group_required('Customer')
def customer_dashboard(request):
    return HttpResponse("Welcome, Customer!")

🔗 Step 5: Add URLs

accounts/urls.py:

urlpatterns = [
    path('register/', views.register_view, name='register'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('seller/', views.seller_dashboard, name='seller_dashboard'),
    path('customer/', views.customer_dashboard, name='customer_dashboard'),
]

🎯 Summary

  • Created user roles using Django's Group model
  • Assigned role during registration
  • Restricted dashboard views by role

📚 Resources

Post a Comment

0 Comments

Me