auth.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. # -*- coding: utf-8 -*-
  2. from fastapi import APIRouter, Depends, Request, Header, Form, Body
  3. from fastapi.responses import FileResponse, StreamingResponse
  4. from sqlalchemy.orm import Session
  5. from fastapi.responses import JSONResponse
  6. from database import get_db
  7. from utils import *
  8. from utils.vcode import *
  9. from utils.redis_util import *
  10. import base64
  11. from common.const import *
  12. from io import BytesIO
  13. from utils.StripTagsHTMLParser import *
  14. from common import security
  15. from datetime import timedelta
  16. from common.security import verify_password
  17. from utils import ase_utils
  18. from common.auth_user import *
  19. from common import YzyApi, TassApi
  20. from models import *
  21. from urllib.parse import quote
  22. from exceptions import *
  23. import traceback
  24. from common.db import db_czrz
  25. from common.enc import mpfun, sys_user_data
  26. router = APIRouter()
  27. @router.get('/tenant/list')
  28. async def tenant_list(
  29. request: Request,
  30. db: Session = Depends(get_db)
  31. ):
  32. return {
  33. "code": 200,
  34. "msg": "操作成功",
  35. "data": {
  36. "tenantEnabled": False,
  37. "voList": []
  38. }
  39. }
  40. def buildVerificationCodeRedisKey(uuid: str) -> str:
  41. return VERIFICATION_CODE_REDIS_PREFIX.format(uuid)
  42. @router.get('/code')
  43. async def code(
  44. request: Request,
  45. db: Session = Depends(get_db)
  46. ):
  47. uuid_str = md5(new_guid())
  48. image, code = getVerifyCode()
  49. buf = BytesIO()
  50. image.save(buf, 'png')
  51. img_data = buf.getvalue()
  52. image_bytes_io = BytesIO(img_data)
  53. image_bytes_io.seek(0)
  54. image_bytes = image_bytes_io.read()
  55. base64_str = base64.b64encode(image_bytes).decode('utf-8')
  56. redis_key = "kaptcha_" + buildVerificationCodeRedisKey(uuid_str)
  57. redis_set(redis_key, code)
  58. return {
  59. "code": 200,
  60. "msg": "操作成功",
  61. "data": {
  62. "captchaEnabled": True,
  63. "uuid": uuid_str,
  64. "img": base64_str
  65. }
  66. }
  67. @router.post('/login')
  68. async def login(
  69. request: Request,
  70. db: Session = Depends(get_db),
  71. data: dict = Depends(remove_xss_json)
  72. ):
  73. try:
  74. # tenantId = data['tenantId']
  75. username = data['username']
  76. password = data['password']
  77. # rememberMe = data['rememberMe']
  78. uuid_str = data['uuid']
  79. code = data['code']
  80. # clientId = data['clientId']
  81. # grantType = data['grantType']
  82. # 仅为了可能的兼容
  83. clientId = "e5cd7e4891bf95d1d19206ce24a7b32e"
  84. grantType = "password"
  85. uuid = buildVerificationCodeRedisKey(uuid_str)
  86. redis_key = "kaptcha_" + uuid
  87. redis_code = redis_get(redis_key)
  88. if code is None or code != redis_code:
  89. raise AppException(500, "图片验证码不正确")
  90. redis_login_key = "login_user_" + username
  91. login_error_times = redis_get(redis_login_key)
  92. if login_error_times is None:
  93. login_error_times = 0
  94. else:
  95. login_error_times = int(login_error_times)
  96. if login_error_times >= 5:
  97. raise AppException(500, "登录错误多,请5分钟后再尝试!")
  98. # 对用户账号进行密码机接口加密处理
  99. username = mpfun.enc_data(username)
  100. password = ase_utils.aesDecrypt(uuid_str, password)
  101. logger.info('userpass: {}', password)
  102. row = db.query(SysUser).filter(SysUser.user_name == username).first()
  103. if sys_user_data.sign_valid_row(row) == False:
  104. raise AppException(500, "系统用户表验证异常,已被非法篡改")
  105. if row is None:
  106. login_error_times = login_error_times + 1
  107. redis_set_with_time(redis_login_key, str(login_error_times), 300)
  108. raise AppException(500, "帐号或者密码错误")
  109. logger.info('row.password: {}', row.password)
  110. # bcrypt 加密校验
  111. # if verify_password(password, row.password) == False:
  112. # 密码机加密校验
  113. if mpfun.enc_data(password) != row.password:
  114. login_error_times = login_error_times + 1
  115. redis_set_with_time(redis_login_key, str(login_error_times), 300)
  116. raise AppException(500, "帐号或者密码错误")
  117. # 校验长期(超过1个月)未使用的账号和及开通后未及时(如72小时)修改初始密码的账号做清除
  118. login_date = row.login_date
  119. if row.login == 0:
  120. # 计算初始化的时间和当前时间相差的小时数
  121. diff_hour = (datetime.now() - login_date).seconds/3600
  122. if diff_hour > 72:
  123. raise AppException(500, "你的账号在开通后(72小时)内未登录及修改初始密码,账号已被锁定,请联系管理员处理,否则将被清除。")
  124. else:
  125. # 计算上次登录到当前时间的相差天数
  126. diff_day = (datetime.now() - login_date).days
  127. if diff_day > 30:
  128. raise AppException(500, "你的账号在超过30天未登录使用,账号已被锁定,请联系管理员处理,否则将被清除。")
  129. redis_set_with_time(redis_login_key, str(0), 1)
  130. user_id = str(row.user_id)
  131. auth = {
  132. "user_id": user_id,
  133. "user_name": mpfun.dec_data(row.user_name),
  134. "nick_name": row.nick_name,
  135. "is_yzy_user": "0"
  136. }
  137. request.session.update({
  138. 'user_auth': auth,
  139. 'user_auth_sign': data_auth_sign(auth),
  140. 'user_name': username
  141. })
  142. db_czrz.log_username(db, row.user_id, auth['user_name'], row.nick_name, "登录", "后台管理登录成功", request.client.host)
  143. row.login_date = datetime.now()
  144. row.login_ip = request.client.host
  145. row.login = row.login + 1
  146. db.commit()
  147. access_token_expires = timedelta(days = 5)
  148. access_token = security.create_access_token(
  149. data={"sub": user_id}, expires_delta = access_token_expires
  150. )
  151. refresh_token_expires = timedelta(days = 10)
  152. refresh_token = security.create_access_token(
  153. data={"sub": user_id}, expires_delta = refresh_token_expires
  154. )
  155. return {
  156. "code": 200,
  157. "msg": "操作成功",
  158. "data": {
  159. "access_token": access_token,
  160. "refresh_token": refresh_token,
  161. "expire_in": 7200,
  162. "refresh_expire_in": 7200,
  163. "client_id": clientId,
  164. "scope": "",
  165. "openid": ""
  166. }
  167. }
  168. except AppException as e:
  169. return {
  170. "code": e.code,
  171. "msg": e.msg
  172. }
  173. except Exception as e:
  174. traceback.print_exc()
  175. return {
  176. "code": 500,
  177. "msg": "帐号或者密码错误"
  178. }
  179. @router.post('/logout')
  180. async def logout(
  181. request: Request,
  182. user: AuthUser = Depends(get_auth_user),
  183. db: Session = Depends(get_db)
  184. ):
  185. logger.info("logout ok")
  186. request.session.clear()
  187. try:
  188. # db_czrz.log(db, user, "退出", "后台管理退出成功", request.client.host)
  189. if user.is_yzy_user == 1:
  190. logout_url = settings.TYRZ_LOGOUT.format(settings.TYRZ_CLIENT_ID) + quote(settings.HOME_URL+"/yjzp/")
  191. logger.info(logout_url)
  192. else:
  193. logout_url = settings.HOME_URL + "/yjzp/"
  194. except Exception as e:
  195. traceback.print_exc()
  196. logout_url = settings.HOME_URL+"/yjzp/"
  197. return {
  198. "code": 200,
  199. "msg": "退出成功",
  200. "data": logout_url
  201. }
  202. # 小屏专用
  203. @router.post('/yzy/callback')
  204. async def yzy(
  205. request: Request,
  206. db: Session = Depends(get_db),
  207. data: dict = Depends(remove_xss_json)
  208. ):
  209. code = data['code']
  210. state = data['state']
  211. state_str = base64.b64decode(state).decode('utf-8')
  212. state_json = json.loads(state_str)
  213. logger.info("code:{}, {}", code, state_json)
  214. resp = YzyApi.get_user_info(code)
  215. if resp['errcode'] != 0:
  216. return {
  217. "code": 500,
  218. "msg": "Code异常"
  219. }
  220. user_id = resp['UserId']
  221. row = db.query(YzyOrgUserEntity).filter(YzyOrgUserEntity.userid == user_id).first()
  222. if row is None:
  223. return {
  224. "code": 500,
  225. "msg": "user_id异常"
  226. }
  227. yzy_account = row.account
  228. row = db.query(SysUser).filter(SysUser.yzy_account == yzy_account).first()
  229. if row is None:
  230. return {
  231. "code": 500,
  232. "msg": "用户不是本系统用户"
  233. }
  234. user_id = str(row.user_id)
  235. access_token_expires = timedelta(seconds = 7200)
  236. access_token = security.create_access_token(
  237. data={"sub": user_id}, expires_delta = access_token_expires
  238. )
  239. refresh_token_expires = timedelta(seconds = 7200)
  240. refresh_token = security.create_access_token(
  241. data={"sub": user_id}, expires_delta = refresh_token_expires
  242. )
  243. return {
  244. "code": 200,
  245. "msg": "粤政易登录成功",
  246. "data": {
  247. "access_token": access_token,
  248. "refresh_token": refresh_token,
  249. "expire_in": 7200,
  250. "refresh_expire_in": 7200,
  251. "scope": "",
  252. "redirect_url": state_json['redirect_url']
  253. }
  254. }
  255. # 粤政易token登录
  256. @router.post('/yzylogin')
  257. async def login(
  258. request: Request,
  259. data: dict = Depends(remove_xss_json),
  260. db: Session = Depends(get_db)
  261. ):
  262. code = data['code']
  263. redis_key = "yzy_" + code
  264. user_id = redis_get(redis_key)
  265. if user_id is None:
  266. return {
  267. "code": 500,
  268. "msg": "用户不是本系统用户"
  269. }
  270. row = db.query(SysUser).filter(SysUser.user_id == int(user_id)).first()
  271. if row is None:
  272. return {
  273. "code": 500,
  274. "msg": "用户不是本系统用户"
  275. }
  276. user_id = str(row.user_id)
  277. auth = {
  278. "user_id": user_id,
  279. "user_name": row.user_name,
  280. "nick_name": row.nick_name,
  281. "is_yzy_user": "1"
  282. }
  283. logger.info('auth {}', auth)
  284. request.session['user_auth'] = auth
  285. request.session['user_auth_sign'] = data_auth_sign(auth)
  286. request.session['user_name'] = row.user_name
  287. db_czrz.log_username(db, row.user_id, auth['user_name'], row.nick_name, "登录", "粤政易登录登录成功", request.client.host)
  288. row.login_date = datetime.now()
  289. row.login_ip = request.client.host
  290. row.login = row.login + 1
  291. db.commit()
  292. access_token_expires = timedelta(days = 5)
  293. access_token = security.create_access_token(
  294. data={"sub": user_id}, expires_delta = access_token_expires
  295. )
  296. refresh_token_expires = timedelta(days = 10)
  297. refresh_token = security.create_access_token(
  298. data={"sub": user_id}, expires_delta = refresh_token_expires
  299. )
  300. return {
  301. "code": 200,
  302. "msg": "操作成功",
  303. "data": {
  304. "access_token": access_token,
  305. "refresh_token": refresh_token,
  306. "expire_in": 7200,
  307. "refresh_expire_in": 7200,
  308. "client_id": 0,
  309. "scope": "",
  310. "openid": ""
  311. }
  312. }
  313. # USBKEY登录
  314. @router.post("/login_with_usbkey")
  315. def login_with_usbkey(
  316. request: Request,
  317. username: str = Body(...),
  318. keyID: str = Body(...),
  319. p7SignData: str = Body(...),
  320. p7SignValue: str = Body(...),
  321. db: Session = Depends(get_db)
  322. ):
  323. result = TassApi.verifyP7Sign(p7SignData, p7SignValue)
  324. if result is None:
  325. return {
  326. "code": 500,
  327. "msg": "证书验签失败",
  328. }
  329. logger.info('keyID: {}', keyID)
  330. logger.info('verifyP7Sign: {}', result)
  331. # 对用户账号进行密码机接口加密处理
  332. username = mpfun.enc_data(username)
  333. redis_login_key = "login_user_" + username
  334. login_error_times = redis_get(redis_login_key)
  335. if login_error_times is None:
  336. login_error_times = 0
  337. else:
  338. login_error_times = int(login_error_times)
  339. if login_error_times >= 5:
  340. raise AppException(500, "登录错误多,请5分钟后再尝试!")
  341. row = db.query(SysUser).filter(SysUser.user_name == username).first()
  342. if row is None:
  343. login_error_times = login_error_times + 1
  344. redis_set_with_time(redis_login_key, str(login_error_times), 300)
  345. raise AppException(500, "帐号或者密码错误")
  346. if sys_user_data.sign_valid_row(row) == False:
  347. raise AppException(500, "系统用户表验证异常,已被非法篡改")
  348. user_id = str(row.user_id)
  349. auth = {
  350. "user_id": user_id,
  351. "user_name": mpfun.dec_data(row.user_name),
  352. "nick_name": row.nick_name,
  353. "is_yzy_user": "0"
  354. }
  355. logger.info('auth {}', auth)
  356. request.session['user_auth'] = auth
  357. request.session['user_auth_sign'] = data_auth_sign(auth)
  358. request.session['username'] = username
  359. db_czrz.log_username(db, row.user_id, auth['user_name'], row.nick_name, "登录", "后台USBKEY登录成功", request.client.host)
  360. row.login_date = datetime.now()
  361. row.login_ip = request.client.host
  362. row.login = row.login + 1
  363. db.commit()
  364. access_token_expires = timedelta(days = 5)
  365. access_token = security.create_access_token(
  366. data={"sub": user_id}, expires_delta = access_token_expires
  367. )
  368. refresh_token_expires = timedelta(days = 10)
  369. refresh_token = security.create_access_token(
  370. data={"sub": user_id}, expires_delta = refresh_token_expires
  371. )
  372. return {
  373. "code": 200,
  374. "msg": "操作成功",
  375. "data": {
  376. "access_token": access_token,
  377. "refresh_token": refresh_token,
  378. "expire_in": 7200,
  379. "refresh_expire_in": 7200,
  380. "client_id": "e5cd7e4891bf95d1d19206ce24a7b32e",
  381. "scope": "",
  382. "openid": ""
  383. }
  384. }