Completed
Push — master ( cd0cbf...dcf2fd )
by Andrew
53s
created

UserCookieMiddleWare.get_client_ip()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 7
rs 9.4286
1
import random
2
3
from django.conf import settings
4
5
api_cookie_name = settings.WS_ADDRESS_COOKIE_NAME
6
api_port = settings.API_PORT
7
from chat import local
8
9
10
class UserCookieMiddleWare(object):
11
	"""
12
	Middleware to set user cookie
13
	If user is authenticated and there is no cookie, set the cookie,
14
	If the user is not authenticated and the cookie remains, delete it
15
	"""
16
17
	def process_response(self, request, response):
18
19
		if not request.COOKIES.get(api_cookie_name):
20
			domain_address = request.get_host().split(':')[0]
21
			api_address = "ws://%s:%s/" % (domain_address, api_port)
22
			response.set_cookie(api_cookie_name, api_address)
23
		# force create Session for annon
24
		if hasattr(request, 'session') and not request.session.session_key:
25
			request.session.save()
26
			request.session.modified = True
27
		return response
28
29
	def process_request(self, request):
30
		try:
31
			local.random
32
		except AttributeError:
33
			local.random = str(random.randint(0, 10000)).rjust(4, '0')
34
			local.user = str(getattr(request.user, 'username', '')).rjust(8, ' ')
35
			local.client_ip = self.get_client_ip(request)
36
37
	def get_client_ip(self, request):
38
		x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
39
		if x_forwarded_for:
40
			ip = x_forwarded_for.split(',')[-1].strip()
41
		else:
42
			ip = request.META.get('REMOTE_ADDR')
43
		return ip