comparison core/middleware.py @ 581:ee87ea74d46b

For Django 1.4, rearranged project structure for new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 05 May 2012 17:10:48 -0500
parents gpp/core/middleware.py@3fe60148f75c
children
comparison
equal deleted inserted replaced
580:c525f3e0b5d0 581:ee87ea74d46b
1 """Common middleware for the entire project."""
2 import datetime
3 import logging
4
5 from django.db import IntegrityError
6 from django.contrib.auth import logout
7 from django.conf import settings
8
9 from core.functions import get_ip
10 from core.whos_online import report_user, report_visitor
11
12
13 class InactiveUserMiddleware(object):
14 """
15 This middleware ensures users with is_active set to False get their
16 session destroyed and are treated as logged out.
17 This middleware should come after the 'django.contrib.auth.middleware.
18 AuthenticationMiddleware' in settings.py.
19 Idea taken from: http://djangosnippets.org/snippets/1105/
20 """
21
22 def process_view(self, request, view_func, view_args, view_kwargs):
23 if request.user.is_authenticated() and not request.user.is_active:
24 logout(request)
25
26
27 ONLINE_COOKIE = 'sg101_online' # online cookie name
28 ONLINE_TIMEOUT = 5 * 60 # online cookie lifetime in seconds
29
30
31 class WhosOnline(object):
32 """
33 This middleware class keeps track of which registered users have
34 been seen recently, and the number of unique unregistered users.
35 This middleware should come after the authentication middleware,
36 as we count on the user attribute being attached to the request.
37 """
38
39 def process_response(self, request, response):
40 """
41 Keep track of who is online.
42 """
43 # Note that some requests may not have a user attribute
44 # as these may have been redirected in the middleware chain before
45 # the auth middleware got a chance to run. If this is the case, just
46 # bail out. We also ignore AJAX requests.
47
48 if not hasattr(request, 'user') or request.is_ajax():
49 return response
50
51 if request.user.is_authenticated():
52 if request.COOKIES.get(ONLINE_COOKIE) is None:
53 # report that we've seen the user
54 report_user(request.user.username)
55
56 # set a cookie to expire
57 response.set_cookie(ONLINE_COOKIE, '1', max_age=ONLINE_TIMEOUT)
58 else:
59 if request.COOKIES.get(settings.CSRF_COOKIE_NAME) is not None:
60 # We have a non-authenticated user that has cookies enabled. This
61 # means we can track them.
62 if request.COOKIES.get(ONLINE_COOKIE) is None:
63 # see if we can get the IP address
64 ip = get_ip(request)
65 if ip:
66 # report that we've seen this visitor
67 report_visitor(ip)
68
69 # set a cookie to expire
70 response.set_cookie(ONLINE_COOKIE, '1', max_age=ONLINE_TIMEOUT)
71
72 return response