USER PASSWORD RESET USING DJANGO
Published: 2024-05-27 11:45:33

## **TABLE OF CONTENTS**
**1. Introduction**
**2. Prerequisites**
**3. Creating a login Template**
- Definition of terms
- Creating a login Template

**4. Implementing user password reset in Django**
- Configuring email settings
- URL configuration
- Creating templates

    - Password request form
    - Password request email template
    - Password reset 
    - Password reset complete form
- Email template
- Testing

**5. Conclusion**
**6. References**


## **Introduction**
In web applications, it's crucial to include password reset functionality to ensure both security and user-friendliness. When using Django, a high-level Python web framework, there are built-in features that simplify the creation of this functionality. This involves setting up a process where users can receive an email allowing them to reset their passwords on the server side, with the email sent directly to their inbox.
By following the guidelines provided, you can efficiently implement user password reset functionality in your Django application.


## **Steps to create Django app**
1. Ensure you have python installed in your computer if you does not have install it by visiting python official website.
2. Install pip which comes with python in default.
          navigate in the terminal to determine its version by running pip --version
3. Install virtual environment

     Virtualenv is a tool to create isolated Python environments.
<code>
    pip install virtualenv
</code>
4. Install Django by running the following in terminal
<code>
    pip install django
</code>
5.Create Django project
<code>
    django-admin startproject password-reset
</code>
6.Navigate into the project folder by running
<code>
    cd password-reset
</code>
7.Run code . in your terminal to run your project in your code editor


## **Creating a sub app in the Django app**
1. Create a Django App:
    - Use the `manage.py` script to create a new app:
<code>
    python manage.py startapp myapp
</code>
2. Configure the Django Project

3. Add the App to INSTALLED_APPS:
    - Open `mysite/settings.py` and add your new app (`myapp`) to the `INSTALLED_APPS` list:
<code>
    INSTALLED_APPS = [
        ...
        'myapp',
    ]
</code>
4. Create Initial Views

a. Create a View:
    - Open `myapp/views.py` and create a simple view:
<code>
    from django.http import HttpResponse
   
    def index(request):
        return HttpResponse("Hello, world. You're at the myapp index.")
</code>
b. Map the View to a URL:
    - Create a file named `urls.py` in the `myapp` directory and add the following code:
<code>
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.index, name='index'),
    ]
</code>
c. Include the App’s URL Configuration:
    - Open `mysite/urls.py` and include the app's `urls.py`:
<code>
    from django.contrib import admin
    from django.urls import include, path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('myapp/', include('myapp.urls')),
    ]
</code>
5. Run the Development Server

a. Run the Server:
    - Use the `manage.py` script to start the development server:

<code>
    python manage.py runserver
</code>
6. Access the App:
    - Open a web browser and go to `http://127.0.0.1:8000/myapp/` to see your app in action.


## **Steps to implement user password Reset in Django**
**1.Configure Email Settings**

Django relies on an external email service to send password reset emails. You’ll need to configure your email settings in the ‘settings.py’. This typically involves specifying:

- EMAIL_BACKEND: The class responsible for sending emails
- EMAIL_HOST: Your email provider's SMTP server address.
- EMAIL_HOST_USER: Your email address used for sending emails.
- EMAIL_HOST_PASSWORD: The password for your email account.
- EMAIL_PORT: The SMTP port number for your email provider.
- EMAIL_USE_TLS: (Optional) Enable TLS encryption for secure communication (recommended).
Example
<code>
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST = 'smtp.example.com'
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True
    EMAIL_HOST_USER = 'your_email@example.com'
    EMAIL_HOST_PASSWORD = 'your_email_password'
    DEFAULT_FROM_EMAIL = 'your_email@example.com'
</code>

**2.URL CONFIGURATION.**

- Set up the default URL settings patterns, in Django by handling password reset views. Make sure to add the django.contrib.auth.urls to your projects urls.py file.
Code example in the ‘settings.py’
<code>
    from django.urls import path, include
    
    ur patterns = [
        ...
        path('accounts/', include('django.contrib.auth.urls')),
        ...
    ]
</code>
**3. Create Templates**
This involves creating templates for the user to reset the password. They include the following:

