supplychain/wwwroot/api/add_sub_distributor_admin.dspy

74 lines
2.7 KiB
Plaintext
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.

"""Create an admin user for the selected sub_distributor. Show the initial password."""
sub_distributor_id = params_kw.get('sub_distributor_id') or params_kw.get('id')
if not sub_distributor_id:
return {'widgettype': 'Error', 'options': {'title': 'Error', 'message': 'Missing sub_distributor_id', 'timeout': 3}}
userorgid = await get_userorgid()
if not userorgid:
return {'widgettype': 'Error', 'options': {'title': 'Auth Error', 'message': 'Please login', 'timeout': 3}}
dbname = get_module_dbname('supplychain')
async with DBPools().sqlorContext(dbname) as sor:
recs = await sor.sqlExe(
'SELECT id, sub_dist_name FROM sub_distributors WHERE id = ${sid}$',
{'sid': sub_distributor_id}
)
if not recs:
return {'widgettype': 'Error', 'options': {'title': 'Error', 'message': '二级分销商不存在', 'timeout': 3}}
sd = recs[0]
org_id = sd.id
admin_username = f'admin_{sub_distributor_id[:8]}'
async with DBPools().sqlorContext('sage') as sor_sage:
# Check/ensure org exists
org_recs = await sor_sage.sqlExe(
'SELECT id FROM organization WHERE id = ${oid}$', {'oid': org_id}
)
if not org_recs:
await sor_sage.C('organization', {
'id': org_id, 'orgname': sd.sub_dist_name,
})
# Check if admin already exists
user_recs = await sor_sage.sqlExe(
'SELECT id FROM users WHERE username = ${un}$', {'un': admin_username}
)
if user_recs:
return {
'widgettype': 'Message',
'options': {
'title': '管理员已存在',
'message': f'管理员 {admin_username} 已存在,请用重置密码功能',
'type': 'warning', 'timeout': 5
}
}
# Generate password from uuid
pwd = getID().replace('-','')[:12]
user_id = getID()
await sor_sage.C('users', {
'id': user_id, 'username': admin_username,
'password': password_encode(pwd),
'orgid': org_id, 'nick_name': sd.sub_dist_name + '管理员',
'user_status': '1',
})
# Assign roles: logined + reseller.admin + reseller.operator
for role_name in ['logined', 'reseller.admin', 'reseller.operator']:
role_recs = await sor_sage.R('role', {'role': role_name})
if role_recs:
await sor_sage.C('userrole', {
'id': getID(), 'userid': user_id, 'roleid': role_recs[0].id,
})
return {
'widgettype': 'Message',
'options': {
'title': '管理员创建成功',
'message': f'用户名: {admin_username}\n初始密码: {pwd}\n请妥善保管登录后建议修改',
'type': 'success', 'timeout': 0
}
}