34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
|
|
"""
|
|||
|
|
确保默认管理员账号存在: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()
|