data_source_oauth.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. if current_app.config.get('NOTION_INTEGRATION_TYPE') == 'internal':
  37. internal_secret = current_app.config.get('NOTION_INTERNAL_SECRET')
  38. oauth_provider.save_internal_access_token(internal_secret)
  39. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source=success')
  40. else:
  41. auth_url = oauth_provider.get_authorization_url()
  42. return redirect(auth_url)
  43. class OAuthDataSourceCallback(Resource):
  44. def get(self, provider: str):
  45. OAUTH_DATASOURCE_PROVIDERS = get_oauth_providers()
  46. with current_app.app_context():
  47. oauth_provider = OAUTH_DATASOURCE_PROVIDERS.get(provider)
  48. if not oauth_provider:
  49. return {'error': 'Invalid provider'}, 400
  50. if 'code' in request.args:
  51. code = request.args.get('code')
  52. try:
  53. oauth_provider.get_access_token(code)
  54. except requests.exceptions.HTTPError as e:
  55. logging.exception(
  56. f"An error occurred during the OAuthCallback process with {provider}: {e.response.text}")
  57. return {'error': 'OAuth data source process failed'}, 400
  58. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source=success')
  59. elif 'error' in request.args:
  60. error = request.args.get('error')
  61. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source={error}')
  62. else:
  63. return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_data_source=access_denied')
  64. class OAuthDataSourceSync(Resource):
  65. @setup_required
  66. @login_required
  67. @account_initialization_required
  68. def get(self, provider, binding_id):
  69. provider = str(provider)
  70. binding_id = str(binding_id)
  71. OAUTH_DATASOURCE_PROVIDERS = get_oauth_providers()
  72. with current_app.app_context():
  73. oauth_provider = OAUTH_DATASOURCE_PROVIDERS.get(provider)
  74. if not oauth_provider:
  75. return {'error': 'Invalid provider'}, 400
  76. try:
  77. oauth_provider.sync_data_source(binding_id)
  78. except requests.exceptions.HTTPError as e:
  79. logging.exception(
  80. f"An error occurred during the OAuthCallback process with {provider}: {e.response.text}")
  81. return {'error': 'OAuth data source process failed'}, 400
  82. return {'result': 'success'}, 200
  83. api.add_resource(OAuthDataSource, '/oauth/data-source/<string:provider>')
  84. api.add_resource(OAuthDataSourceCallback, '/oauth/data-source/callback/<string:provider>')
  85. api.add_resource(OAuthDataSourceSync, '/oauth/data-source/<string:provider>/<uuid:binding_id>/sync')