auth.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import json
  2. from typing import List
  3. from fastapi import Depends
  4. from fastapi import APIRouter
  5. from fastapi.security import OAuth2PasswordRequestForm
  6. from app import schemas
  7. from app.utils.utils import encode_base64
  8. from utils.sx_time import sxtimeit
  9. from utils.sx_web import web_try
  10. from configs.settings import config
  11. super_admin_role = config.get('PERMISSIONS', 'super_admin_role')
  12. project_admin_role = config.get('PERMISSIONS', 'project_admin_role')
  13. special_project_id = config.get('PERMISSIONS', 'special_project_id')
  14. router = APIRouter(
  15. prefix="/jpt/auth",
  16. tags=["auth-接口文档生成token"],
  17. )
  18. @router.post("/switch")
  19. @web_try()
  20. @sxtimeit
  21. def switch_project(switch: schemas.SwitchProject):
  22. role_id = 0
  23. if switch.project_id == special_project_id and super_admin_role in switch.role_ids:
  24. role_id = 1
  25. elif switch.project_id == special_project_id and project_admin_role in switch.role_ids:
  26. role_id = 2
  27. elif switch.project_id == special_project_id:
  28. role_id = 3
  29. elif project_admin_role in switch.role_ids or super_admin_role in switch.role_ids:
  30. role_id = 4
  31. else:
  32. role_id = 5
  33. token_data = {"user_id": switch.user_id,"user_name":switch.user_name,"project_id": switch.project_id, "role_id": role_id}
  34. token_data_str =json.dumps(token_data)
  35. access_token = encode_base64(token_data_str).replace('\n','')
  36. return {"access_token": access_token, "token_type": "Bearer", "role_id": role_id}
  37. @router.post("/login",response_model=schemas.Token)
  38. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  39. user_id, project_id = form_data.username, form_data.password
  40. token_data = {"user_id": user_id,"user_name":"刘涛","project_id": project_id, "role_id": 1}
  41. token_data_str =json.dumps(token_data)
  42. access_token = encode_base64(token_data_str).replace('\n','')
  43. return {"access_token": access_token, "token_type": "bearer"}