First follow the Installing Python Fat Cookie Library first then proceed.
Some basic example usage:
>>> import pycookie
>>> fc = pycookie.FatCookie('CUT AND PASTE FROM `FC` COOKIE')
>>> fc.eid
'Your EID'
>>> fc.uin
'Your UIN'
These are simple examples of how to ‘authenticate’ users in django with the pycookie module.
In your views.py file you can require that someone is logged in to see one paticular view. Or just use the cookie info to identify the logged in user. To lock down a single view you could write something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
import pycookie
def secure_view(request):
try:
fat_cookie = request.cookies.get('FC', None)
user = pycookie.FatCookie(fat_cookie)
except pycookie.FatCookieException:
return HttpResponseRedirect('https://utdirect.utexas.edu')
# write your view code here
# check for a paticular user like so:
admin = False
if user.eid == 'admin_eid':
admin = True
return render_to_response('template.html', RequestContext({
'user': user,
'admin': admin,
}))
|
Now you say do I have to do this in every view? No. You can write a decorator which will wrap the check code for a valid Fat Cookie around any view you choose. The decorator function would look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
import pycookie
def require_uteid(func):
def _dec(request, *args, **kwargs):
try:
fat_cookie = request.cookies.get('FC', None)
user = pycookie.FatCookie(fat_cookie)
request.ut_user = user
return func(request, *args, **kwargs)
except pycookie.FatCookieException:
return HttpResponseRedirect('https://utdirect.utexas.edu')
return _dec
|
Now to use the decorator you just do this in Python 2.4 or greater:
@require_uteid
def secure_view(request):
# check the user
if request.ut_user.eid == 'admin_eid':
admin = True
# rest of your view
In Python 2.3 it would look like this:
def secure_view(request):
# check the user
if request.ut_user == 'admin_eid':
admin = True
# rest of your view
secure_view = require_uteid(secure_view)
Sometimes you want to have an entire site protected by eid or to automatically create user when a new person logs in. First you will need to write a middleware class to handle logging users in. Middleware is run everytime Django processes a request or response, so you alter the request or response anyway you see fit. This is a perfect way to check if a person is logged in or not.
The following middleware would replace Django’s ‘AuthenticationMiddleware’ place the following in your app directory in a file named middleware.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | from django.http import HttpResponseRedirect
from django.contrib.auth.models import AnonymousUser
import pycookie
class UTUser(AnonymousUser):
"""AnonymousUser has the properties of a Django User
we use it to appear like we have a Django User object.
"""
def __init__(self, fat_cookie):
self.id = fat_cookie.uin
self.username = fat_cookie.eid
name = fat_cookie.name.split(' ')
self.first_name = name[0]
self.last_name = name[-1]
def is_anonymous(self):
return False
def is_authenticated(self):
return True
class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
try:
fat_cookie = request.cookies.get('FC', None)
user = pycookie.FatCookie(fat_cookie)
request._cached_user = UTUser(user)
except pycookie.FatCookieException:
return HttpResponseRedirect('https://utdirect.utexas.edu')
return request._cached_user
class FCAuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "Requires 'django.contrib.sessions.middleware.SessionMiddleware'."
request.__class__.user = LazyUser()
return None
|
Now you just need to ‘install’ the middleware edit your settings.py file and modify the MIDDLEWARE_CLASSES like this:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'my_app.middleware.FCAuthenticationMiddleware',
)