<p>您需要一个标志来区分旧用户和新用户的身份验证。
让我集中讨论基于会话的身份验证。你知道吗</p>
<pre><code>AUTHENTICATION_BACKENDS = [
'common.auth.backends.CustomUserBackend'
</code></pre>
<p>]</p>
<p>从中间件中删除它<code>django.contrib.auth.middleware.AuthenticationMiddleware</code>,并放置CustomAuthenticationMiddleware。你知道吗</p>
<pre><code>MIDDLEWARE = [
...
'Your CustomAuthenticationMiddleware',
....
]
</code></pre>
<p>在<code>CustomAuthenticationMiddleware</code>,根据session变量附加用户。你知道吗</p>
<p>为类<code>CustomUserBackend</code>实现这些方法。请阅读<a href="https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#module-django.contrib.auth.backends" rel="nofollow noreferrer">Auth</a></p>
<pre><code>def get_user(self, user_id):
# read is_legacy_user from session
# Try to get user based on session is_legacy_user
# Note that this method is called in CustomAuthenticationMiddleware middleware.
# and you have to read from 2 separate table. Session is your friend to differentiate which table we need to fetch.
def authenticate(self, request, email, password, is_legacy_user):
if is_legacy_user:
#write the logic for legacy user.
else:
#write the logic for new user.
</code></pre>
<p>从视图调用<code>authenticate</code>函数(<code>from django.contrib.auth import authenticate</code>)。你知道吗</p>
<p>对于旧用户</p>
<pre><code>user = authenticate(email, password, is_legacy_user=True)
# Store the user ID in session as well as is_legacy_user value
</code></pre>
<p>对于新用户</p>
<pre><code>authenticate(email, password, is_legacy_user=False)
# Store the user ID in session as well as is_legacy_user value
</code></pre>
<p>我希望这就是你将如何解决基于会话的身份验证问题。如果这起作用;将转向基于令牌的。你知道吗</p>