import datetime from django core cache import cache from django http i

 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import datetime
from django.core.cache import cache
from django.http import HttpResponse
from django.conf import settings
from django.http import HttpResponseRedirect
import flash
from common.functions import get_object_or_None
from project.models import Online
class OnlineMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
request.user.last_login = datetime.datetime.now()
request.user.ip = request.META['REMOTE_ADDR']
request.user.save()
if not get_object_or_None(Online, user=request.user):
Online.objects.create(user=request.user)
users = Online.objects.all()
online_minimum = datetime.datetime.now() - datetime.timedelta(minutes=15)
for user in users:
if user.user.last_login < online_minimum:
user.delete()
class LastLoginMiddleware(object):
def process_request(self, request):
cache.set("user_"+ str(request.user.id), True, 600)
class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
from accounts.models import Profile
user = get_user(request)
if user.is_authenticated():
profile = Profile.objects.get(user_ptr=user)
else:
profile = user
request._cached_user = profile
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
request.__class__.user = LazyUser()
return None