Files
aiagent/saars/backend/app/utils/ensure_admin.py
2026-03-07 10:29:17 +08:00

34 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
确保默认管理员账号存在username=admin, password=123456角色 admin。
"""
from app import db
from app.models.user import User, Role
from app.utils.auth import hash_password
def ensure_admin_user(admin_username="admin", admin_password="123456", admin_email=None):
"""若不存在则创建管理员角色及管理员用户。"""
if not admin_email:
admin_email = f"{admin_username}@localhost"
role = Role.query.filter_by(name="admin").first()
if not role:
role = Role(name="admin", description="Administrator")
db.session.add(role)
db.session.flush()
user = User.query.filter_by(username=admin_username).first()
if not user:
user = User(
username=admin_username,
email=admin_email,
password_hash=hash_password(admin_password),
role_id=role.id,
is_active=True,
)
db.session.add(user)
else:
if user.role_id != role.id:
user.role_id = role.id
if not user.is_active:
user.is_active = True
db.session.commit()