P
P
Pavel Chulkov2020-08-21 10:07:47
Django
Pavel Chulkov, 2020-08-21 10:07:47

Authorizing a user by IP Address in Django?

There is a modernized user model: model.py

class CustomUser(AbstractUser):
    email = models.EmailField(max_length=200, blank=True, verbose_name='Почта')
    ip_address = models.GenericIPAddressField(blank=True, null=True, verbose_name='Внутренний IP')
    members = models.ManyToManyField('CustomGroup', db_table='slug', blank=True, verbose_name='Группы', related_name='groups')
    dvr = models.BooleanField(default=False, verbose_name='Доступ к архиву')
    update_cam = models.BooleanField(default=False, verbose_name='Редактирование камер')

Added fields ip_address , dvr , update_cam ... I
check the user's ip on a specific page
def home(request):
    
    list_cameras = Cameras.objects.all()
    context = {
        'list_cameras':list_cameras
    }
    template = 'test.html'
    
    def get_client_ip(request):
        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')
        return ip
    ip = get_client_ip(request)
    print(ip)

    list_users = CustomUser.objects.values('username', 'ip_address', 'password') #<--- на это можно не смотреть 

    print(list_users)

    return render(request, template, context)


How to make it so that Python would check if one of the users received the received ip address and automatically authorize it?
Python 3, Django 2.2.14

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Melnikov, 2020-08-21
@Skandalist

Login import
J = user (in your case, we get the user by IP)
Login...

from django.contrib.auth import login
....

login(request, j)

P
Pavel Chulkov, 2020-08-21
@Skandalist

def home(request):
    
    list_cameras = Cameras.objects.all()
    context = {
        'list_cameras':list_cameras
    }
    template = 'index.html'

    def get_client_ip(request):
        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')
        return ip
    
# Забираем IP клиента
    if request.user == AnonymousUser():
        try:
            ip = get_client_ip(request)
            print(ip)
            user = CustomUser.objects.get(ip_address=ip) #<-- Проверяет входит ли ip тот что мы получили
            login(request,user)
            print(user)
            return render(request, template, context)
        except ObjectDoesNotExist:
            print('Ошибка ! Пользователя с таким IP нет ')
            return render(request, template, context)
    else:
        return render(request, template, context)

Here is a working solution! Only works on the home page

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question