The Django Web Framework Part VI

Similar documents
django-openid Documentation

django-oauth2-provider Documentation

django-allauth-2fa Documentation

django-ratelimit-backend Documentation

silk Documentation Release 0.3 Michael Ford

Django MFA Documentation

Django: Views, Templates, and Sessions

django-facebook-graph Documentation

django-mama-cas Documentation

Tuesday, July 2, 13. intentionally left blank

neo4django Documentation

django-secure Documentation

django-oscar-paypal Documentation

django-facebook-graph Documentation

Django PAM Documentation

django-users2 Documentation

django-audit-log Documentation

Tangent MicroServices Documentation

django-mongonaut Documentation

django-cas Documentation

mozilla-django-oidc Documentation

maxecurity Product Suite

Django IPRestrict Documentation

django SHOP Release dev0

Gargoyle Documentation

SSH with Globus Auth

SJC Password Self-Service System FAQ 2018

django-password-reset Documentation

django-dajax Documentation

django-teamwork Documentation

DJOAuth2 Documentation

django-geoip Documentation

The Design of Short Message Server with Linux Machine

django-waffle Documentation

Web Development with Python and Django. Mike Crute Mike Pirnat David Stanek

alphafilter Documentation

Django starting guide

MapEntity Documentation

Django Phantom Theme Documentation

django-dajaxice Documentation

Easy-select2 Documentation

Course Outline Repository Guide

MIT AITI Python Software Development Lab DJ1:

open-helpdesk Documentation

cmsplugin-blog Release post 0 Øyvind Saltvik

GETTING STARTED WITH STUDENT LEARNING SPACE Instructions for Students

Release Joris Beckers

Django Concurrency Documentation

Django-CSP Documentation

django-audiofield Documentation

Bambu API Documentation

django-facetools Documentation

ganetimgr Documentation

django-avatar Documentation

django-avatar Documentation

Building a Django Twilio Programmable Chat Application

django-auditlog Documentation

Authentication and Authorization of End User in Microservice Architecture

7401ICT eservice Technology. (Some of) the actual examination questions will be more precise than these.

django-sticky-uploads Documentation

django-intercom Documentation

django-cron Documentation

staff Documentation Release 1.2

django-permission Documentation

Getting Started. Accessing MyTeachingStrategies Navigating MyTeachingStrategies Guided Tour Setting Language Preference to Spanish

PROFESSIONALISM RUBRIC PORTAL AND DASHBOARDS

Djam Documentation. Release Participatory Culture Foundation

10.User Password and Object Security

ska Documentation Release Artur Barseghyan

System and Software Architecture Description (SSAD)

Privileged Remote Access SIEM Tool Plugin Installation and Administration

SECTION 100 LOGIN/LOGOUT

DEPLOYMENT GUIDE Version 1.0. Deploying the BIG-IP Access Policy Manager with Oracle Access Manager

django-revproxy Documentation

django-embed-video Documentation

Django OAuth Toolkit Documentation

wagtailtrans Documentation

Django Deployment & Tips daybreaker

spaste Documentation Release 1.0 Ben Webster

ISSN: [Kumar, Sood* et al., 7(3): March, 2018] Impact Factor: 5.164

django-stored-messages Documentation

FCS Documentation. Release 1.0 AGH-GLK

flask-jwt-simple Documentation

Assessment Data Online: Admin Guide

django-debreach Documentation

tally Documentation Release Dan Watson

django-registration Documentation

Django Map Widgets Documentation

django-telegram-login Documentation

How to Configure Authentication and Access Control (AAA)

Playing tasks with Django & Celery

Configuration examples for the D-Link NetDefend Firewall series DFL-260/860

NFER Tests Analysis Tool Frequently Asked Questions

Quoting Wikipedia, software

django-slim Documentation

JAMES BENNETT DJANGOCON EUROPE 3RD JUNE 2015 THE NET IS DARK AND FULL OF TERRORS

DEPLOYMENT GUIDE Version 1.0. Deploying the BIG-IP Access Policy Manager v with Oracle Access Manager

