kboss/b/user/loginUser.dspy
2025-07-16 14:27:17 +08:00

219 lines
11 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.

async def check_wechat_login_status(code):
"""
查询微信扫码登录状态
如果用户扫码并同意授权,返回授权信息
"""
db = DBPools()
async with db.sqlorContext('kboss') as sor:
# appid = "wxf6b18088093fbea9"
# secret = "4f034d3dc767f4b101dc889028459f61"
try:
wechat_info = await sor.R('params', {'pname': 'wechat_appid_secret'})
if wechat_info:
wechat_info_dic = json.loads(wechat_info[0]) if isinstance(wechat_info[0], str) else wechat_info[0]
pvalue = json.loads(wechat_info_dic['pvalue'])
appid = pvalue['appid']
secret = pvalue['secret']
else:
return {
'status': False,
'msg': 'can not find appid'
}
url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code'
async with aiohttp_client.request(
method='GET',
url=url) as res:
data = await res.text()
data_dic = json.loads(data)
if 'access_token' in data_dic and 'openid' in data_dic:
# 获取用户信息
openid = data_dic['openid']
return {
'status': True,
'msg': 'success',
'openid': openid
}
else:
print('用户获取openid出错', data)
if 'invalid code' in data_dic.get('errmsg'):
return {
'status': False,
'msg': 'invalid code',
'data': data_dic['errmsg']
}
elif 'code been used' in data_dic.get('errmsg'):
return {
'status': False,
'msg': 'code been used',
'data': data_dic['errmsg']
}
else:
return {
'status': False,
'msg': 'get openid failed',
'data': str(data)
}
except Exception as e:
raise e
async def loginUser(ns):
"""
用户登录
"""
db = DBPools()
async with db.sqlorContext('kboss') as sor:
if ns:
# 处理微信授权后的登录
if ns.get('wechatCode'): # 微信扫码登录后的`code`
wechat_user_info = await check_wechat_login_status(ns.get('wechatCode'))
if wechat_user_info['msg'] == 'can not find appid':
return {
'status': False,
'msg': '没有找到微信后台配置信息'
}
elif wechat_user_info['msg'] == 'invalid code':
return {
'status': False,
'msg': '无效的code'
}
elif wechat_user_info['msg'] == 'code been used':
return {
'status': False,
'msg': 'code已经被使用'
}
elif wechat_user_info['msg'] == 'get openid failed':
return {
'status': False,
'msg': '获取微信基本信息错误'
}
if wechat_user_info:
openid_f = wechat_user_info['openid']
# 查询数据库查看openid是否已绑定账户
userreacs = await sor.R('users', {'wechat_openid': openid_f, 'del_flg': '0'})
if len(userreacs) >= 1:
# 如果openid绑定了用户, 查找用户名和密码 使用账号密码登录
ns['username'] = userreacs[0]['username']
ns['password'] = password_decode(userreacs[0]['password'])
else:
# 如果openid未绑定账号跳转到手机号绑定页面
return {'status': False, 'msg': '微信授权成功,请绑定手机号后登录', 'action': 'redirect', 'wechat_openid': openid_f}
else:
return {
'status': False,
'msg': '暂时不能使用微信登录, 请使用其他方式登录'
}
if ns.get('password') and (not ns.get('wechatCode')):
# 密码解密
data = """-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEApJ3ThUWT3CgvH0O8rrT6qycpqX0NTq4Q3CxBrvNxo9//qX2b
KvhomoLNd+vdti8xNOK6/3zuTJIVt0RoNKwE0HWMR8H0jgp7ING54DtT5B8bhmUp
bs/hownGzIBGOedhqeOPiv0Q5oSi9OIEE+PK2L8KdgFF2Z6Q1DQdv5Y1qvD/t2mJ
VjR+NPTwcwBIT8UJ0Cfu8lqHjjJbNF//smTjQ8v2pnqp19jItuHeD4G4u7a8fWC3
/IGEv4+uc5rq5qhwdzRxHUveNmoE+nyh0T8RC8Y8/XLkEiD0nMvZZjBn7Bof6f1s
t0aqJX8R1VGvzdTJ8eTvJuyMNsR4wLoF5PvxhQIDAQABAoIBAAkz6MMdL6kk9sI8
F2YUKHG9cvI07Obs8XTAy9Wlag34raJ8RI3Z002hnS3K5tssUKDqdMloFff744qA
ulHV6AyYKOtK2yQk6KgRPkX13lIoSj6jx/XLWb7mnGskV+JQa1pQpkUYsenHmOCX
auKKko8cpwLcpI4IJx3MSBMRqUoEFgDAZd98tpKyLHzqJN4CL9MkC3jkJcenIV6V
CDXFWaf2l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private_key)
back_text = cipher.decrypt(base64.b64decode(ns['password']), 0)
ns['password'] = back_text.decode('utf-8')
type1 = 0
if ns.get('username') != 'admin':
# 这里用户名密码登录也需要手机号,放开下面代码
# logincode = await sor.R('params',{'pname':'login_message','pvalue':'0','del_flg':'0'})
# if len(logincode) >= 1:
if ns.get('codeid'):
type1 += 1
code = await sor.R('validatecode', {'id': ns.get('codeid'), 'vcode': ns.get('vcode')})
if len(code) < 1:
return {'status': False, 'msg': '验证码不正确'}
type = 0
if type1 == 1:
# 手机号验证码登录
userreacs = await sor.R('users', {'mobile': ns.get('username')})
# 如果是微信扫码后绑定已有账号
if ns.get('wechat_openid'):
if userreacs:
# 绑定openid到已有账号
await sor.U('users', {'id': userreacs[0]['id'], 'wechat_openid': ns['wechat_openid']})
else:
return {
'status': False,
'msg': '手机号未注册'
}
else:
ns['password'] = password_encode(ns['password'])
ns['del_flg'] = '0'
userreacs = await sor.R('users', ns)
if len(userreacs) >= 1:
type += 1
await remember_user(userreacs[0]['id'], username=userreacs[0]['username'], userorgid=userreacs[0]['orgid'])
else:
ns['mobile'] = ns['username']
ns.pop('username')
userreacs = await sor.R('users', ns)
if len(userreacs) >= 1:
type += 1
await remember_user(userreacs[0]['id'], username=userreacs[0]['username'], userorgid=userreacs[0]['orgid'])
if type >= 1:
if userreacs[0]['user_status'] != '0':
return {'status': False, 'msg': '该账户已停用'}
userrolereacs = await sor.R('userrole', {'userid': userreacs[0]['id'], 'del_flg': '0'})
if len(userrolereacs) >= 1:
permissionlist = []
datalist = []
roles = []
for i in userrolereacs:
role = await sor.R('role', {'id': i['roleid'], 'del_flg': '0'})
if role[0]['role'] not in roles:
roles.append(role[0]['role'])
ns = {'roleid': i['roleid'], 'del_flg': '0'}
reacs = await sor.R('rolepermission', ns)
for j in reacs:
try:
reacs = await sor.R('permission', {'id': j['permid'], 'del_flg': '0'})
permissionlist.append(reacs[0])
except:
continue
for i in permissionlist:
if i not in datalist:
datalist.append(i)
org = await sor.R('organization', {'id': userreacs[0]['orgid']})
return {'status': True, 'msg': '登录成功', 'data': datalist, 'roles': roles,
'userId': userreacs[0]['id'], 'user': userreacs[0], 'org_type': org[0]['org_type']}
admin = 0
if userreacs[0]['orgid'] == '100':
admin += 1
else:
org = await sor.R('organization', {'id': userreacs[0]['orgid']})
return {'status': True, 'msg': '登录成功', 'userId': userreacs[0]['id'], 'user': userreacs[0], 'org_type': org[0]['org_type'], 'roles': 'None'}
# 返回admin标识
return {'status': True, 'msg': '登录成功', 'userId': userreacs[0]['id'], 'admin': admin, 'user': userreacs[0]}
else:
return {'status': False, 'msg': '用户名或密码错误'}
return {'status': False, 'msg': '登录失败'}
ret = await loginUser(params_kw)
return ret