Django’da Kullanıcıları Tek Oturuma Nasıl Zorlarız?

Kullanıcıların birden fazla yerde oturum açmalarını engellemek isterseniz aşağıdaki gibi bir yapı kullanarak engelleme yapabilirsiniz. Oturumlarda kullanılan session_id kontrol edilecek ve tekilleştirilme uygulanacak birden fazla sessin olursa bir önceki session otomatik kapatılacak.

from django.contrib.sessions.models import Session

# utils.py
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]
    elif len(request.META.get("REMOTE_ADDR")) > 6:
        ip = request.META.get("REMOTE_ADDR")
    elif len(request.META.get("CF-Connecting-IP")) > 6:
        ip = request.META.get("CF-Connecting-IP")
    return ip

# models.py
class LoggedInUser(models.Model):
    user = models.OneToOneField(
        Users, on_delete=models.CASCADE, related_name="logged_in_user"
    )
    session_key = models.CharField(max_length=32, null=True, blank=True)
    ipAddress = models.GenericIPAddressField()

    class Meta:
        app_label = "account"

    def __str__(self):
        return self.user.email

# middleware.py
class OneSessionPerUserMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_anonymous is False and customer_multiple_session:
            pass
        else:
            if request.user.is_authenticated:
                session_key = request.session.session_key
                client_ip = get_client_ip(request)
                try:
                    stored_session_key = (
                        request.user.logged_in_user.session_key
                    )

                    if stored_session_key != session_key:
                        Session.objects.filter(
                            session_key=stored_session_key
                        ).delete()

                    request.user.logged_in_user.session_key = session_key
                    request.user.logged_in_user.save()
                except LoggedInUser.DoesNotExist:
                    LoggedInUser.objects.create(
                        user=request.user,
                        session_key=session_key,
                        ipAddress=client_ip,
                    )

        response = self.get_response(request)
        return response