data_source_oauth.py 4.2 KB

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