data_source_oauth.py 3.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import logging
  2. from datetime import datetime
  3. from typing import Optional
  4. import flask_login
  5. import requests
  6. from flask import request, redirect, current_app, session
  7. from flask_login import current_user, login_required
  8. from flask_restful import Resource
  9. from werkzeug.exceptions import Forbidden
  10. from libs.oauth_data_source import NotionOAuth
  11. from controllers.console import api
  12. from ..setup import setup_required
  13. from ..wraps import account_initialization_required
  14. def get_oauth_providers():
  15. with current_app.app_context():
  16. notion_oauth = NotionOAuth(client_id=current_app.config.get('NOTION_CLIENT_ID'),
  17. client_secret=current_app.config.get(
  18. 'NOTION_CLIENT_SECRET'),
  19. redirect_uri=current_app.config.get(
  20. 'CONSOLE_URL') + '/console/api/oauth/data-source/callback/notion')
  21. OAUTH_PROVIDERS = {
  22. 'notion': notion_oauth
  23. }
  24. return OAUTH_PROVIDERS
  25. class OAuthDataSource(Resource):
  26. def get(self, provider: str):
  27. # The role of the current user in the table must be admin or owner
  28. if current_user.current_tenant.current_role not in ['admin', 'owner']:
  29. raise Forbidden()
  30. OAUTH_DATASOURCE_PROVIDERS = get_oauth_providers()
  31. with current_app.app_context():
  32. oauth_provider = OAUTH_DATASOURCE_PROVIDERS.get(provider)
  33. print(vars(oauth_provider))
  34. if not oauth_provider:
  35. return {'error': 'Invalid provider'}, 400
  36. auth_url = oauth_provider.get_authorization_url()
  37. return redirect(auth_url)
  38. class OAuthDataSourceCallback(Resource):
  39. def get(self, provider: str):
  40. OAUTH_DATASOURCE_PROVIDERS = get_oauth_providers()
  41. with current_app.app_context():
  42. oauth_provider = OAUTH_DATASOURCE_PROVIDERS.get(provider)
  43. if not oauth_provider:
  44. return {'error': 'Invalid provider'}, 400
  45. if 'code' in request.args:
  46. code = request.args.get('code')
  47. try:
  48. oauth_provider.get_access_token(code)
  49. except requests.exceptions.HTTPError as e:
  50. logging.exception(
  51. f"An error occurred during the OAuthCallback process with {provider}: {e.response.text}")
  52. return {'error': 'OAuth data source process failed'}, 400
  53. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source=success')
  54. elif 'error' in request.args:
  55. error = request.args.get('error')
  56. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source={error}')
  57. else:
  58. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source=access_denied')
  59. class OAuthDataSourceSync(Resource):
  60. @setup_required
  61. @login_required
  62. @account_initialization_required
  63. def get(self, provider, binding_id):
  64. provider = str(provider)
  65. binding_id = str(binding_id)
  66. OAUTH_DATASOURCE_PROVIDERS = get_oauth_providers()
  67. with current_app.app_context():
  68. oauth_provider = OAUTH_DATASOURCE_PROVIDERS.get(provider)
  69. if not oauth_provider:
  70. return {'error': 'Invalid provider'}, 400
  71. try:
  72. oauth_provider.sync_data_source(binding_id)
  73. except requests.exceptions.HTTPError as e:
  74. logging.exception(
  75. f"An error occurred during the OAuthCallback process with {provider}: {e.response.text}")
  76. return {'error': 'OAuth data source process failed'}, 400
  77. return {'result': 'success'}, 200
  78. api.add_resource(OAuthDataSource, '/oauth/data-source/<string:provider>')
  79. api.add_resource(OAuthDataSourceCallback, '/oauth/data-source/callback/<string:provider>')
  80. api.add_resource(OAuthDataSourceSync, '/oauth/data-source/<string:provider>/<uuid:binding_id>/sync')