回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我必须用PHP应用程序实现一个向后兼容的Django服务器。遗留应用程序正在使用<code>LegacyUser</code>模型进行授权,该模型或多或少类似于:</p>
<pre><code>class LegacyUser(models.Model):
id = models.BigAutoField(primary_key=True)
email = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=120, blank=True, null=True)
...
other_data_fields
...
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
EMAIL_FIELD = 'email'
</code></pre>
<p>在新系统中,我不必添加<code>LegacyUser</code>的新记录(但我可以)。你知道吗</p>
<p>目前,遗留系统不允许每个组创建多个用户。实际上<code>LegacyUser</code>应该被视为一个组,但我是作为一个用户实现的。你知道吗</p>
<p>现在我必须为每个<code>LegacyUser</code>实现多个<code>Users</code>,因此我添加了适当的Django用户进行授权,如:</p>
<pre><code>class User(AbstractUser):
username = None
email = models.EmailField(unique=True)
legacy_user = models.ForeignKey(LegacyUser, on_delete=models.DO_NOTHING)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['publisher']
class Meta:
managed = True
db_table = 'user'
</code></pre>
<p>在<code>base.py</code>设置中:</p>
<pre><code>...
AUTH_USER_MODEL = 'api.LegacyUser'
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'id',
}
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend', #Supports User
'common.auth.backends.LegacyBackend' #Supports LegacyUser
]
...
</code></pre>
<p>新的应用程序应该能够同时登录<code>LegacyUser</code>和<code>User</code>。授权后LegacyUser.id应该用作用户标识声明。你知道吗</p>
<p>这意味着如果我有一个像:</p>
<pre><code>{
"id": 1,
"email": admin@domain.com,
"password": "hashed_password",
...
}
</code></pre>
<p>和两个用户,例如</p>
<pre><code>{
"id": 1,
"email": user1@domain.com,
"password": "hashed_password",
"legacy_user_id": 1,
...
}
</code></pre>
<pre><code>{
"id": 2,
"email": user2@domain.com,
"password": "hashed_password",
"legacy_user_id": 1,
...
}
</code></pre>
<p><code>LegacyUser.id</code>或<code>User.legacy_user.id</code>的值应该在请求中可见。你知道吗</p>
<p>除此之外,<code>email</code>字段在<code>LegacyUser</code>和<code>User</code>中必须是唯一的</p>
<p>这是否可能有两种用户授权模型?<code>AUTH_USER_MODEL</code>只能让我有一个这样的模型</p>
<pre><code>AUTH_USER_MODEL = 'api.LegacyUser'
</code></pre>
<p>我想到的解决方案(归档向后兼容的应用程序)是将当前密码和电子邮件从<code>LegacyUser</code>复制到新的<code>User</code>模型,并将它们标记为最高权限。你知道吗</p>
<p>同步新系统和旧系统的密码也是必须的,这样我就可以使用一些存储过程,在数据库的更新中更改两处的密码?对我来说,它闻起来很难闻,也许有其他方法可以做到这一点,而不同步这些密码或只是使用两个表进行授权?你知道吗</p>
<blockquote>
<p>Edit: To solve this issue I have created MySQL view with unified user data needed only for authorization like: </p>
<pre><code>CREATE OR REPLACE VIEW unified_user AS
SELECT email as email, password as password, is_active as is_active, last_login as last_login
FROM user
UNION ALL
SELECT email as email, password as password, 1 as is_active, null as last_login
FROM legacy_user;
</code></pre>
<p>So synchronization of passwords will be done automatically as view will be updated </p>
</blockquote>