Implementing User Authentication and Authorization in Django
User authentication ensures that users can securely log in and access their accounts. Authorization, on the other hand, determines what actions authenticated users are allowed to perform. Django provides a robust authentication system that is easy to integrate and extend for these purposes.
Setting Up the Default Authentication System
Django's default authentication system is included in its configuration by default. Ensure the following apps are listed in the INSTALLED_APPS
section of your settings.py
:
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
Migrate the database to set up the necessary tables:
python manage.py migrate
Creating a User Model
Django provides a built-in user model, but you can create a custom one if needed. To use the default model:
from django.contrib.auth.models import User
# Creating a new user
user = User.objects.create_user(username='johndoe', password='securepassword')
user.email = 'johndoe@example.com'
user.save()
To create a custom user model, modify your models.py
:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
phone_number = models.CharField(max_length=15, blank=True, null=True)
Update the AUTH_USER_MODEL
setting in settings.py
:
AUTH_USER_MODEL = 'yourapp.CustomUser'
Handling User Login and Logout
Django provides built-in views for login and logout. Add the following URLs to your urls.py
:
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
Create a simple login template named registration/login.html
:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log in</button>
</form>
Restricting Access with Permissions
Django provides permission classes to restrict access. To use them in views:
from django.contrib.auth.decorators import login_required, permission_required
@login_required
def dashboard(request):
return render(request, 'dashboard.html')
@permission_required('yourapp.can_edit')
def edit_page(request):
return render(request, 'edit_page.html')
Permissions can be assigned using the Django admin or through the shell:
from django.contrib.auth.models import User, Permission
user = User.objects.get(username='johndoe')
permission = Permission.objects.get(codename='can_edit')
user.user_permissions.add(permission)
Conclusion
Django's authentication and authorization system provides a solid foundation for securing your web applications. It is highly customizable, enabling you to extend its functionality to meet specific requirements. With this system, you can easily manage user accounts, roles, and permissions in your projects.