两个不同Django项目实现不登录切换

两个不同Django项目实现不登录切换

没有设计单点登录 两个项目都依赖db backend Session, 所以如果浏览器直接跳转会需要登录, 而且权限控制都是独立的

临时方案: 使用中间件根据两个系统相同的用户email 验证并登录

需要設置为相同的Cookie Domain

abc.com , ac-abc.com

SESSION_COOKIE_DOMAIN = ".abc.com"

注意logout会清楚全部的session

# coding:utf-8
import json
import base64

from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.contrib.sessions.models import Session
from django.contrib.auth import login

from user.models import BvUser, SmbUser


class SsoLoginMiddleware(MiddlewareMixin):

    def _decode(self, session_data):
        # 1 django/contrib/sessions/backends/base.py session_data decode
        # 2 django/contrib/sessions/serializer.py serializers
        try:
            encoded_data = base64.b64decode(session_data)
            hash, serialized = encoded_data.split(b':', 1)
            return json.loads(serialized.decode('latin-1'))
        except Exception:
            ...

    def process_request(self, request):  # 请求之前
        session_key = request.session.session_key
        # 是否本系统的session
        try:
            # check akm_session
            Session.objects.get(pk=session_key)
        except Session.DoesNotExist:
            try:
                bv_session = Session.objects.using(settings.BV_CRM).get(pk=session_key)
            except Session.DoesNotExist:
                pass
            else:
                session_data = bv_session.session_data
                session_dict = self._decode(session_data)
                if session_dict:
                    login_user = session_dict.get("_auth_user_id")
                    bv_user = BvUser.objects.using(settings.BV_CRM).get(pk=login_user)
                    bv_email = bv_user.email
                    # akm_user
                    akm_user = SmbUser.objects.filter(email=bv_email).first()
                    if akm_user:
                        login(request, akm_user)


Buy me a 肥仔水!