SlideShare a Scribd company logo
07/03/14 DjangoSummer 2014 1
User Authentication
TwD CH8
使用者認證機制
Speaker: asika Kuo
For DjangoSummer
DjangoSummer 2014 2
Overview
● Setting up Authentication
– 使用者認證機制的基礎設施
● django.contrib.auth
● UserModel/ModelForm/templates/views/URLMappings
● Adding Login Functionality
– 實作登入功能
● Restricting Access
– 利用 python decorator 實作限制訪問的功能
● Logging Out
DjangoSummer 2014 3
Note
● 其實 django 已經有很多使用者認證的套件,實務上大家直接去找一
套來用就好(基於不重複造輪子原則你也應該這麼做)
– https://www.djangopackages.com/grids/g/registration/
– https://bitbucket.org/ubernostrum/django-registration/wiki/Home
–
● 不過本章會從頭開始教起
– 讓大家對於使用者認證該有的功能有個認識
– 之前章節內容的加強版演練
● Working with forms
● Extend upon the user model
● Upload media
DjangoSummer 2014 4
8. User Authentication
● django.contrib.auth
– Django的標準安裝中就會包含的 application,提供使用者認證機制
– Contains
● Users
● Permissions: a series of binary flags (e.g. yes/no) determining what a user may
or may not do
● Groups: a method of applying permissions to more than one user
● A configurable password hashing system: a must for ensuring data security
● Forms and view tools for logging in users, or restricting content
● A pluggable backend system, allowing you to provide your own authentication-
related functionality
DjangoSummer 2014 5
8.1. Setting up Authentication
● Install auth application
– tango_with_django_project/settings.py
INSTALLED_APPS = (
'django.contrib.auth', # THIS LINE SHOULD BE PRESENT AND
UNCOMMENTED
'django.contrib.contenttypes', # THIS LINE SHOULD BE PRESENT
AND UNCOMMENTED
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'rango',
)
DjangoSummer 2014 6
8.1. Setting up Authentication
● django.contrib.auth
– Provides Django with access to the authentication system
● django.contrib.contenttypes
– Used by the authentication application to track models
installed in your database
註:裝完這兩個 application 以後記得去
syncdb
DjangoSummer 2014 7
8.1. Setting up Authentication
● Django 預設使用 PBKDF2 演算法做密碼的 hashing
● 假如還需要更高的安全性的話,也可以替換成其他方法
DjangoSummer 2014 8
8.2. The User Model
● User
– Django 認證系統的核心類別
● django.contrib.auth.models.User
– 代表每一個 Django application 的使用者
– 被認證系統使用的場合:
● Access restriction
● New user registerion
● Association of creators with site content
DjangoSummer 2014 9
8.2. The User Model
● User model
– 主要的屬性
● Username
● Password
● Email address
● User's Firstname
● User's Surname
– 其他
● is_active
● ...
DjangoSummer 2014 10
8.3. Additional User Attributes
● User model 提供基本的使用者該有的屬性
– 還不夠的話怎麼辦?
● Rango application 想要附加兩個屬性
– 一個 URLField ,讓使用者提供自己的 website
– 一個 ImageField ,上傳使用者的頭像
DjangoSummer 2014 11
8.3. Additional User Attributes
●
rango/models.py 增加 UserProfile model class
from django.contrib.auth.models import User
class UserProfile(models.Model):
# 和現有的 User object 對 1-1 對應
user = models.OneToOneField(User)
# 我們要附加上去的屬性
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images',
blank=True)
# 覆寫掉原本的 __unicode__() 來印出我們想顯示的物件內容
def __unicode__(self):
return self.user.username
DjangoSummer 2014 12
8.3. Additional User Attributes
● 範例當中是用與 User object 建立 1-to-1 對映的方法來達到
增加新屬性的目的
– 除此之外也可以直接繼承 User model 來新增屬性
– 但此處建議不同的 application 都可以直接利用 User
object 做 1-to-1 對映,再將自己的屬性附加上去
● 通用性較高且維護較容易?
DjangoSummer 2014 13
8.3. Additional User Attributes
●
●
●
●
●
●
blank=True 代表屬性可留空白
●
upload_to 參數是圖片上傳後放置的目錄
– <MEDIA_ROOT>/profile_images
from django.contrib.auth.models import User
class UserProfile(models.Model):
# 我們要附加上去的屬性
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images',
blank=True)
DjangoSummer 2014 14
8.3. Additional User Attributes
●
rango/admin.py 註冊新的 Model
– admin.site.register(UserProfile)
●
記得每次建立新的 model 就要去 syncdb
DjangoSummer 2014 15
8.4. Creating a User Registration View and
Template
● 至此我們已經建立了使用者認證的基礎建設
● 接下來要增加註冊使用者的功能
– 建立 UserForm 和 UserProfileForm
– 建立處理新增使用者的 view
– 建立用來顯示 Form 的 template
– 建立 view 的 URL mapping
– 在 index 加上新增使用者的連結
DjangoSummer 2014 16
8.4.1. Creating the UserForm and
UserProfileForm
●
在 rango/forms.py 建立 UserForm 和 UserProfileForm ,分
別對應到我們之前建立的 models
class UserForm(forms.ModelForm):
password = forms.CharField(
widget=forms.PasswordInput()
)
class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
DjangoSummer 2014 17
8.4.1. Creating the UserForm and
UserProfileForm
● Meta
– Form 類別的內部屬性
– model
● 至少需要指定和 Form 關聯的 Model 類別
● UserForm --> UserModel
● (不關聯會怎樣?)
– ValueError: ModelForm has no model class specified
● (關聯不對會怎樣?)
– FieldError: Unknown field(s) (username, email) specified for
UserProfile
– field
● 需要 render 成 HTML 的欄位列表
DjangoSummer 2014 18
8.4.1. Creating the UserForm and
UserProfileForm
● password =
forms.CharField(widget=forms.PasswordInput())
– 如果這裡不特別指定 HTML form element 的屬性的話,
password 還是會依照 model 所定義的型別
( CharField )被 render 出來,但會變成明碼輸出
DjangoSummer 2014 19
8.4.2. Creating the register() View
registered=False
是否為 POST?
取得 Form 的資料
創建空的
UserForm 和
UserProfileForm
物件
表單資料是否
通過驗證?
從 UserForm
創建 UserModel 物件
並寫回 DB
user.set_password()
並寫回 DB
從 UserProfileForm
創建 UserProfile 物件
並對映 user
如果有上傳頭像就
記錄到 UserProfile
把 UserProfile
寫回 DB
印出錯誤訊息
registered=True
接受 request
根據回應內容
render template
DjangoSummer 2014 20
8.4.3. Creating the Registration Template
●
建立 templates/rango/register.html
● as_p
– Render form input 時把每個項目用 <p> 包裝起來
– 此外還有 as_table/as_ul
● enctype="multipart/form-data”
– 如果 form 的內容包含檔案上傳時則必須用這種 POST encode 方式
– 檔案會被分割成一系列的 chunk 再傳回給 server
● csrf_token
– 必須要包含在 form 當中
DjangoSummer 2014 21
up
vote305down
voteaccepted
When you make a POST request, you have to encode the data that forms the body of the
request in some way.
HTML forms provide two methods of encoding. The default is application/x-www-form-
urlencoded, which is more or less the same as a query string on the end of the URL. The
other, multipart/form-data, is a more complicated encoding but one which allows entire
files to be included in the data. (HTML 5 introduces the text/plain encoding which is
useful only for debugging … and even then the others are better given sensible debugging
tools).
The specifics of the encodings don't really matter to most developers.
When you are writing client-side code: Use multipart/form-data when your form
includes any <input type="file"> elements.
When you are writing server-side code: Use a prewritten form handling library (e.g. Perl's
CGI->param or the one exposed by PHP's $_POST superglobal) and it will take care of the
differences for you. Don't bother trying to parse the raw input received by the server.
share|improve this answeredited Sep 17 '13 at 13:56
answered Dec 24 '10 at 12:21
upvote247down vote
favorite
78
What does enctype='multipart/form-data' mean in a form and when should we use
it.
html
share|improve this questionedited Jul 23 '12 at 11:44
asked Dec 24 '10 at 12:19
DjangoSummer 2014 22
8.4.4. The register() View URL Mapping
●
修改 rango/urls.py
●
●
●
●
修改 templates/rango/index.html
– <a href="/rango/register/">Register Here</a>
urlpatterns = patterns('',
...
# ADD NEW PATTERN!
url(r'^register/$', views.register, name='register'),
)
DjangoSummer 2014 23
8.5. Adding Login Functionality
● Workflow
– Create a login in view to handle user credentials
– Create a login template to display the login form
– Map the login view to a url
– Provide a link to login from the index page
DjangoSummer 2014 24
8.5.1. Creating the login() View
● authenticate(**credentials)
– Returns a User object if the password is valid for the
given username. If the password is invalid,
authenticate() returns None
● login()
– To log a user in, from a view, use login(). It takes an
HttpRequest object and a User object. login() saves the
user’s ID in the session, using Django’s session
framework
DjangoSummer 2014 25
8.5.1. Creating the login() View
● HttpResponseRedirect
– 告知使用者的瀏覽器跳轉到指定的網址
– HTTP status code=302
● Note: HttpResponse 物件預設回傳 status code=200
(OK)
DjangoSummer 2014 26
8.5.2. Creating a Login Template
●
手刻 templates/rango/login.html
<!DOCTYPE html>
<html>
<body> 中略
<form id="login_form" method="post" action="/rango/login/">
{% csrf_token %}
Username: <input type="text" name="username" value=""
size="50" />
<br />
Password: <input type="password" name="password" value=""
size="50" />
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>
DjangoSummer 2014 27
8.5.3. Mapping the Login View to a URL
● rango/urls.py
urlpatterns = patterns('',
中略
url(r'^login/$', views.user_login, name='login'),
)
DjangoSummer 2014 28
8.5.4. Linking Together
●
修改 templates/rango/index.html
– 在 template 中檢查使用者是否已經登入
{% if user.is_authenticated %}
<h1>Rango says... hello {{ user.username }}!</h1>
{% else %}
<h1>Rango says... hello world!</h1>
{% endif %}
註:為什麼在 template 裡可以存取 user 變數?
Django 預設的 TEMPLATE_CONTEXT_PROCESSORS 即包含
django.core.context_processors.auth ,當我們在 rango.views.index() 呼叫
render_to_response() 做 render 時會自動包含 user 變數進去
DjangoSummer 2014 29
8.6. Restricting Access
● 8.6.1. Restricting Access with a Decorator
– 利用 auth 模組的 login_required decorator 來修飾 views.restricted()
– 如果已經 login 會回傳 HttpResponse 否則會導向 LOGIN_URL
●
● login_required()
– If the user isn’t logged in, redirect to settings.LOGIN_URL, passing
the current absolute path in the query string. Example:
/accounts/login/?next=/polls/3/
– If the user is logged in, execute the view normally. The view code is
free to assume the user is logged in
DjangoSummer 2014 30
8.6. Restricting Access
● Python Decorator
– 包裝現有的 function
●
傳入 function --> 傳出 function
– 在不修改 function 內部的情況下添加
新的功能
– 程式員可以把一些會大量使用的檢查
動作 ( 例如權限 ) 寫成 decorator ,
再包覆到會執行動作的 method 或
function 上。可以節省大量的重覆程
式碼,同時讓程式更加簡單易懂
def check_div_zero(func):
def deco(a, b):
if a * b == 0:
alert(".....")
return
func(a, b)
return deco
@check_div_zero
def div(a, b):
return a / b
## 等同於以下寫法
def div2(a, b):
return a / b
div2 = check_div_zero(div2)
http://python.org.tw/Python/Cookbook/Decorator
DjangoSummer 2014 31
8.7. Logging Out
●
使用 django 提供的 logout() 確保使用者確實登出,且
session 已經結束
●
修改 rango/views.py
from django.contrib.auth import logout
# Use the login_required() decorator to ensure only those
logged in can access the view.
@login_required
def user_logout(request):
# Since we know the user is logged in, we can now just log
them out.
logout(request)
# Take the user back to the homepage.
return HttpResponseRedirect('/rango/')
DjangoSummer 2014 32
8.7. Logging Out
●
建立 URL mapping
●
●
●
●
修改 index.html 把登入前後的功能區分開來
{% if user.is_authenticated %}
<a href="/rango/restricted/">Restricted Page</a><br />
<a href="/rango/logout/">Logout</a><br />
{% else %}
<a href="/rango/register/">Register Here</a><br />
<a href="/rango/login/">Login</a><br />
{% endif %}
urlpatterns = patterns('',
...
url(r'^logout/$', views.user_logout, name='logout'),
)
DjangoSummer 2014 33
8.8. Exercises
● 本章總結
– 利用 django.contrib.auth 做認證
– 在基本的 User model 之外附加額外的使用者資訊
– 實作 login/logout/restrict 功能
●
● 本章練習
– 把 APP 改成使用者登入後才能新增 Category/Page
– 沒登入只能看
– 如果使用者輸入的登入資訊不正確,提供適當的錯誤訊息
– 利用 django-registration 提供進階功能
● Email 信箱認證
● 寄送密碼

More Related Content

What's hot (20)

Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
John.Jian.Fang
 
Implementing security routines with zf2
Implementing security routines with zf2Implementing security routines with zf2
Implementing security routines with zf2
Er Galvão Abbott
 
Jwis2011 ruo ando
Jwis2011 ruo andoJwis2011 ruo ando
Jwis2011 ruo ando
Ruo Ando
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
People Strategists
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
Pierre Sudron
 
Web2 - jQuery
Web2 - jQueryWeb2 - jQuery
Web2 - jQuery
voicerepublic
 
前端概述
前端概述前端概述
前端概述
Ethan Zhang
 
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksJSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
Mario Heiderich
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig
 
Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
Manuel Carrasco Moñino
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
tutorialsruby
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
Fabrizio Giudici
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
Robbie Cheng
 
Обзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScriptОбзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScript
COMAQA.BY
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
Adam Culp
 
JSF Custom Components
JSF Custom ComponentsJSF Custom Components
JSF Custom Components
Michael Fons
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
Jyothishmathi Institute of Technology and Science Karimnagar
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
John.Jian.Fang
 
Implementing security routines with zf2
Implementing security routines with zf2Implementing security routines with zf2
Implementing security routines with zf2
Er Galvão Abbott
 
Jwis2011 ruo ando
Jwis2011 ruo andoJwis2011 ruo ando
Jwis2011 ruo ando
Ruo Ando
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
Pierre Sudron
 
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksJSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
Mario Heiderich
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
Fabrizio Giudici
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
Robbie Cheng
 
Обзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScriptОбзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScript
COMAQA.BY
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
Adam Culp
 
JSF Custom Components
JSF Custom ComponentsJSF Custom Components
JSF Custom Components
Michael Fons
 

Viewers also liked (7)

Inggris1
Inggris1Inggris1
Inggris1
ahankshabieb
 
Social media sentinel
Social media sentinelSocial media sentinel
Social media sentinel
Text Amsterdam
 
tangowithdjango - Ch12
tangowithdjango - Ch12tangowithdjango - Ch12
tangowithdjango - Ch12
Asika Kuo
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15
Asika Kuo
 
нептун
нептуннептун
нептун
DRNanno
 
Bahasa Inggris IX
Bahasa Inggris IXBahasa Inggris IX
Bahasa Inggris IX
ahankshabieb
 
History of the Caldecott Medal
History of the Caldecott MedalHistory of the Caldecott Medal
History of the Caldecott Medal
cutebluefrog
 
tangowithdjango - Ch12
tangowithdjango - Ch12tangowithdjango - Ch12
tangowithdjango - Ch12
Asika Kuo
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15
Asika Kuo
 
нептун
нептуннептун
нептун
DRNanno
 
History of the Caldecott Medal
History of the Caldecott MedalHistory of the Caldecott Medal
History of the Caldecott Medal
cutebluefrog
 

Similar to TangoWithDjango - ch8 (20)

Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engine
Michael Parker
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
Alessandro Molina
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
 
Drupal Security Hardening
Drupal Security HardeningDrupal Security Hardening
Drupal Security Hardening
Gerald Villorente
 
Drupal Security Hardening
Drupal Security HardeningDrupal Security Hardening
Drupal Security Hardening
Gerald Villorente
 
Client Actions In Odoo 17 - Odoo 17 Slides
Client Actions In Odoo 17 - Odoo 17 SlidesClient Actions In Odoo 17 - Odoo 17 Slides
Client Actions In Odoo 17 - Odoo 17 Slides
Celine George
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Drupal 8 entities & felds
Drupal 8 entities & feldsDrupal 8 entities & felds
Drupal 8 entities & felds
Andy Postnikov
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
Gabriel Walt
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
Giuliano Iacobelli
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Dive into Play Framework
Dive into Play FrameworkDive into Play Framework
Dive into Play Framework
Maher Gamal
 
Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docx
fantabulous2024
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
murtazahaveliwala
 
Django Frequently Asked Interview Questions
Django Frequently Asked Interview QuestionsDjango Frequently Asked Interview Questions
Django Frequently Asked Interview Questions
AshishMishra308598
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
 
.Net template solution architecture
.Net template solution architecture.Net template solution architecture
.Net template solution architecture
Diogo Gonçalves da Cunha
 
IBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocial
IBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocialIBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocial
IBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocial
IBM Connections Developers
 
Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engine
Michael Parker
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
Alessandro Molina
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
 
Client Actions In Odoo 17 - Odoo 17 Slides
Client Actions In Odoo 17 - Odoo 17 SlidesClient Actions In Odoo 17 - Odoo 17 Slides
Client Actions In Odoo 17 - Odoo 17 Slides
Celine George
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Drupal 8 entities & felds
Drupal 8 entities & feldsDrupal 8 entities & felds
Drupal 8 entities & felds
Andy Postnikov
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
Gabriel Walt
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
Giuliano Iacobelli
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Dive into Play Framework
Dive into Play FrameworkDive into Play Framework
Dive into Play Framework
Maher Gamal
 
Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docx
fantabulous2024
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
murtazahaveliwala
 
Django Frequently Asked Interview Questions
Django Frequently Asked Interview QuestionsDjango Frequently Asked Interview Questions
Django Frequently Asked Interview Questions
AshishMishra308598
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
 
IBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocial
IBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocialIBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocial
IBM Connect 2014 - JMP103: Extending Your Application Arsenal With OpenSocial
IBM Connections Developers
 

Recently uploaded (20)

ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 

TangoWithDjango - ch8

  • 1. 07/03/14 DjangoSummer 2014 1 User Authentication TwD CH8 使用者認證機制 Speaker: asika Kuo For DjangoSummer
  • 2. DjangoSummer 2014 2 Overview ● Setting up Authentication – 使用者認證機制的基礎設施 ● django.contrib.auth ● UserModel/ModelForm/templates/views/URLMappings ● Adding Login Functionality – 實作登入功能 ● Restricting Access – 利用 python decorator 實作限制訪問的功能 ● Logging Out
  • 3. DjangoSummer 2014 3 Note ● 其實 django 已經有很多使用者認證的套件,實務上大家直接去找一 套來用就好(基於不重複造輪子原則你也應該這麼做) – https://www.djangopackages.com/grids/g/registration/ – https://bitbucket.org/ubernostrum/django-registration/wiki/Home – ● 不過本章會從頭開始教起 – 讓大家對於使用者認證該有的功能有個認識 – 之前章節內容的加強版演練 ● Working with forms ● Extend upon the user model ● Upload media
  • 4. DjangoSummer 2014 4 8. User Authentication ● django.contrib.auth – Django的標準安裝中就會包含的 application,提供使用者認證機制 – Contains ● Users ● Permissions: a series of binary flags (e.g. yes/no) determining what a user may or may not do ● Groups: a method of applying permissions to more than one user ● A configurable password hashing system: a must for ensuring data security ● Forms and view tools for logging in users, or restricting content ● A pluggable backend system, allowing you to provide your own authentication- related functionality
  • 5. DjangoSummer 2014 5 8.1. Setting up Authentication ● Install auth application – tango_with_django_project/settings.py INSTALLED_APPS = ( 'django.contrib.auth', # THIS LINE SHOULD BE PRESENT AND UNCOMMENTED 'django.contrib.contenttypes', # THIS LINE SHOULD BE PRESENT AND UNCOMMENTED 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'rango', )
  • 6. DjangoSummer 2014 6 8.1. Setting up Authentication ● django.contrib.auth – Provides Django with access to the authentication system ● django.contrib.contenttypes – Used by the authentication application to track models installed in your database 註:裝完這兩個 application 以後記得去 syncdb
  • 7. DjangoSummer 2014 7 8.1. Setting up Authentication ● Django 預設使用 PBKDF2 演算法做密碼的 hashing ● 假如還需要更高的安全性的話,也可以替換成其他方法
  • 8. DjangoSummer 2014 8 8.2. The User Model ● User – Django 認證系統的核心類別 ● django.contrib.auth.models.User – 代表每一個 Django application 的使用者 – 被認證系統使用的場合: ● Access restriction ● New user registerion ● Association of creators with site content
  • 9. DjangoSummer 2014 9 8.2. The User Model ● User model – 主要的屬性 ● Username ● Password ● Email address ● User's Firstname ● User's Surname – 其他 ● is_active ● ...
  • 10. DjangoSummer 2014 10 8.3. Additional User Attributes ● User model 提供基本的使用者該有的屬性 – 還不夠的話怎麼辦? ● Rango application 想要附加兩個屬性 – 一個 URLField ,讓使用者提供自己的 website – 一個 ImageField ,上傳使用者的頭像
  • 11. DjangoSummer 2014 11 8.3. Additional User Attributes ● rango/models.py 增加 UserProfile model class from django.contrib.auth.models import User class UserProfile(models.Model): # 和現有的 User object 對 1-1 對應 user = models.OneToOneField(User) # 我們要附加上去的屬性 website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images', blank=True) # 覆寫掉原本的 __unicode__() 來印出我們想顯示的物件內容 def __unicode__(self): return self.user.username
  • 12. DjangoSummer 2014 12 8.3. Additional User Attributes ● 範例當中是用與 User object 建立 1-to-1 對映的方法來達到 增加新屬性的目的 – 除此之外也可以直接繼承 User model 來新增屬性 – 但此處建議不同的 application 都可以直接利用 User object 做 1-to-1 對映,再將自己的屬性附加上去 ● 通用性較高且維護較容易?
  • 13. DjangoSummer 2014 13 8.3. Additional User Attributes ● ● ● ● ● ● blank=True 代表屬性可留空白 ● upload_to 參數是圖片上傳後放置的目錄 – <MEDIA_ROOT>/profile_images from django.contrib.auth.models import User class UserProfile(models.Model): # 我們要附加上去的屬性 website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images', blank=True)
  • 14. DjangoSummer 2014 14 8.3. Additional User Attributes ● rango/admin.py 註冊新的 Model – admin.site.register(UserProfile) ● 記得每次建立新的 model 就要去 syncdb
  • 15. DjangoSummer 2014 15 8.4. Creating a User Registration View and Template ● 至此我們已經建立了使用者認證的基礎建設 ● 接下來要增加註冊使用者的功能 – 建立 UserForm 和 UserProfileForm – 建立處理新增使用者的 view – 建立用來顯示 Form 的 template – 建立 view 的 URL mapping – 在 index 加上新增使用者的連結
  • 16. DjangoSummer 2014 16 8.4.1. Creating the UserForm and UserProfileForm ● 在 rango/forms.py 建立 UserForm 和 UserProfileForm ,分 別對應到我們之前建立的 models class UserForm(forms.ModelForm): password = forms.CharField( widget=forms.PasswordInput() ) class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website', 'picture')
  • 17. DjangoSummer 2014 17 8.4.1. Creating the UserForm and UserProfileForm ● Meta – Form 類別的內部屬性 – model ● 至少需要指定和 Form 關聯的 Model 類別 ● UserForm --> UserModel ● (不關聯會怎樣?) – ValueError: ModelForm has no model class specified ● (關聯不對會怎樣?) – FieldError: Unknown field(s) (username, email) specified for UserProfile – field ● 需要 render 成 HTML 的欄位列表
  • 18. DjangoSummer 2014 18 8.4.1. Creating the UserForm and UserProfileForm ● password = forms.CharField(widget=forms.PasswordInput()) – 如果這裡不特別指定 HTML form element 的屬性的話, password 還是會依照 model 所定義的型別 ( CharField )被 render 出來,但會變成明碼輸出
  • 19. DjangoSummer 2014 19 8.4.2. Creating the register() View registered=False 是否為 POST? 取得 Form 的資料 創建空的 UserForm 和 UserProfileForm 物件 表單資料是否 通過驗證? 從 UserForm 創建 UserModel 物件 並寫回 DB user.set_password() 並寫回 DB 從 UserProfileForm 創建 UserProfile 物件 並對映 user 如果有上傳頭像就 記錄到 UserProfile 把 UserProfile 寫回 DB 印出錯誤訊息 registered=True 接受 request 根據回應內容 render template
  • 20. DjangoSummer 2014 20 8.4.3. Creating the Registration Template ● 建立 templates/rango/register.html ● as_p – Render form input 時把每個項目用 <p> 包裝起來 – 此外還有 as_table/as_ul ● enctype="multipart/form-data” – 如果 form 的內容包含檔案上傳時則必須用這種 POST encode 方式 – 檔案會被分割成一系列的 chunk 再傳回給 server ● csrf_token – 必須要包含在 form 當中
  • 21. DjangoSummer 2014 21 up vote305down voteaccepted When you make a POST request, you have to encode the data that forms the body of the request in some way. HTML forms provide two methods of encoding. The default is application/x-www-form- urlencoded, which is more or less the same as a query string on the end of the URL. The other, multipart/form-data, is a more complicated encoding but one which allows entire files to be included in the data. (HTML 5 introduces the text/plain encoding which is useful only for debugging … and even then the others are better given sensible debugging tools). The specifics of the encodings don't really matter to most developers. When you are writing client-side code: Use multipart/form-data when your form includes any <input type="file"> elements. When you are writing server-side code: Use a prewritten form handling library (e.g. Perl's CGI->param or the one exposed by PHP's $_POST superglobal) and it will take care of the differences for you. Don't bother trying to parse the raw input received by the server. share|improve this answeredited Sep 17 '13 at 13:56 answered Dec 24 '10 at 12:21 upvote247down vote favorite 78 What does enctype='multipart/form-data' mean in a form and when should we use it. html share|improve this questionedited Jul 23 '12 at 11:44 asked Dec 24 '10 at 12:19
  • 22. DjangoSummer 2014 22 8.4.4. The register() View URL Mapping ● 修改 rango/urls.py ● ● ● ● 修改 templates/rango/index.html – <a href="/rango/register/">Register Here</a> urlpatterns = patterns('', ... # ADD NEW PATTERN! url(r'^register/$', views.register, name='register'), )
  • 23. DjangoSummer 2014 23 8.5. Adding Login Functionality ● Workflow – Create a login in view to handle user credentials – Create a login template to display the login form – Map the login view to a url – Provide a link to login from the index page
  • 24. DjangoSummer 2014 24 8.5.1. Creating the login() View ● authenticate(**credentials) – Returns a User object if the password is valid for the given username. If the password is invalid, authenticate() returns None ● login() – To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework
  • 25. DjangoSummer 2014 25 8.5.1. Creating the login() View ● HttpResponseRedirect – 告知使用者的瀏覽器跳轉到指定的網址 – HTTP status code=302 ● Note: HttpResponse 物件預設回傳 status code=200 (OK)
  • 26. DjangoSummer 2014 26 8.5.2. Creating a Login Template ● 手刻 templates/rango/login.html <!DOCTYPE html> <html> <body> 中略 <form id="login_form" method="post" action="/rango/login/"> {% csrf_token %} Username: <input type="text" name="username" value="" size="50" /> <br /> Password: <input type="password" name="password" value="" size="50" /> <br /> <input type="submit" value="submit" /> </form> </body> </html>
  • 27. DjangoSummer 2014 27 8.5.3. Mapping the Login View to a URL ● rango/urls.py urlpatterns = patterns('', 中略 url(r'^login/$', views.user_login, name='login'), )
  • 28. DjangoSummer 2014 28 8.5.4. Linking Together ● 修改 templates/rango/index.html – 在 template 中檢查使用者是否已經登入 {% if user.is_authenticated %} <h1>Rango says... hello {{ user.username }}!</h1> {% else %} <h1>Rango says... hello world!</h1> {% endif %} 註:為什麼在 template 裡可以存取 user 變數? Django 預設的 TEMPLATE_CONTEXT_PROCESSORS 即包含 django.core.context_processors.auth ,當我們在 rango.views.index() 呼叫 render_to_response() 做 render 時會自動包含 user 變數進去
  • 29. DjangoSummer 2014 29 8.6. Restricting Access ● 8.6.1. Restricting Access with a Decorator – 利用 auth 模組的 login_required decorator 來修飾 views.restricted() – 如果已經 login 會回傳 HttpResponse 否則會導向 LOGIN_URL ● ● login_required() – If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/ – If the user is logged in, execute the view normally. The view code is free to assume the user is logged in
  • 30. DjangoSummer 2014 30 8.6. Restricting Access ● Python Decorator – 包裝現有的 function ● 傳入 function --> 傳出 function – 在不修改 function 內部的情況下添加 新的功能 – 程式員可以把一些會大量使用的檢查 動作 ( 例如權限 ) 寫成 decorator , 再包覆到會執行動作的 method 或 function 上。可以節省大量的重覆程 式碼,同時讓程式更加簡單易懂 def check_div_zero(func): def deco(a, b): if a * b == 0: alert(".....") return func(a, b) return deco @check_div_zero def div(a, b): return a / b ## 等同於以下寫法 def div2(a, b): return a / b div2 = check_div_zero(div2) http://python.org.tw/Python/Cookbook/Decorator
  • 31. DjangoSummer 2014 31 8.7. Logging Out ● 使用 django 提供的 logout() 確保使用者確實登出,且 session 已經結束 ● 修改 rango/views.py from django.contrib.auth import logout # Use the login_required() decorator to ensure only those logged in can access the view. @login_required def user_logout(request): # Since we know the user is logged in, we can now just log them out. logout(request) # Take the user back to the homepage. return HttpResponseRedirect('/rango/')
  • 32. DjangoSummer 2014 32 8.7. Logging Out ● 建立 URL mapping ● ● ● ● 修改 index.html 把登入前後的功能區分開來 {% if user.is_authenticated %} <a href="/rango/restricted/">Restricted Page</a><br /> <a href="/rango/logout/">Logout</a><br /> {% else %} <a href="/rango/register/">Register Here</a><br /> <a href="/rango/login/">Login</a><br /> {% endif %} urlpatterns = patterns('', ... url(r'^logout/$', views.user_logout, name='logout'), )
  • 33. DjangoSummer 2014 33 8.8. Exercises ● 本章總結 – 利用 django.contrib.auth 做認證 – 在基本的 User model 之外附加額外的使用者資訊 – 實作 login/logout/restrict 功能 ● ● 本章練習 – 把 APP 改成使用者登入後才能新增 Category/Page – 沒登入只能看 – 如果使用者輸入的登入資訊不正確,提供適當的錯誤訊息 – 利用 django-registration 提供進階功能 ● Email 信箱認證 ● 寄送密碼