""" 初始化超级用户 用法: cd ~/repos/sage && ./py3/bin/python ~/repos/cms/scripts/init_superuser.py [username] [password] 默认: admin / admin123 """ import os, sys, asyncio from sqlor.dbpools import DBPools from appPublic.jsonConfig import getConfig from appPublic.uniqueID import getID # Sage环境导入password_encode sys.path.insert(0, os.path.expanduser("~/repos/sage")) from appPublic.password import password_encode async def main(): username = sys.argv[1] if len(sys.argv) > 1 else "admin" password = sys.argv[2] if len(sys.argv) > 2 else "admin123" config = getConfig('.') db = DBPools(config.databases) async with db.sqlorContext('sage') as sor: # 检查用户是否存在 existing = await sor.R('users', {'username': username}) if existing: print(f"用户 {username} 已存在 (id={existing[0]['id']})") # 更新密码 await sor.U('users', { 'id': existing[0]['id'], 'passwd': password_encode(password) }) print(f"密码已更新为: {password}") else: user_id = getID() await sor.C('users', { 'id': user_id, 'username': username, 'passwd': password_encode(password), 'orgid': '0', 'orgtypeid': 'owner', 'status': '1', }) print(f"用户已创建: {username} (id={user_id})") # 查找或创建superuser角色 roles = await sor.R('role', {'orgtypeid': 'owner', 'name': 'superuser'}) if not roles: role_id = getID() await sor.C('role', { 'id': role_id, 'orgtypeid': 'owner', 'name': 'superuser' }) print(f"角色 owner.superuser 已创建 (id={role_id})") else: role_id = roles[0]['id'] print(f"角色 owner.superuser 已存在 (id={role_id})") # 获取用户ID users = await sor.R('users', {'username': username}) uid = users[0]['id'] # 查找或创建用户-角色关联 (userrole表) # 检查userrole表是否存在 try: ur = await sor.R('userrole', {'userid': uid, 'roleid': role_id}) if not ur: await sor.C('userrole', { 'id': getID(), 'userid': uid, 'roleid': role_id, }) print(f"已分配角色 owner.superuser 给用户 {username}") else: print(f"用户 {username} 已拥有 owner.superuser 角色") except Exception as e: print(f"注意: userrole表操作异常: {e}") print("可能需要手动分配角色") print(f"\n登录信息:") print(f" 用户名: {username}") print(f" 密码: {password}") if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(main())