Save user data in UserProfile with Middleware and GeoIP
I have a small question to ask you. I use GEO IP to locate my users and I would like to record this information every time user log in to improve the user experience of the app. The problem is that it doesn't save absolutely nothing at each connection. UserProfile models is empty...
Anyone has an idea about this?
user/middleware.py
from .models import UserProfile
from django.contrib.gis.geoip2 import GeoIP2
from django.utils.deprecation import MiddlewareMixin
class LastLoginInfo(MiddlewareMixin):
def geolocalisation(request):
if request.user.is_authenticated():
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
device_type = ""
browser_type = ""
browser_version = ""
os_type = ""
os_version = ""
if request.user_agent.is_mobile:
device_type = "Mobile"
if request.user_agent.is_tablet:
device_type = "Tablet"
if request.user_agent.is_pc:
device_type = "PC"
browser_type = request.user_agent.browser.family
browser_version = request.user_agent.browser.version_string
os_type = request.user_agent.os.family
os_version = request.user_agent.os.version_string
g = GeoIP2()
location = g.city(ip)
location_country = location["country_name"]
location_city = location["city"]
#UserProfile.objects.update_or_create(user=request.user, defaults={'ip_address_ua': request.data['ip']})
UserProfile.objects.filter(user=request.user.pk).update(ip_address_ua=ip, device_ua=device_type, browser_ua=browser_type, os_device_ua=os_version, city_ua=location_city, country_ua=location_country)
main/settings.py
MIDDLEWARE = [
...
'user.middleware.LastLoginInfo',
...
]
Just make some changes :)
class LastLoginInfo(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated:
First, your method is missing the self
parameter.
def process_request(self, request):
If this does not resolve the issue, then I believe the issue here is the ordering of your middleware:
You should ensure that your middleware is listed AFTER any authentication middleware.
Otherwise, this statement will never catch
if request.user.is_authenticated():
For example, if you use django.contrib.auth.middleware.AuthenticationMiddleware
, you need the following:
MIDDLEWARE = [
...
'django.contrib.auth.middleware.AuthenticationMiddleware'
'user.middleware.LastLoginInfo', # this must come AFTER auth middleware
...
]