auth.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. jupyter_download = False
  34. if super_admin_role in switch.role_ids:
  35. jupyter_download = True
  36. token_data = {"user_id": switch.user_id, "user_name": switch.user_name,
  37. "project_id": switch.project_id, "role_id": role_id}
  38. token_data_str = json.dumps(token_data)
  39. access_token = encode_base64(token_data_str).replace('\n', '')
  40. return {"access_token": access_token, "token_type": "Bearer", "role_id": role_id, "jupyter_download": jupyter_download}
  41. @router.post("/login", response_model=schemas.Token)
  42. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  43. user_id, project_id = form_data.username, form_data.password
  44. token_data = {"user_id": user_id, "user_name": "刘涛",
  45. "project_id": project_id, "role_id": 1}
  46. token_data_str = json.dumps(token_data)
  47. access_token = encode_base64(token_data_str).replace('\n', '')
  48. return {"access_token": access_token, "token_type": "bearer"}