7. User authentication and permissions - LiVanych/locallibrary GitHub Wiki

Read full version

Enabling authentication

The configuration is set up in the INSTALLED_APPS and MIDDLEWARE sections of the project file (locallibrary/locallibrary/settings.py), as shown below:

INSTALLED_APPS = [
    ...
    #Core authentication framework and its default models.
    'django.contrib.auth',
    #Django content type system (allows permissions to be associated with models).
    'django.contrib.contenttypes',
    ....

MIDDLEWARE = [
    ...
    #Manages sessions across requests
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
    #Associates users with requests using sessions.
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ....

Creating users and groups

Goto http://127.0.0.1:8000/admin/

  1. Create Group 'Library Members'

  2. Create Group 'Librarians'

  3. Create user 'abertu' and add him to 'Library Members' group.

  4. Create user 'nikolson' adn add him to 'Librarians' group.

Setting up your authentication views

Project URLs

Add the following to the bottom of the project urls.py file (locallibrary/locallibrary/urls.py) file:

#Add Django site authentication urls (for login, logout, password management)
urlpatterns += [
    path('accounts/', include('django.contrib.auth.urls')),
]

Navigate to the http://127.0.0.1:8000/accounts/ URL (note the trailing forward slash!) and Django will show an error that it could not find this URL, and listing all the URLs it tried. From this you can see the URLs that will work, for example:

accounts/ login/ [name='login']
accounts/ logout/ [name='logout']
accounts/ password_change/ [name='password_change']
accounts/ password_change/done/ [name='password_change_done']
accounts/ password_reset/ [name='password_reset']
accounts/ password_reset/done/ [name='password_reset_done']
accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/ reset/done/ [name='password_reset_complete']

Now try to navigate to the login URL (http://127.0.0.1:8000/accounts/login/). This will fail again, but with an error that tells you that we're missing the required template (registration/login.html) on the template search path. You'll see the following lines listed in the yellow section up the top.

Template directory

Note: Your folder structure should now look like the below:

locallibrary (Django project folder)
   |_catalog
   |_locallibrary
   |_templates (new)
                |_registration

Exception Type:    TemplateDoesNotExist
Exception Value:    registration/login.html

The next step is to create a registration directory on the search path and then add the login.html file.

To make these directories visible to the template loader (i.e. to put this directory in the template search path) open the project settings (/locallibrary/locallibrary/settings.py), and update the TEMPLATES section's 'DIRS' line as shown.

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...

Login template

Create a new HTML file called /locallibrary/templates/registration/login.html and give it the following contents:

{% extends "base_generic.html" %}

{% block content %}

{% if form.errors %}
  <p>Your username and password didn't match. Please try again.</p>
{% endif %}

{% if next %}
  {% if user.is_authenticated %}
    <p>Your account doesn't have access to this page. To proceed,
    please login with an account that has access.</p>
  {% else %}
    <p>Please login to see this page.</p>
  {% endif %}
{% endif %}

<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>

<tr>
  <td>{{ form.username.label_tag }}</td>
  <td>{{ form.username }}</td>
</tr>

<tr>
  <td>{{ form.password.label_tag }}</td>
  <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{# Assumes you setup the password_reset view in your URLconf #}
<p><a href="{% url 'password_reset' %}">Lost password?</a></p>

{% endblock %}

Navigate back to the login page (http://127.0.0.1:8000/accounts/login/) If you try to log in that will succeed and you'll be redirected to another page (by default this will be http://127.0.0.1:8000/accounts/profile/). The problem here is that, by default, Django expects that after login you will want to be taken to a profile page, which may or may not be the case. As you haven't defined this page yet, you'll get another error!

Open the project settings (/locallibrary/locallibrary/settings.py) and add the text below to the bottom. Now when you log in you should be redirected to the site homepage by default.

# Redirect to home URL after login (Default redirects to `/accounts/profile/`)
LOGIN_REDIRECT_URL = '/'

Logout template

If you navigate to the logout URL (http://127.0.0.1:8000/accounts/logout/) then you'll see some odd behaviour — your user will be logged out sure enough, but you'll be taken to the Admin logout page. That's not what you want, if only because the login link on that page takes you to the Admin login screen (and that is only available to users who have the is_staff permission).

Create and open /locallibrary/templates/registration/logged_out.html. Copy in the text below:

{% extends "base_generic.html" %}

{% block content %}
  <p>Logged out!</p>  
  <a href="{% url 'login'%}">Click here to login again.</a>
{% endblock %}

Password reset templates

Password reset form

This is the form used to get the user's email address (for sending the password reset email). Create /locallibrary/templates/registration/password_reset_form.html, and give it the following contents:

{% extends "base_generic.html" %}

{% block content %}
  <form action="" method="post">
  {% csrf_token %}
  {% if form.email.errors %}
    {{ form.email.errors }}
  {% endif %}
      <p>{{ form.email }}</p> 
    <input type="submit" class="btn btn-default btn-lg" value="Reset password">
  </form>
{% endblock %}

Password reset done

This form is displayed after your email address has been collected. Create /locallibrary/templates/registration/password_reset_done.html, and give it the following contents:

{% extends "base_generic.html" %}

{% block content %}
  <p>
     We've emailed you instructions for setting your password. 
     If they haven't arrived in a few minutes, check your spam folder.
  </p>
{% endblock %}

Password reset email

This template provides the text of the HTML email containing the reset link that we will send to users. Create /locallibrary/templates/registration/password_reset_email.html, and give it the following contents:

Someone asked for password reset for email {{ email }}. Follow the link below:
{{ protocol}}://{{ domain }} \ 
                 {% url 'password_reset_confirm' uidb64=uid token=token %}

Password reset confirm

This page is where you enter your new password after clicking the link in the password reset email. Create /locallibrary/templates/registration/password_reset_confirm.html, and give it the following contents:

{% extends "base_generic.html" %}

{% block content %}
    {% if validlink %}
        <p>Please enter (and confirm) your new password.</p>
        <form action="" method="post">
        {% csrf_token %}
            <table>
                <tr>
                    <td>{{ form.new_password1.errors }}
                        <label for="id_new_password1">New password:</label></td>
                    <td>{{ form.new_password1 }}</td>
                </tr>
                <tr>
                    <td>{{ form.new_password2.errors }}
                        <label for="id_new_password2">
                          Confirm password:
                         </label>
                      </td>
                    <td>{{ form.new_password2 }}</td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Change my password" /></td>
                </tr>
            </table>
        </form>
    {% else %}
        <h1>Password reset failed</h1>
        <p>
          The password reset link was invalid, 
          possibly because it has already been used. 
          Please request a new password reset.
        </p>
    {% endif %}
{% endblock %}

Password reset complete

This is the last password-reset template, which is displayed to notify you when the password reset has succeeded. Create /locallibrary/templates/registration/password_reset_complete.html, and give it the following contents:

{% extends "base_generic.html" %}

{% block content %}
  <h1>The password has been changed!</h1>
  <p><a href="{% url 'login' %}">log in again?</a></p>
{% endblock %}

Testing the new authentication pages

Now that you've added the URL configuration and created all these templates, the authentication pages should now just work!

You can test the new authentication pages by attempting to log in and then logout your superuser account using these URLs:

http://127.0.0.1:8000/accounts/login/
http://127.0.0.1:8000/accounts/logout/

You'll be able to test the password reset functionality from the link in the login page. Be aware that Django will only send reset emails to addresses (users) that are already stored in its database!

Note: The password reset system requires that your website supports email, which is beyond the scope of this article, so this part won't work yet. To allow testing, put the following line at the end of your settings.py file. This logs any emails sent to the console (so you can copy the password reset link from the console).

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

For more information, see Sending email (Django docs).

Testing against authenticated users

This section looks at what we can do to selectively control content the user sees based on whether they are logged in or not.

Testing in templates

Open the base template (/locallibrary/catalog/templates/base_generic.html) and copy the following text into the sidebar block, immediately before the endblock template tag.

<ul class="sidebar-nav">

    ...

   {% if user.is_authenticated %}
     <li>User: {{ user.get_username }}</li>
     <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li>   
   {% else %}
     <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li>   
   {% endif %} 
  </ul>

Note: Try it out! If you're on the home page and you click Login/Logout in the sidebar, then after the operation completes you should end up back on the same page.

Listing the current user's books

Models

Open catalog/models.py, and import the User model from django.contrib.auth.models (add this just below the previous import line at the top of the file, so User is available to subsequent code that makes use of it):

from django.contrib.auth.models import User

Next add the borrower field to the BookInstance model:

borrower = models.ForeignKey(User, 
                             on_delete=models.SET_NULL, 
                             null=True, blank=True)

While we're here, let's add a property that we can call from our templates to tell if a particular book instance is overdue. While we could calculate this in the template itself, using a property as shown below will be much more efficient.

Add this somewhere near the top of the file:

from datetime import date

Now add the following property definition to the BookInstance class:

@property
def is_overdue(self):
    if self.due_back and date.today() > self.due_back:
        return True
    return False

Note: We first verify whether due_back is empty before making a comparison. An empty due_back field would cause Django to throw an error instead of showing the page: empty values are not comparable. This is not something we would want our users to experience!

Now that we've updated our models, we'll need to make fresh migrations on the project and then apply those migrations:

python3 manage.py makemigrations
python3 manage.py migrate

Admin

Now open catalog/admin.py, and add the borrower field to the BookInstanceAdmin class in both the list_display and the fieldsets as shown below. This will make the field visible in the Admin section, allowing us to assign a User to a BookInstance when needed.

@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
    list_display = ('book', 'status', 
                    'borrower', 'due_back', 'id')
    list_filter = ('status', 'due_back')
    
    fieldsets = (
        (None, {
            'fields': ('book','imprint', 'id')
        }),
        ('Availability', {
            'fields': ('status', 'due_back', 'borrower')
        }),
    )

Loan a few books

Now that it's possible to loan books to a specific user, go and loan out a number of BookInstance records. Set their borrowed field to your test user, make the status "On loan", and set due dates both in the future and the past.

On loan view

Now we'll add a view for getting the list of all books that have been loaned to the current user. We'll use the same generic class-based list view we're familiar with, but this time we'll also import and derive from LoginRequiredMixin, so that only a logged in user can call this view. We will also choose to declare a template_name, rather than using the default, because we may end up having a few different lists of BookInstance records, with different views and templates.

Add the following to catalog/views.py:

from django.contrib.auth.mixins import LoginRequiredMixin

class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
    """Generic class-based view listing books on loan to current user."""
    model = BookInstance
    template_name ='catalog/bookinstance_list_borrowed_user.html'
    paginate_by = 10
    
    def get_queryset(self):
        return BookInstance.objects.filter(
                                          borrower=self.request.user
                                          ).filter(status__exact='o'
                                                   ).order_by('due_back')

In order to restrict our query to just the BookInstance objects for the current user, we re-implement get_queryset() as shown above. Note that "o" is the stored code for **"on loan" ** and we order by the due_back date so that the oldest items are displayed first.

URL conf for on loan books

Now open /catalog/urls.py and add a path() pointing to the above view (you can just copy the text below to the end of the file).

urlpatterns += [   
    path('mybooks/', views.LoanedBooksByUserListView.as_view(), 
                                           name='my-borrowed'),
]

Template for on-loan books

Now all we need to do for this page is add a template. First, create the template file /catalog/templates/catalog/bookinstance_list_borrowed_user.html and give it the following contents:

{% extends "base_generic.html" %}

{% block content %}
    <h1>Borrowed books</h1>

    {% if bookinstance_list %}
    <ul>

      {% for bookinst in bookinstance_list %} 
      <li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
        <a href="{% url 'book-detail' bookinst.book.pk %}">
         {{bookinst.book.title}}
        </a> ({{ bookinst.due_back }})        
      </li>
      {% endfor %}
    </ul>

    {% else %}
      <p>There are no books borrowed.</p>
    {% endif %}       
{% endblock %}

When the development server is running, you should now be able to view the list for a logged in user in your browser at http://127.0.0.1:8000/catalog/mybooks/. Try this out with your user logged in and logged out (in the second case, you should be redirected to the login page).

Add the list to the sidebar

The very last step is to add a link for this new page into the sidebar. We'll put this in the same section where we display other information for the logged in user.

Open the base template (/locallibrary/catalog/templates/base_generic.html) and add the line in bold to the sidebar as shown.

<ul class="sidebar-nav">
   {% if user.is_authenticated %}
   <li>User: {{ user.get_username }}</li>
   <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li>
   <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li>   
   {% else %}
   <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li>   
   {% endif %} 
 </ul>

What does it look like?

When any user is logged in, they'll see the My Borrowed link in the sidebar, and the list of books displayed as below (the first book has no due date, which is a bug we hope to fix in a later tutorial!).

Permissions

Models

Defining permissions is done on the model "class Meta" section, using the permissions field. You can specify as many permissions as you need in a tuple, each permission itself being defined in a nested tuple containing the permission name and permission display value. For example, we might define a permission to allow a user to mark that a book has been returned as shown:

class BookInstance(models.Model):
    ...
    class Meta:
        ...        
        permissions = (("can_mark_returned", "Set book as returned"),) 
python3 manage.py makemigrations
python3 manage.py migrate

Templates

vim catalog/base_generic.html
{% block sidebar %}
 <ul class="sidebar-nav">
  <li><a href="/admin/">Login as admin</a></li>
  <hr>
  <li><a href="{% url 'index' %}">Home</a></li>
  <li><a href="{% url 'books' %}">All books</a></li>
  <li><a href="{% url 'authors' %}">All authors</a></li>
  <hr>
  {% if user.is_authenticated %}
    <li>User: {{ user.get_username }}</li>
    <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li>
    <li><a href="{% url 'logout' %}?next={{request.path}}">Logout</a></li>
  {% else %}
    <li><a href="{% url 'login' %}?next={{request.path}}">Login</a></li>
  {% endif %}
  </ul>

  {% if user.is_staff %}
  <hr />
  <ul class="sidebar-nav">
    <li>Staff</li>
    {% if perms.catalog.can_mark_returned %}
      <li><a href="{% url 'all-borrowed' %}">All borrowed</a></li>
    {% endif %}
   </ul>
  {% endif %}
{% endblock %}

Views

# For Librarians
from django.contrib.auth.mixins import PermissionRequiredMixin

class LoanedBooksAllsListView(PermissionRequiredMixin,generic.ListView):
    """
    Generic class-based view listing of all borrowed books.
    """
    model = BookInstance
    permission_required = 'catalog.can_mark_returned'
    template_name = 'catalog/bookinstance_list_borrowed_all.html'
    paginate_by = 10

    def get_queryset(self):
        return BookInstance.objects.filter(status__exact='o').order_by('due_back')

Admin Site

Add permission for 'Librarians' group as Choosen permission => catalog|book instance|Set book as returned. Add permission (enable checkbox) 'Staff status' for all users from 'Librarians' group.

Summary

Excellent work — you've now created a website that library members can log in into and view their own content and that librarians (with the correct permission) can use to view all loaned books and their borrowers. At the moment we're still just viewing content, but the same principles and techniques are used when you want to start modifying and adding data.

In our next article we'll look at how you can use Django forms to collect user input, and then start modifying some of our stored data.

See also

User authentication in Django (Django docs)

Using the (default) Django authentication system (Django docs)

Introduction to class-based views > Decorating class-based views (Django docs)

Read full version

⚠️ **GitHub.com Fallback** ⚠️