550 likes | 2.68k Views
Cookies, Sessions, Users, and Registration CMPT 170 Spring 2009, SFU Surrey (based on Chapter 14 of The Django Book) Django Authentication The Problem with HTTP HTTP is a stateless protocol From the server's point of view, no connection whatsoever between different HTTP requests
E N D
Cookies, Sessions, Users, and RegistrationCMPT 170 Spring 2009, SFU Surrey(based on Chapter 14 of The Django Book) Django Authentication
The Problem with HTTP • HTTP is a stateless protocol • From the server's point of view, no connection whatsoever between different HTTP requests • This is a big problem when it comes handling user accounts • We want a user to be able to login to a website and do things to their account that only they can do
Response HTTP/1.1 200 OK Content-Type: text/html Set-Cookie: PREF=ID=5b14f22bdaf1e81c:TM=1167000671:LM=1167000671; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com Server: GWS/2.1 ... The Solution: Cookies Request GET / HTTP/1.1 Host: google.com ...
Cookies • Websites often send your browsers unique cookies • A cookie is just a small amount of data, usually a string • Cookies can be used to identify who you are to the server in later requests GET / HTTP/1.1 Host: google.com Cookie: PREF=ID=5b14f22bdaf1e81c:TM=1167000671:LM=1167000671 ...
Getting and Setting Cookies • Django makes it easy to get/set cookies directly • However, dealing directly with cookies is very low-level • It's usually preferable to instead use high-level applications that set cookies behind the scenes • This is what we will be doing with authentication
Getting Cookies in Django def show_color(request): if "favorite_color" in request.COOKIES: return HttpResponse("Your favorite color is %s" % \ request.COOKIES["favorite_color"]) else: return HttpResponse("No favorite color.") A view's request object stores cookies in a dictionary called COOKIES.
Setting Cookies in Django def set_color(request): if "favorite_color" in request.GET: response = HttpResponse("favorite color = %s" % \ request.GET["favorite_color"]) response.set_cookie("favorite_color", request.GET["favorite_color"]) return response else: return HttpResponse("No color given!")
A Few Cookie Options • max_age: Age (in seconds) that the cookie should last. If this parameter is None, the cookie will last only until the browser is closed. • expires: The actual date/time when the cookie should expire. If given, this parameter overrides the max_age parameter. • secure: If set to True, this parameter instructs the browser to only return this cookie to pages accessed over HTTPS.
Pros and Cons of Cookies • They work! Everyone uses them! • They are not programs; they store data only • However • Cookies are not secure unless sent via HTTPS • Browsers let users manage cookies, so there is no guarantee a browser will accept your site's cookies • Browsers/user could modify cookies in any way they want at any time --- so don't store important information in them! • Cookie poisoning
Some Cookie Limit • Browsers limit how many cookies from any one domain they will store • Firefox 2/IE 6/IE 7: 50 cookies per domain • Opera 9: 30 cookies per domain • Cookies must be less than 4KB each • IE limits the sum of the sizes of all cookies from a single domain to be 4KB
Third-party Cookies • Web advertisers often set cookies (via image downloadss) that can track you across multiple websites • Thus they can build a profile of your browsing habits to send you targetted ads • These raise serious privacy issues • Many web browsers let you deny 3rd party cookies --- often with no ill-effects • Of course, advertisers and tracking companies might not be happy about this!
Alternatives to Cookies • IP addresses • Not so good • Different users/computers may share same IP address • IP address may change during a session (e.g. in dial-up access) • URL query strings can contain information • Server appends state info to URL links • Similar to cookies, but with more consistency/security issues • PHP and Java Servlets can use this approach
Alternatives to Cookies • Hidden fields in forms • ASP.NET can track users by storing information in hidden form fields • window.name • 2-32MB of data can be stored in a page's window.name attribute • Each page/tab has its own window.name • Flash plug-in locally stored objects • Similar to cookies • Only works if you have Flash installed • Different set of privacy/security controls
Django's Session Framework • A high-level way to handle store and retrieve user-specific data • Uses cookies, but you don't usually need to worry about them • Implements many best practices, so the default are generally efficient and safe • Sessions are installed by default in new Django projects • Search settings.py for 'session' to see where
Using Sessions # Set a session value: request.session["fav_color"] = "blue" # Get a session value -- this could be called in a # different view, or many requests later (or both): fav_color = request.session["fav_color"] # Clear an item from the session: del request.session["fav_color"] # Check if the session has a given key: if "fav_color" in request.session: ...
Using Sessions • Use sessions instead of cookies! • Use strings as the keys • But don't use strings like '_color' that start with an underscore: the underscore indicates a special variable • Don't replace request.session, i.e. this is bad:request.session = s2 # bad!!
Sample Usage def post_comment(request, new_comment): if request.method != 'POST': raise Http404('Only POSTs are allowed') if request.session.get('has_commented', False): return HttpResponse("You've already commented.") c = comments.Comment(comment=new_comment) c.save() request.session['has_commented'] = True return HttpResponse('Thanks for your comment!')
Simple Login This is not a very good way to login to a Django site. It's a simple example of how to use a session. Later we will see a better way of logging in using the authentication application. def login(request): if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = Member.objects.get(username=request.POST['username']) if m.password == request.POST['password']: request.session['member_id'] = m.id return HttpResponseRedirect('/you-are-logged-in/') except Member.DoesNotExist: return HttpResponse("Username/password didn't match.")
Simple Logout Again, later we will see a better way of logging out using the authentication application. def logout(request): try: del request.session['member_id'] except KeyError: pass return HttpResponse("You're logged out.")
Some Session Details • Sessions are based entirely on cookies • They have various options you can set, such as when they expire • Session information is stored in the database table django_session • Session data is only fetched on demand: so if you don't use it, it won't access the database for it
Users and Authentication • Sessions let us store data • Django's user and authentication application is built on top of sessions • Django's authentication system handles • user accounts • groups • permissions • cookie-based user sessions
Authentication • Authentication has two main tasks • Verifying that a user is who they say they are • e.g. by comparing a username and password to ones stored in the database • Verifying that a user is allowed to perform some action • By checking against a (database) table of permissions
Basic Components • Users: people registered with your site • Permissions: yes/no flags indication what actions a user may perform • Groups: a way to give multiple user the same permissions/labels • Messages: a way to send system messages to users
Enabling Authentication • Django's authentication app is enabled by default • Search settings.py for 'auth' to see how • Also requires the sessions app to be installed • Also enabled by default
Authenticated Users • The request.user object lets us test if a user is authenticated if request.user.is_authenticated(): # Do something for authenticated users. else: # Do something for anonymous users.
Some User Object Fields • user objects have many pre-defined fields and methods, e.g. • username: required; 30 or fewer alphanumeric characters • first_name, last_name: optional • password: required; hash of user's password • is_staff: True iff user can use admin site • is_active: False means user can't use account (set this instead of deleting an account) • is_superuser: True iff user has all permissions • last_login, date_joined
Some User Object Methods • is_authenticated(): True iff user is authenticated • is_anonymous(): True iff user is not authenticated • set_password(passwd): change the user's password • check_password(passwd): compare to user's password • get_all_permissions(): return a list of all user's permission strings
Loggin in and out • Logging in and logging out is so common that Django provide's pre-written views for both • However, it is first useful to see how to do logging in/out manually ...
Manual Login from django.contrib import auth def login_view(request): uname = request.POST.get('username', '') passwd = request.POST.get('password', '') user = auth.authenticate(username=uname, password=passwd) if user is not None and user.is_active: # Correct password, and the user is marked "active" auth.login(request, user) # Redirect to a success page. return HttpResponseRedirect("/account/loggedin/") else: # Show an error page return HttpResponseRedirect("/account/invalid/")
Manual Logout from django.contrib import auth def logout_view(request): auth.logout(request) # Redirect to a success page. return HttpResponseRedirect("/account/loggedout/")
Generic Login • Most Django sites use the generic login/logout views # urls.py from django.contrib.auth.views import login, logout urlpatterns = patterns('', # ... (r'^accounts/login/$', login), (r'^accounts/logout/$', logout), )
Login and Logout Templates • The default login expects a login template at registration/login.html • The default login expects a login template at registration/logged_out.html • See chapter 14 of the Django book for more information on these methods (http://www.djangobook.com/en/2.0/chapter14/) • Here's a sample of what the login template might look like ...
Sample Login Template {% if form.errors %} <p class="error">Invalid username or password</p> {% endif %} <form action='.' method='post'> <label for="username">User name:</label> <input type="text" name="username" value="" id="username"> <label for="password">Password:</label> <input type="password" name="password" value="" id="password"> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next|escape }}" /> <form action='.' method='post'>
Limiting Access • We have two main ways to limit access of anonymous (non-authenticated users) • One way is to check with an if-statement: from django.http import HttpResponseRedirect def my_view(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login/?next=%s' % request.path) # ...
Limiting Access • The other way is to use a decorator: from django.contrib.auth.decorators import login_required @login_required def my_view(request): # ... If the user is not logged in, this re-directs to /accounts/login
Creating Users • Can create users via the admin interface • Or programmatically: >>> from django.contrib.auth.models import User >>> user = User.objects.create_user(username='john',email='jlennon@beatles.com', password='glass onion')
Changing Passwords >>> user = User.objects.get(username='john') >>> user.set_password('goo goo goo joob') >>> user.save() Passwords are stored as salted hashes, so you shouldn't set them directly unless you understand what this means in detail!
Conclusion • You will almost always want to use the standard Django ways of handling users • Security is harder than you might think, and so you not do it yourself unless you know what you are doing • For more details, see chapter 14 of the Django book: http://www.djangobook.com/en/2.0/chapter14/