Layers of Authentication

Django(72)

Now if you go run the devel server, you can see that we can login, logout, and that the login|logout button is display the correct option.

Should I暴露这?

我们将回答的两个问题中的第一个是“我应该exposure这?"

在这种情况下,它意味着我们会看看我们的笔记s/note_list.html笔记s/note_detail.htmltemplates and hide editing capabilities from users who are not logged in.

We'll start with the笔记s/note_list.htmltemplate.

我们需要做的只是包装

div and{%endif%}

respectively.

然后返回应用程序,并在查看登录并注销时,查看FrontPage如何更改。

Next we need to do the same for笔记s/note_detail.htmltemplate.

First we'll exclude the JavaScript like we did before:

{%if用户.is_authenticated%}{%endif%}

Then we need to handle the displayed content as well. Because non-authenticated users can't make changes, they shouldn't be shown inputs or textfields. Instead we'll just display the content in a couple ofS和A.

.

class="detail">{%if用户.is_authenticated%}方法="post"action=“更新/”>class="text">for=“标题”>Titletype="text"name=“标题”id=“标题”value="{ {object.title}}">for=“slul”>Slugtype="text"name=“slul”id=“slul”value="{ {object.slug}}">
name="text"id="text">{ {object.text}}class="submit"type="submit"value="update note">{%else%}Title:{ {object.title}}Slug:{ {object.slug}}

{ {object.text}}

{%endif%}

现在运行该应用程序,并使用登录和删除并查看不同的票据(以及笔记列表)。

Our UI now indicates to users what permissions are available, but we still have to actually enforce those permissions. On to the next section.

Should IPermit这?

添加身份验证的最后一步是回答第二个问题:“我应该permit这?"

All four of our custom views allow creating or modifying data, so we have a pretty simple answer: no, no,,.

Accomplishing that involves five more lines of code in笔记s/views.py.

First add this import at the top:

django.contrib.auth..decoratorsimport需要登录

和then add that decorator to each of the views:

@login_requireddefcreate_note.(要求):#等等

@login_requireddefajax_create_note(要求):#等等

@login_requireddefupdate_note(要求):#等等

@login_requireddefajax_update_note(要求):#等等

Save the application, and go ahead and test that the views don't work by manually typing in the corresponding urls at/创建/,笔记//update/和so on.

Now our precious notes are actually secure.

Download

You can download the present这里git存储库的状态.

Moving Onward

虽然我们没有对此进行大量影响,但它令人印象深刻地注意到这个小测试应用程序现在在四种不同的用户方案中正确运行:JavaScript No-Auth,JavaScript Auth,No-JavaScript No-Auth,以及No-JavaScript,Auth。

当我们仔细设计系统时,我们只关注简单的二分法(JavaScript与JavaScript,经过身份验证的与身份验证),而不是必须处理处理更大的图像的指数爆发。

Hmm. Okay. Done pontificating.

With that this third entry in theDjango, jQuery & Ajaxseries comes to a close. This was originally going to be the last entry in the series, but I had an idea I've been rolling around in my head that sounds both fun and helpful,所以我决定加上最后一次欢呼。