**a) Password reset request form:**
- It is a form template designed to allow users to request a password reset for their accounts.
- Django provides a `PasswordResetForm’ for this purpose. You can customize this form or create your own based on your requirements.

example
<code>
![Password reset request form](https://paper-attachments.dropboxusercontent.com/s_68D1EC615B06F1E9E630A3F173EA237B36441EC12E219A500BADABB1B7047161_1716476749610_forgot-your-password.jpg)
</code>
**b. Password reset confirmation form**

- The Password Reset form contains an action that sends the user an email with a special SSO link to reset their password.

<code>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Password Reset Done</title>
    </head>
    <body>
        <h2>Password Reset Email Sent</h2>
        <p>We've emailed you instructions for setting your password. If you haven't received the email, please check your spam folder.</p>
    </body>
    </html> 
</code>

When a user submits the password reset form, the ‘PasswordResetView` handles the logic:

- Validates the submitted email address against registered users.
- Generates a unique password reset token using a cryptographically secure method.
- Creates a password reset record associated with the user and the generated token.
- Sends an email containing the reset link to the user's email address.

![Confirmation email](https://paper-attachments.dropboxusercontent.com/s_68D1EC615B06F1E9E630A3F173EA237B36441EC12E219A500BADABB1B7047161_1716477825737_confirmation.png)



**c. Password reset email template**
- A password reset email template is a transactional email that is triggered when customers click on a “Forgot password?” link to reset the previous password.

<code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Reset Email</title>
</head>
<body>
    <h2>Password Reset</h2>
    <p>You're receiving this email because you requested a password reset for your account.</p>
    <p>Please click the link below to reset your password:</p>
    <p><a href="{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}">Reset Password</a></p>
    <p>If you didn't request a password reset, you can safely ignore this email.</p>
</body>
</html>
</code>

**d. password reset form**
- The password reset form allows users who have forgotten their password to securely reset it. It verifies the user's identity through their email address and then prompts them to create a new password.
<code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Reset Confirm</title>
</head>
<body>
    <h2>Reset Password</h2>
    <form method="post">
        <code>{% csrf_token %}</code>
        <code>{{ form.as_p }}</code>
        <button type="submit">Continue</button>
    </form>
</body>
</html>
</code>

**e. Password reset complete form**
- It is a form that triggers the confirmation that the password has been reset and the user can login to the account using the new created password.

<code>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Password Reset Complete</title>
    </head>
    <body>
        <h2>Password Reset Successful</h2>
        <p>Your password has been successfully reset. You can now <a href="{% url 'login' %}">log in</a> with your new password.</p>
    </body>
    </html>
</code>


**4. Email Template**
- Customize the email template for the password reset email. Django uses a default text-based email template, but you can create your own HTML email template for a better user experience.
<code>
    PASSWORD_RESET_EMAIL_TEMPLATE = 'path_to_your_email_template.html'
</code>

## **5. Testing**

Thoroughly test the password reset functionality to ensure its correctness and security. Test scenarios should include:

- User receives the password reset email.
- User clicks on the reset link.
- User successfully resets the password.


## **Conclusion**

Django provides a robust built-in functionality for implementing user password reset with emails. This feature enhances user experience by allowing them to retrieve forgotten passwords easily. By configuring your email backend, defining URL patterns for the provided views, creating informative templates, and ensuring everything works through testing, you can establish a secure and user-friendly password reset system for your Django application.


## **References**
https://youtu.be/whK97tOV2z4
https://django-password-reset.readthedocs.io/
https://docs.djangoproject.com/en/5.0/


**MEMBER ROLES**
All members participated generally in the discussion, conducting research and gathering information relevant to the group’s objective. Individual roles are as follows:

| Name                                                    | Role                                                                                                                                                                                                                  |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. Victor Kedenge                                       | - Created agendas and distributed to the team<br>- Scheduled and led the meeting.<br>- Coordinating among the group members                                                                                           |
| 2.Julius Gichure                                        | - Creating templates responsible for resetting users password which includes:<br>    - Password reset request form<br>    - Password reset form<br>    - Password reset confirmation<br>    - Password reset complete |
| 3.John Brown                                            | - Creating user login template and handling of its codes<br>- Configuring email settings<br>- URL Configurations                                                                                                      |
| 4. Beth Owala                                           | - Creating email template responsible for generating users reset link<br>- Performing conclusion                                                                                                                      |
| 5.Abdirahman Aben                                       | - Conducted editing<br>- Taking notes<br>- Providing references                                                                                                                                                       |
| 6.Sharon Imali<br><br><br><br><br>7. Moris Mutugi | - Attaching images<br>- Typing down notes on discussed points within the group members<br>- Adding video tutorials for further references                                                                             |