Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

05 Authentication

Peter Bittner edited this page Jan 13, 2017 · 5 revisions

Overview

Currently anyone can see these new pages because there is no authentication in place.

By the way, we'll talk about "authentication" and "authorization" a little bit in this class. Keep in mind that:

  • Authentication = login + password (who you are)
  • Authorization = permissions (what you are allowed to do)

(If you want to read more: http://stackoverflow.com/questions/6556522/authentication-versus-authorization)

URLs

Before we can lock down our views we need to create a way for users to login to our site.

Change your root URLs file elevennote/urls.py to look like this: from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from django.http import HttpResponseRedirect

urlpatterns = [
    # Handle the root url.
    url(r'^$', lambda r: HttpResponseRedirect('notes/')),

    # Admin
    url(r'^admin/', include(admin.site.urls)),

    # Registration
    url(r'^accounts/login/$', auth_views.login, name='login'),
    url(r'^accounts/logout/$', auth_views.logout),
 
    # Our app
    url(r'^notes/', include('note.urls', namespace="note")),
]

Notice this line? url(r'^$', lambda r: HttpResponseRedirect('notes/')),

That provided a redirect so that http://localhost:8000/ goes to our app. Try it out.

Templates

We will need a template for our new login page.

First run this command: mkdir note/templates/registration

And then create note/templates/registration/login.html:

<form action="{% url 'login' %}" method="post" accept-charset="utf-8">
  {% csrf_token %}
  {% for field in form %}
    <label>{{ field.label }}</label>
    {% if field.errors %}
      {{ field.errors }}
    {% endif %}
    {{ field }}
  {% endfor %}
  <input type="hidden" name="next" value="{{ next }}" />
  <input class="button small" type="submit" value="Submit"/>
</form>

Views

Django provides an easy way to specify that a view requires a user to login. Import the login_required decorator and apply it to both your views:

In note/views.py:

...
from django.contrib.auth.decorators import login_required

@login_required
def index(request):
    ...

@login_required
def detail(request, note_id):
    ...

You don't need to understand decorators now to use these, but if decorators in Python are new to you there are a lot of resources to help you understand what they are doing.