HI Friends ,
Today i will tell you how can we filter login of Admin user in respect of IP addresses stored in backend.
Work Motivation : Allow any admin user login only with any number of ip address selected in backend .
Coding
we will create two models in models.py Profile , Failed
Profile :
class Profile(models.Model):
user = models.ForeignKey(User)
ip=models.IPAddressField(null=True)
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Failed(models.Model):
user=models.ForeignKey(User)
timestamp=models.DateTimeField(auto_now_add=True)
ip=models.IPAddressField()
Now Create a decorator
from django.http import HttpResponse
from django.contrib.auth.views import logout
from django.contrib.admin.models import User
from userapp.models import UserProfile , Failedlogintry
def check_ip_required(f):
def wrap(request, *args, **kwargs):
#it will check session of admin user , if session key exist then it will allow further else will redirect to login page
try:
#check admin user exists or not
user=User.objects.get(username=request.user)
#fetch user profile obj
userprofileobj = Profile.objects.filter(user=user)
iplist =[]
for i in userprofileobj:
iplist.append(str(i.ip))
#ip list is having all ip address of that admin stored in backend
loginip=str(request.META['REMOTE_ADDR'])
if len(iplist) is 0: # if admin is not having any ip stored in backend
logout(request) # logout session of admin user
Failed.objects.create(user=user,\ ip=request.META['REMOTE_ADDR']) # make a entry in failedlogintry table
return HttpResponse("You are not authorized to Logins.")
if loginip not in iplist:
logout(request) #if ip address from which admin is trying to login is not in db then logout
Failed.objects.create(user=user,\ ip=request.META['REMOTE_ADDR'])
return HttpResponse("You are not authorized to Login.")
except:
pass
return f(request, *args, **kwargs)
wrap.__doc__=f.__doc__
wrap.__name__=f.__name__
return wrap
admin.py
we can restrict any admin having only 10 ip in admin.py file
from django.contrib import admin
from userapp.models import UserProfile
class ProfileAdmin(admin.ModelAdmin):
list_display=['user','ip']
def save_model(self, request, obj, form, change):
adminname = obj.user
count = Profile.objects.filter(user=adminname).count()
if count <= 9:
obj.save()
else:
pass
admin.site.register(Profile, ProfileAdmin)
urls.py from userapp.decorators import decorated_includes, check_ip_required
url(r'^admin/',decorated_includes(check_ip_required , include(admin.site.urls)) ),
Please ignore indentation errors .if any issue please leave comment or mail me . Thanks & Regards:
Prashant Gaur
+91 9030015491
91prashantgaur@gmail.com
Today i will tell you how can we filter login of Admin user in respect of IP addresses stored in backend.
Work Motivation : Allow any admin user login only with any number of ip address selected in backend .
Coding
we will create two models in models.py Profile , Failed
Profile :
class Profile(models.Model):
user = models.ForeignKey(User)
ip=models.IPAddressField(null=True)
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Failed(models.Model):
user=models.ForeignKey(User)
timestamp=models.DateTimeField(auto_now_add=True)
ip=models.IPAddressField()
Now Create a decorator
from django.http import HttpResponse
from django.contrib.auth.views import logout
from django.contrib.admin.models import User
from userapp.models import UserProfile , Failedlogintry
def check_ip_required(f):
def wrap(request, *args, **kwargs):
#it will check session of admin user , if session key exist then it will allow further else will redirect to login page
try:
#check admin user exists or not
user=User.objects.get(username=request.user)
#fetch user profile obj
userprofileobj = Profile.objects.filter(user=user)
iplist =[]
for i in userprofileobj:
iplist.append(str(i.ip))
#ip list is having all ip address of that admin stored in backend
loginip=str(request.META['REMOTE_ADDR'])
if len(iplist) is 0: # if admin is not having any ip stored in backend
logout(request) # logout session of admin user
Failed.objects.create(user=user,\ ip=request.META['REMOTE_ADDR']) # make a entry in failedlogintry table
return HttpResponse("You are not authorized to Logins.")
if loginip not in iplist:
logout(request) #if ip address from which admin is trying to login is not in db then logout
Failed.objects.create(user=user,\ ip=request.META['REMOTE_ADDR'])
return HttpResponse("You are not authorized to Login.")
except:
pass
return f(request, *args, **kwargs)
wrap.__doc__=f.__doc__
wrap.__name__=f.__name__
return wrap
admin.py
we can restrict any admin having only 10 ip in admin.py file
from django.contrib import admin
from userapp.models import UserProfile
class ProfileAdmin(admin.ModelAdmin):
list_display=['user','ip']
def save_model(self, request, obj, form, change):
adminname = obj.user
count = Profile.objects.filter(user=adminname).count()
if count <= 9:
obj.save()
else:
pass
admin.site.register(Profile, ProfileAdmin)
urls.py from userapp.decorators import decorated_includes, check_ip_required
url(r'^admin/',decorated_includes(check_ip_required , include(admin.site.urls)) ),
Please ignore indentation errors .if any issue please leave comment or mail me . Thanks & Regards:
Prashant Gaur
+91 9030015491
91prashantgaur@gmail.com