v1.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
  2. from werkzeug.security import check_password_hash
  3. from fastapi import APIRouter, Request, Response
  4. from fastapi import HTTPException, Header
  5. from fastapi.responses import JSONResponse
  6. from hub import methods, Global
  7. router = APIRouter()
  8. # mdb = Global.get_mongodb_client()
  9. # serializer = Serializer(secret_key='casper.com@2021', expires_in=86400 * 100) # debug
  10. serializer = Serializer(secret_key='casper.com@2021', expires_in=86400) # release
  11. def get_token_by_user(user):
  12. """生成token"""
  13. data = {
  14. 'id': user.get('uid'),
  15. 'username': user.get('username'),
  16. 'password': user.get('password'),
  17. }
  18. return serializer.dumps(data).decode('utf-8')
  19. @router.post('/token/api')
  20. async def get_token(request: Request, response: Response):
  21. """获取令牌"""
  22. methods.debug_log('api.get_token.28', f"#now at {methods.now_string()}, #ip: {request.client.host}")
  23. # --- check key --- # debug
  24. # node_api = NodeApi()
  25. # if not node_api.verify_key():
  26. # return JSONResponse(status_code=401, content=dict(message='not verified!', code=1))
  27. # --- get params ---
  28. params = await request.json()
  29. username = params.get('username')
  30. password = params.get('password')
  31. user = Global.mdb.get_one('User', {'username': username})
  32. if user:
  33. role_name = Global.mdb.get_one_by_id('UserRole', user.get('role_id')).get('role_name')
  34. else:
  35. role_name = ''
  36. # --- fail log---
  37. if not user:
  38. data = {
  39. 'username': username,
  40. 'is_login': 'Fail',
  41. 'role_name': role_name,
  42. 'login_at': methods.now_ts(),
  43. 'login_ip': request.client.host,
  44. }
  45. Global.mdb.add('UserLoginLog', data)
  46. code = 2
  47. elif not check_password_hash(user['password'], password):
  48. data = {
  49. 'username': username,
  50. 'is_login': 'Fail',
  51. 'role_name': role_name,
  52. 'login_at': methods.now_ts(),
  53. 'login_ip': request.client.host,
  54. }
  55. Global.mdb.add('UserLoginLog', data)
  56. code = 3
  57. else:
  58. data = {
  59. 'username': username,
  60. 'role_name': role_name,
  61. 'is_login': 'Pass',
  62. 'login_at': methods.now_ts(),
  63. 'login_ip': request.client.host,
  64. }
  65. Global.mdb.add('UserLoginLog', data)
  66. code = 0
  67. # --- 登录失败 ---
  68. if code:
  69. return JSONResponse(status_code=401, content=dict(message='unauthorized access!', code=code))
  70. # --- make token ---
  71. data = {
  72. 'id': str(user['_id']),
  73. 'username': user['username'],
  74. 'password': user['password'],
  75. }
  76. token = serializer.dumps(data).decode('utf-8')
  77. content = dict(message='authorization passed.', uid=str(user['_id']), role_name=role_name, code=0)
  78. headers = {'authorization': token}
  79. return JSONResponse(content=content, headers=headers)
  80. async def login_required(request: Request):
  81. """
  82. 检查登录token
  83. methods.debug_log('token.login_required.96', f"#code: {code}")
  84. """
  85. # --- check ---
  86. # if request.method == 'POST':
  87. # sources = await request.json()
  88. # tag = sources.get('tag', 'v1')
  89. # code = int(sources.get('code'))
  90. # # methods.debug_log('token.login_required', f"m-107: code -> {code} | token -> {token}")
  91. # if not token and tag == 'v3' and code in [1102, 8201]:
  92. # methods.debug_log('token.login_required', f"m-103: code -> {code}")
  93. # superuser = Global.mdb.get_one('User', {'username': 'admin'})
  94. # return {
  95. # 'uid': str(superuser.get('_id')),
  96. # 'username': 'admin',
  97. # 'password': 'admin',
  98. # 'role_id': superuser.get('role_id'),
  99. # 'skip_is': True,
  100. # }
  101. # --- check --- todo 屏蔽token验证,正常情况下应放开
  102. # if not token:
  103. # # raise HTTPException(status_code=401, detail='unauthorized access!')
  104. # raise HTTPException(status_code=401, headers=dict(message='unauthorized access!', code='4'))
  105. # --- fill --- todo 屏蔽token验证,正常情况下应放开
  106. # try:
  107. # data = serializer.loads(token)
  108. # user = Global.mdb.get_one_by_id('User', data['id'])
  109. # role_id = user.get('role_id')
  110. # # role_acl = Global.mdb.get_one_by_id('UserRole', role_id).get('role_acl')
  111. # return {
  112. # 'uid': data['id'],
  113. # 'username': data['username'],
  114. # 'password': data['password'],
  115. # 'role_id': role_id,
  116. # }
  117. # except Exception as e:
  118. # # raise HTTPException(status_code=401, detail='unauthorized access!')
  119. # raise HTTPException(status_code=401, headers=dict(message='unauthorized access!', code='5'))
  120. # todo 正常情况下应屏蔽
  121. return {'skip_is': True}