sessions.txt +-- Sessions and Authorization in Web Applications HTTP has no memory! Each request/response stands alone each request/response may interleave with many others (from other clients) so how can we have persistent sessions for ongoing work? Server sends unique session ID ("cookie") back with first response in HTTP response header Client includes that session ID with subsequent requests in HTTP request header Server maintains dictionary of session ID : session data looks up each client's session data each time request appears +-- Authorization in Django: users and logins The machinery is provided in django.contrib.auth, but is unobvious https://docs.djangoproject.com/en/1.3/topics/auth/ http://www.djangobook.com/en/2.0/chapter14/ Starting from a simple app without users or authorization (for example, starting from booksite.py, how to make bookshop.py): 1. In settings.py INSTALLED_APPS uncomment auth, sessions, contenttypes, then: python manage.py syncdb 2. Authorize users in the database auth_user table, for example: user = User.objects.create_user('jon', 'jon@uw.edu', 'mypasswd') 3. In your top-level urls.py add these three lines at the appropriate locations: from django.contrib.auth.views import login, logout ... url(r'^accounts/login/$', login), url(r'^accounts/logout/$', logout), ... 4. In views.py, decorate pertinent views with @login_required. This will redirect to the login page when needed. You do NOT have to add any other code in views.py to support login/logout, that is already provided by django.contrib.auth.views.login,logout referenced in urls.py 5. In your templates directory, add a registration/ directory containing the forms login.html and logged_out.html. You can copy a sample login.html from the references linked above. Your login.html must include {% csrf_token %} for security. 6. In your templates, add Logout links where appropriate: Logout 7. Add a Login link to /accounts/login where appropriate. It is not needed on pages whose views are decorated with @login_required, but it is often helpful to put a Login link on the logged_out.html page. The Login link should include a next?... query string to indicate the page to show after a successful login. The bookshop sample uses this Login link: Login +-- Sessions in Django Persistent data across multiple HTTP request/reponse Each client (identified by cookie) has different data Example: shopping cart Django sessions use cookies but hides them from application programmer Enable session middleware in settings.py (this is the default) Every request object (first arg to every view function) contains request.session, a dictionary-like object you can read, write to store data about the session. request.session persists through multiple views, "remembers" Can set request.session to persist after user exits browser writes cookie in a file on the user's computer