How to Set Up Signup, Login, and Logout using Django's Middleware
Tags: middleware, django, pythonsecurity, authentication
Published: 2024-05-21 07:03:29


1. Create a Python project containing an app with files <code>apps.py</code>, <code>models.py</code>, <code>views.py</code>, and <code>forms.py</code>, and create a virtual environment:

```python
django-admin startproject <project_name>  
cd <project_name>  
python3 -m venv <virtual_environment_name>   
pip install django    
source <virtual_environment_name>/bin/activate   
python manage.py startapp <app_name>
```


<ol start="2">
<li>In your `settings.py` file, make sure: <ul><li>`django.contrib.auth.middleware.AuthenticationMiddleware` is included under the MIDDLEWARE setting.
</li><li><code>django.contrib.auth</code> and <code>django.contrib.contenttypes</code> are listed under INSTALLED_APPS in <code>settings.py</code>. Add your app to INSTALLED_APPS, as well. Then, run <code>manage.py migrate</code> to create the necessary database tables.</li></li>
</ol>

<ol start="3">
<li>In the views.py file, create a signup view and a <code>landing_page</code> view, and use the <code>@login_required</code> decorator for all your views that require login:</li>
</ol>

```python
# django_app/views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm

def signup(request):
   if request.method == 'POST':
       form = UserCreationForm(request.POST)
       if form.is_valid():
           form.save()
           return redirect('login')
   else:
       form = UserCreationForm()
   return render(request, 'signup.html', {'form': form})
def landing_page(request):
   if request.user.is_authenticated:
       return render(request, 'my_template.html')
   return render(request, 'landing_page.html')

@login_required
def my_app(request):
    # Action logic here
   return render(request, 'my_template.html')
```

<ol start="4">
<li>Create a <code>signup.html</code> template, a <code>registration/login.html</code> template, a <code>landing_page.html</code> template, and a <code>my_template.html</code> template:</li>
</ol>

```python
<!-- signup.html -->

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Sign Up</title>
</head>
<body>
   <h2>Sign Up</h2>
   <form method="post">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Sign Up</button>
   </form>
</body>

<!-- registration/login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Login</title>
</head>
<body>
   <h2>Login</h2>
   <form method="post">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Login</button>
   </form>
</body>
</html>

<!-- landing_page.html -->
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Welcome to Your Site</title>
</head>
<body>
   <h1>Welcome to Your Site</h1>
   <p>Sign up or log in to access the features:</p>
   <a href="{% url 'signup' %}">Sign Up</a>
   <a href="{% url 'login' %}">Log In</a>
</body>
</html>
```

<ol start="5">
<li>Import <code>from django.contrib.auth import views as auth_views</code> in your <code>url.py</code> file and add the new paths:</li>
</ol>

```python
# urls.py

from django.contrib import admin
from django.urls import path
from upload_app import views
from django.contrib.auth import views as auth_views

urlpatterns = [
   path('admin/', admin.site.urls),
   path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
   path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
   path('', views.landing_page, name='landing_page'),
   path('signup/', views.signup, name='signup'),
   path('my_app/', views.my_app, name='my_app'),
  # Your app’s paths
]
```

<ol start="6">
<li>To allow logging in, singing in,  and logging out, add this script to the rest of the templates in your app:</li>
</ol>

```python
{% if user.is_authenticated %}
   <p>Welcome, {{ user.username }}!</p>
   <a href="{% url 'logout' %}">Logout</a>
{% else %}
   <a href="{% url 'signup' %}">Sign up</a>
   <a href="{% url 'login' %}">Login</a>
{% endif %}
```

<ol start="7">
<li>In <code>settings.py</code>, add the following code to open the respective templates whenever a user logs in and out:</li>
</ol>

```python
LOGIN_REDIRECT_URL = 'my_app'  # Redirect to upload page after login
LOGOUT_REDIRECT_URL = 'login'   # Redirect to login page after logout
```

For more information about Python built-in and third-party security features, see [Python Security Essentials for Your Apps](https://dev.to/sharony/python-security-essentials-for-your-apps-1810).