Django总共只允许一个用户会话

时间:2019-05-26 10:35:47

标签: python django session django-middleware

我目前正在尝试对我的应用程序实施一项策略,一次只允许一个用户会话,如果用户尝试从另一台设备登录,则旧会话将被终止。

但是对于某些人,我得到以下错误,而我自己也找不到错误:(:

  

位于/ User处的RelatedObjectDoesNotExist不具有login_in_user。

我的项目包含两个应用程序,即实际应用程序和一个“帐户”应用程序,其中包含此处显示的所有信息。

signals.py

# Signals that fires when a user logs in and logs out

from django.contrib.auth import user_logged_in, user_logged_out
from django.dispatch import receiver
from .models import LoggedInUser

@receiver(user_logged_in)
def on_user_logged_in(sender, request, **kwargs):
    LoggedInUser.objects.get_or_create(user=kwargs.get('user'))


@receiver(user_logged_out)
def on_user_logged_out(sender, **kwargs):
    LoggedInUser.objects.filter(user=kwargs.get('user')).delete()

models.py

# Model to store the list of logged in users
class LoggedInUser(models.Model):
    user = models.OneToOneField(User, related_name='logged_in_user', on_delete=models.CASCADE)
    session_key = models.CharField(max_length=32, null=True, blank=True)

    def __str__(self):
        return self.user

我的用户模型与此代码段位于同一位置

middleware.py

#Session model stores the session data
from django.contrib.sessions.models import Session
from .models import LoggedInUser

class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            stored_session_key = request.user.logged_in_user.session_key

            # if there is a stored_session_key in the database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            if stored_session_key and stored_session_key != request.session.session_key:
                Session.objects.get(session_key=stored_session_key).delete()

            request.user.logged_in_user.session_key = request.session.session_key
            request.user.logged_in_user.save()

        response = self.get_response(request)

        # This is where you add any extra code to be executed for each request/response after
        # the view is called.

        return response

更新:

我的middleware.py文件现在看起来像:

# Session model stores the session data
from django.contrib.sessions.models import Session
from .models import LoggedInUser


class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            session_key = request.session.session_key

            # if there is a stored_session_key  in our database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            try:
                logged_in_user = request.user.logged_in_user
                stored_session_key = logged_in_user.session_key
                # stored_session_key exists so delete it if it's different
                if stored_session_key != session_key:
                    Session.objects.filter(session_key=stored_session_key).delete()
                logged_in_user.session_key = session_key
                logged_in_user.save()
            except LoggedInUser.DoesNotExist:
                LoggedInUser.objects.create(user=request.user, session_key=session_key)

        response = self.get_response(request)

        return response

这似乎工作正常,但是如果我从两个不同的浏览器中以同一用户身份登录,我仍然可以做到这一点,并且仍然可以获得两个不同的会话密钥,并且会话保持打开状态。

如果我在从两台不同的计算机登录时检查数据库以同一用户身份访问该应用程序,则LoggedInUser表上保存的会话密钥会简单更改,但该应用程序的行为至少类似于已撤销该密钥最古老的会话!?

2 个答案:

答案 0 :(得分:1)

实际上错误在这里发生,

stored_session_key = request.user.logged_in_user.session_key

即。登录用户不存在相关的logged_in_userLoggedInUser对象)。因此,您必须创建一个新的。

session_key = request.session.session_key

try:
    logged_in_user = request.user.logged_in_user
    stored_session_key = logged_in_user.session_key
    # stored_session_key exists so delete it if it's different
    if stored_session_key != session_key:
        Session.objects.filter(session_key=stored_session_key).delete()
    logged_in_user.session_key = session_key
    logged_in_user.save()
except LoggedInUser.DoesNotExist:
    LoggedInUser.objects.create(user=request.user, session_key=session_key)

答案 1 :(得分:0)

这有效并回答了您的问题。

class OneSessionPerUserMiddleware:
# Called only once when the web server starts
def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    if request.user.is_authenticated:
        session_key = request.session.session_key

        try:
            logged_in_user = request.user.logged_in_user
            stored_session_key = logged_in_user.session_key
            # stored_session_key exists so delete it if it's different
            if stored_session_key and stored_session_key != request.session.session_key:
                Session.objects.get(session_key=stored_session_key).delete()
            request.user.logged_in_user.session_key = request.session.session_key
            request.user.logged_in_user.save()
        except LoggedInUser.DoesNotExist:
            LoggedInUser.objects.create(user=request.user, session_key=session_key)
        stored_session_key = request.user.logged_in_user.session_key

        # if there is a stored_session_key  in our database and it is
        # different from the current session, delete the stored_session_key
        # session_key with from the Session table
        if stored_session_key and stored_session_key != request.session.session_key:
            Session.objects.get(session_key=stored_session_key).delete()

        request.user.logged_in_user.session_key = request.session.session_key
        request.user.logged_in_user.save()

    response = self.get_response(request)

    # This is where you add any extra code to be executed for each request/response after
    # the view is called.
    # For this tutorial, we're not adding any code so we just return the response

    return response