The Django Web Framework – Part VIII

The Django Web
Framework — Part VIII
Web Programming Course – Fall 2013
Outline
•
Tying up loose ends
•
Middleware
•
File Upload & Static Files
•
Security
2
Middleware
3
Middleware
•
It’s a light, low-level “plugin” system for globally altering
Django’s input or output.
•
Each middleware component is responsible for doing
some specific function
•
SessionMiddleware, AuthenticationMiddleware, etc.
4
Middleware
•
MIDDLEWARE_CLASSES in settings.py
•
Order is important (dependencies, for example).
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
5
6
Default Middlewares
•
CommonMiddleware
•
GZipMiddleware
•
LocaleMiddleware
•
SessionMiddleware
•
AuthenticationMiddleware
•
CsrfViewMiddleware
7
Showtime.
•
Let’s write a Middleware!
8
File Upload & Static Files
File Uploads
•
When a file uploaded through a from, the file data ends
up in request.FILES.
Basic File Uploads
from django import forms
!
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
<form method="post"
enctype="multipart/form-data">
!
...
</form>
Basic File Uploads
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from myapp.forms import UploadFileForm
!
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
!
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
Handling Uploaded File
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
Files in Models
•
models.FileField
!
•
class models.FileField(upload_to=None[, max_length=100, **options])
upload_to
•
MEDIA_ROOT & MEDIA_URL
Serving Static Files
•
Websites generally need to serve additional files such as
images, JavaScript, or CSS.
•
Django provides django.contrib.staticfiles to
help you manage them. 😊
Serving Static Files
1. Make sure that django.contrib.staticfiles is included in
your INSTALLED_APPS.
2. In your settings file, define STATIC_URL.
!
STATIC_URL = '/static/'
4. Use {% static %} in your templates.
{% load staticfiles %}
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>
Serving Static Files
•
Serving static files during development.
•
Serving static files after deployment.
•
STATIC_ROOT
•
manage.py collectstatic
Security
Common Attack Types
•
Cross Site Scripting (XSS)
•
Cross Site Request Forgery (CSRF)
•
SQL Injection
•
Clickjacking
•
User-uploaded Contents
Before We Start
•
Let’s talk about cookies!
•
Same-origin policy.
Cross Site Scripting
•
XSS attacks allow a user to inject client side scripts into
the browsers of other users.
•
Usually achieved by storing the malicious scripts in the
database.
•
Let’s see an example.
Cross Site Scripting Protection
•
Using Django templates protects you against the majority
of XSS attacks.
•
Django templates escape specific characters which are
particularly dangerous to HTML.
•
{% autoescape off %}
•
You should also be very careful when storing HTML in the
database, especially when that HTML is retrieved and
displayed.
Cross Site Request Forgery (CSRF)
•
Also known as one-click attack or session riding.
•
CSRF attacks allow a malicious user to execute actions
using the credentials of another user without that user’s
knowledge or consent.
•
Let’s see an example.
Cross Site Request Forgery
Eve: Hello Alice! Look here:
<img
src="http://bank.com/withdraw?account=Alice&amount=1000&for=Eve">
Cross Site Request Forgery
•
Involve sites that rely on a user's identity.
•
Exploit the site's trust in that identity.
•
Trick the user's browser into sending HTTP requests to a
target site.
•
Involve HTTP requests that have side effects.
Cross Site Request Forgery Protection
•
Django has built-in protection against most types of
CSRF attacks.
•
It’s enabled by default.
Cross Site Request Forgery Protection
<form method="post">
{% csrf_token %}
…
</form>
<input type='hidden' name='csrfmiddlewaretoken'
value='db6f662fc2ae5cc0e0823fb7e0331e79' />
How It Works?
1. A CSRF cookie that is set to a random value.
2. A hidden form field with the name ‘csrfmiddlewaretoken’
present in all outgoing POST forms.
3. For all incoming requests that are not using HTTP GET,
HEAD, OPTIONS or TRACE, a CSRF cookie must be
present, and the ‘csrfmiddlewaretoken’ field must be
present and correct.
Cross Site Request Forgery Protection
•
@csrf_exempt decorator.
•
Be careful.
SQL Injection
•
SQL injection is a type of attack where a malicious user is
able to execute arbitrary SQL code on a database.
•
Attacker can drop tables, delete data or access to
unauthorized resources.
•
Let’s see an example.
SQL Injection Protection
•
By using Django’s querysets, the resulting SQL will be
properly escaped by the underlying database driver.
•
However, Django also gives developers power to write
raw queries or execute custom sql.
•
Be aware when you’re using this capabilities.
Ha ha ha!
Congratulations.
Thank you, everybody.
Any Questions?
35
References
•
https://docs.djangoproject.com/en/1.6/topics/http/middleware/
•
https://docs.djangoproject.com/en/1.6/ref/middleware/
•
https://docs.djangoproject.com/en/1.6/topics/http/file-uploads/
•
https://docs.djangoproject.com/en/1.6/ref/contrib/staticfiles/
•
https://docs.djangoproject.com/en/1.6/topics/security/
•
https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/
•
http://en.wikipedia.org/wiki/Cross-site_scripting
•
http://en.wikipedia.org/wiki/CSRF