Google Tag Manager. Google Tag Manager Custom Module for Magento

Design Use Cases. Students With A Goal (S.W.A.G.) June 5, Senior System Analyst Software Development Lead. User Interface Specialist

Type your codes into the Username and Password section and click on Login.

Transcription:

The Django Web Framework Part VI Web Programming Course Fall 2013

Outline Session Framework User Authentication & Authorization in Django 2

Session Framework Session Framework lets you store and retrieve arbitrary data on a per-site-visitor basis. Stores data on server-side and abstracts sending and receiving cookies. Cookies contain a Session ID, not the data itself (There is one exception).

Session Framework Enabled by default in projects created by djangoadmin.py We ll talk about middlewares later. settings.py!! MIDDLEWARE_CLASSES = (, 'django.contrib.sessions.middleware.sessionmiddleware', )! INSTALLED_APPS = (, 'django.contrib.sessions', )

Session Life-Cycle Is there a cookie? Is the session expired?

Session Engines Database-backed sessions Cached sessions File-based sessions Cookie-based sessions settings.py!! SESSION_ENGINE = 'django.contrib.sessions.backends.file'

But what is a cache? Students panicked and asked the teacher.

Using Sessions in Views When SessionMiddleware is activated, each HttpRequest object will have a session attribute. It s a dictionary-like object. def my_hilarious_view(request):... fav_color = request.session['fav_color']...! def my_awesome_view(request):... request.session['fav_color'] = 'blue'...

Using Sessions in Views Showtime! Let s do something with our blog example

User Authentication & Authorization Thank you, Django.

User Authentication & Authorization Authentication Verifies that a user is who they claim to be. Authorization Determines what an authenticated user is allowed to do. We used the term authentication to refer both of these tasks.

The Authentication System The authentication system consists of: Users Permissions Groups Password hashing system Forms and view tools for logging in users, etc. Pluggable backend system

Installation settings.py!! MIDDLEWARE_CLASSES = (, 'django.contrib.sessions.middleware.sessionmiddleware', 'django.contrib.sessions.middleware.authenticationmiddleware', )! INSTALLED_APPS = (, 'django.contrib.sessions', 'django.contrib.auth', ) python3 manage.py syncdb

The Authentication System There is Django s default implementation. More than sufficient for most common project needs. Django supports extensive extension and customization of authentication system.

User Objects >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') >>> from django.contrib.auth.models import User >>> u = User.objects.get(username exact='john') >>> u.set_password('new password') >>> u.save() from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # the password verified for the user if user.is_active: print("user is valid, active and authenticated") else: print("the password is valid, but the account has been disabled!") else: # the authentication system was unable to verify the username and password print("the username and password were incorrect.")

Login/Logout Showtime! Let s add a login page to our blog! from django.contrib.auth import authenticate, login! def my_login_view(request): username = request.post['username'] password = request.post['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. else: # Return a 'disabled account' error message else: # Return an 'invalid login' error message.

Limiting Access to Logged-In Users There is a simple, raw way:! def my_view(request): if not request.user.is_authenticated(): return redirect('/login/?next=%s' % request.path) There is a convenient way:!! from django.contrib.auth.decorators import login_required! @login_required def my_view(request):... What happens when user is not logged in?

Limiting Access to Logged-In Users Showtime! Let s restrict users!

Accessing User in Templates {{ user }} would do it. Showtime.

Built-in Views Django provides several views that you can use for handling login, logout, and password management.! (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}), Views for logout, password_change, etc.

Built-in Forms A bunch of default forms located in django.contrib.auth.forms. AuthenticationForm, PasswordChangeForm, PasswordResetForm, UserCreationForm, SetPasswordForm Showtime.

Users in Admin Let s see there.

Any Questions? 23

References https://docs.djangoproject.com/en/1.6/topics/http/ sessions/ https://docs.djangoproject.com/en/1.6/topics/auth/ https://docs.djangoproject.com/en/1.6/topics/auth/ default/ https://docs.djangoproject.com/en/1.6/ref/contrib/auth/ http://www.python.org 24