在Django中,要改造Auth user
表并增加对OAuth2认证的支持,你需要定制UserAdmin
并添加自定义字段,同时创建相应的模型来处理OAuth2认证信息。以下是一个简化的例子:
首先,定义一个新的模型来存储OAuth2认证信息:
from django.db import models
from django.contrib.auth.models import User
class OAuth2Info(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
access_token = models.CharField(max_length=255)
refresh_token = models.CharField(max_length=255)
# 其他OAuth2相关字段
然后,定制UserAdmin
来管理额外的字段:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import OAuth2Info
class CustomUserAdmin(UserAdmin):
list_display = ('username', 'email', 'is_staff', 'is_active', 'oauth2_info')
list_select_related = ('oauth2info',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name', 'email')}),
('OAuth2 Info', {'fields': ('oauth2info',)}), # 添加OAuth2信息的字段
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'email', 'is_staff', 'is_active'),
}),
)
# 注册模型关联
inlines = (OAuth2InfoInline,)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
最后,创建一个StackedInline
来编辑用户的OAuth2信息:
from django.contrib import admin
from django.contrib.auth.models import User
from .models import OAuth2Info
class OAuth2InfoInline(admin.StackedInline):
model = OAuth2Info
can_delete = False
verbose_name_plural = 'OAuth2 info'
class CustomUserAdmin(UserAdmin):
inlines = (OAuth2InfoInline,)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
这样,在Django Admin后台,你就可以管理用户的OAuth2认证信息了。记得在settings.py
中添加你的应用,以确保上述代码能够被正确加载。