Previous Page Next Page

Verifying Authentication

Now that you can log users in and out, you can start securing your website by verifying that users are authenticated before giving them access to your views. You can verify authentication in both your view functions and template files.

Verifying Authentication in View Functions

You can use the is_authenticated() function of the User object in a view's HttpRequest to determine if the user is authenticated. Then you can modify the view's behavior, depending on whether the user is authenticated. For example, if the user isn't authenticated, you could redirect that person to a login page, render a different view, or render only a portion of the current view.

The following code snippet shows an example of using the is_authenticated() function in a view to redirect unauthenticated users to a login page:

def secure_view(request):
    if not request.users.is_authenticated():
        return HttpResponseRedirect('/Login')

Django provides a decorator function that simplifies verification of authentication. The login_required() function verifies whether the user is authenticated. If the user isn't authenticated, this function redirects the user to the URL specified in the LOGIN_URL setting in the settings.py file. The login_required() function passes the URL of the current request to the login function as a query string using the next variable name. For example, the following code applies the login_required decorator:

@login_required(redirect_field_name='reDir')
def secure_view(request):
. . .

If the user is not authenticated, this decorator redirects the browser to the following URL, where LOGIN_URL is set to /Login and the request.get_full_path() for the secure_view() view function is /views/secure_view:

/Login?next=/views/secure_view

Did you Know?

The login_required() function also accepts an optional argument, redirect_field_name. It allows you to specify the argument name, instead of next, that should be used to pass the redirection URL to your login function:

@login_required(redirect_field_name='reDir')
def secure_view(request):


Verifying Authentication in Templates

You can also verify whether the user has been authenticated in a template by passing in a RequestContext and then accessing the User object. Then you can use the authentication information to determine how to render the template.

For example, the following code snippet verifies whether the user is authenticated before showing a table of data:

{% if user.is_authenticated %}
<table>
{{ secure_data }}
</table>
{% endif %}

Try It Yourself: Verify Authentication in Templates and Views

In this section, you will modify the base template to display a welcome message if the user is authenticated. You will also add a decorator template to the People details() view function to force users to be authenticated before they view the home page. You will also modify the home_view() function to verify authentication and pass an empty Blog list if the user isn't authenticated so that no blog entries appear on the home page.

1.
Open the iFriends/settings.py file in an editor.

2.
Add the following line of code to set the LOGIN_URL setting that the login_required() decorator function uses for logins:

LOGIN_URL ='/Login'

3.
Save the iFriends/settings.py file.

4.
Open the iFriends/People/views.py file in an editor.

5.
Add the following import statements to import the RequestContext object and the login_required() decorator function:

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

6.
Add the following decorator function, shown in Listing 15.4, to the details() view function to allow only authenticated users to view the web page:

@login_required

7.
Modify the render_to_response() call (shown in Listing 15.4) of the details() function to include the context_instance argument so that the RequestContext is available in the person_details.html template:

return render_to_response('people/person_details.html', rDict,
                    context_instance = RequestContext(request))

8.
Save the iFriends/People/views.py file.

9.
Open the iFriends/Home/views.py file in an editor.

10.
Add the following import statements to import the RequestContext login_required() decorator function:

from django.template import RequestContext

11.
Add the following lines of code, shown in Listing 15.5, to verify that the user is authenticated. If the user isn't authenticated, return an empty Blog list so that no blogs are displayed on the home page:

if request.user.is_authenticated():
    bList = Blog.objects.all()
else:
    bList = []

12.
Modify the render_to_response() call, shown in Listing 15.5, to include the context_instance argument so that the RequestContext is available in the homepage.html template:

context_instance = RequestContext(request))

13.
Save the iFriends/Home/views.py file.

14.
Open the iFriends/templates/iFriends_base.html file in an editor.

15.
Add the following table column entry, as shown in Listing 15.6, to see whether the user is authenticated. If the user is authenticated, a welcome message is displayed. If not, a link to the login page is displayed:

<td bgcolor="white"><font size="3">
    {% if user.is_authenticated %}
        Welcome {{ user.username }}.
    {% else %}
        <a href="/Login">Login</a>
    {% endif %}
</font></td>

By the Way

All the views that render templates that extend the iFriends_base.html file must include the RequestContext in the render_to_response(). Otherwise, the welcome message is not displayed for authenticated users.

16.
Save the iFriends/templates/iFriends_base.html file.

17.
Access the following URL in a browser to log out of the website:

http://127.0.0.1:8000/Logout/

Verify that you are redirected to the login page, shown in Figure 15.2.

Figure 15.2. The web page generated by the login_user() view function.


18.
Click the Home link in the navigation bar to bring up the home page. Verify that no Largest Blog is listed, as shown in Figure 15.3.

Figure 15.3. The home page view for an unauthenticated user, with a Login link and no Largest Blog link.


19.
Click one of the people in the list. Authentication should fail, because you have logged out. You should be directed back to the login page, shown in Figure 15.2.

20.
Click the Home link again to bring up the home page. Then click the Login link to verify that it links correctly to the login page.

21.
From the login page, enter a valid username and password, and verify that you are brought back to the home page. A welcome message should now be displayed instead of the Login link, and the Largest Blog link should also be listed, as shown in Figure 15.4.

Figure 15.4. The home page view for an authenticated user, with a welcome message and a Largest Blog link.


Listing 15.4. Imports and the details() View Function of the iFriends/People/views.py File

from django.template import RequestContext
from django.contrib.auth.decorators import login_required
. . .
@login_required
def details(request, pID='0', opts=()):
    rDict = {}
    p = get_object_or_404(Person, pk=pID)
    rDict['p'] = p
    quotes = Quote.objects.all()
    rDict['quotes'] = quotes
    pageLinks = ({'name': 'People', 'value': '/People/'})
    rDict['pageLinks'] = pageLinks
    return render_to_response('people/person_details.html', rDict,
                    context_instance = RequestContext(request))

Listing 15.5. Imports and the home_view() Function of the iFriends/Home/views.py File

from django.template import RequestContext
. . .
def home_view(request):
    quotes = Quote.objects.all()
    pList = Person.objects.all()
    if request.user.is_authenticated():
        bList = Blog.objects.all()
    else:
        bList = []
    return render_to_response('home/homepage.html', {
                              'quotes': quotes,
                              'pList': pList,
                              'bList': bList,},
                              context_instance = RequestContext(request))

Listing 15.6. Table Row Containing the Navigation Link and Login/Welcome Data in the iFriends/templates/iFriends_base.html File

. . .
<tr>
<td bgcolor="bbbbbbb">
    {% navLink %}
</td>
<td bgcolor="white"><font size="3">
    {% if user.is_authenticated %}
        Welcome {{ user.username }}.
    {% else %}
        <a href="/Login">Login</a>
    {% endif %}
</font></td>
</tr>
. . .


Previous Page Next Page