You've already forked opc-backend
62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
|
|
import os
|
||
|
|
import django
|
||
|
|
|
||
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
|
||
|
|
django.setup()
|
||
|
|
|
||
|
|
from django.contrib.auth import get_user_model
|
||
|
|
from users.models import Role, UserRole
|
||
|
|
from opc_cert.models import OpcCertification, CertStatus
|
||
|
|
|
||
|
|
User = get_user_model()
|
||
|
|
|
||
|
|
def init_admin():
|
||
|
|
print("--- 正在初始化管理员账号 ---")
|
||
|
|
admin_user = User.objects.filter(username='admin').first()
|
||
|
|
if not admin_user:
|
||
|
|
admin_user = User.objects.create_superuser(
|
||
|
|
username='admin',
|
||
|
|
phone='18888888888',
|
||
|
|
email='admin@opc.local',
|
||
|
|
password='admin123',
|
||
|
|
nickname='系统管理员'
|
||
|
|
)
|
||
|
|
print("管理员账号创建成功 (admin/admin123)")
|
||
|
|
else:
|
||
|
|
admin_user.set_password('admin123')
|
||
|
|
admin_user.is_staff = True
|
||
|
|
admin_user.is_superuser = True
|
||
|
|
admin_user.save()
|
||
|
|
print("管理员账号已存在,密码重置为 admin123")
|
||
|
|
|
||
|
|
admin_role, _ = Role.objects.get_or_create(code='ADMIN', defaults={'name': '管理员', 'is_system': True})
|
||
|
|
UserRole.objects.get_or_create(user=admin_user, role=admin_role)
|
||
|
|
print("管理员角色已分配")
|
||
|
|
|
||
|
|
def clean_opc_roles():
|
||
|
|
print("--- 正在清洗错误的 OPC_USER 角色 ---")
|
||
|
|
opc_role = Role.objects.filter(code='OPC_USER').first()
|
||
|
|
if not opc_role:
|
||
|
|
print("未找到 OPC_USER 角色")
|
||
|
|
return
|
||
|
|
|
||
|
|
user_roles = UserRole.objects.filter(role=opc_role)
|
||
|
|
count = 0
|
||
|
|
for ur in user_roles:
|
||
|
|
user = ur.user
|
||
|
|
# 检查该用户是否有 APPROVED 的认证记录
|
||
|
|
has_approved_cert = OpcCertification.objects.filter(user=user, status=CertStatus.APPROVED).exists()
|
||
|
|
if not has_approved_cert:
|
||
|
|
ur.delete()
|
||
|
|
# 给用户分配普通 USER 角色
|
||
|
|
user_role, _ = Role.objects.get_or_create(code='USER', defaults={'name': '普通用户'})
|
||
|
|
UserRole.objects.get_or_create(user=user, role=user_role)
|
||
|
|
print(f"移除了用户 {user.username} 的 OPC_USER 角色,并分配了 USER 角色")
|
||
|
|
count += 1
|
||
|
|
|
||
|
|
print(f"清洗完成,共处理了 {count} 个异常用户的角色。")
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
init_admin()
|
||
|
|
clean_opc_roles()
|