oauth.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import logging
  2. from datetime import datetime, timezone
  3. from typing import Optional
  4. import requests
  5. from flask import current_app, redirect, request
  6. from flask_restful import Resource
  7. from werkzeug.exceptions import Unauthorized
  8. from configs import dify_config
  9. from constants.languages import languages
  10. from events.tenant_event import tenant_was_created
  11. from extensions.ext_database import db
  12. from libs.helper import extract_remote_ip
  13. from libs.oauth import GitHubOAuth, GoogleOAuth, OAuthUserInfo
  14. from models import Account
  15. from models.account import AccountStatus
  16. from services.account_service import AccountService, RegisterService, TenantService
  17. from services.errors.account import AccountNotFoundError
  18. from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkSpaceNotFoundError
  19. from services.feature_service import FeatureService
  20. from .. import api
  21. def get_oauth_providers():
  22. with current_app.app_context():
  23. if not dify_config.GITHUB_CLIENT_ID or not dify_config.GITHUB_CLIENT_SECRET:
  24. github_oauth = None
  25. else:
  26. github_oauth = GitHubOAuth(
  27. client_id=dify_config.GITHUB_CLIENT_ID,
  28. client_secret=dify_config.GITHUB_CLIENT_SECRET,
  29. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",
  30. )
  31. if not dify_config.GOOGLE_CLIENT_ID or not dify_config.GOOGLE_CLIENT_SECRET:
  32. google_oauth = None
  33. else:
  34. google_oauth = GoogleOAuth(
  35. client_id=dify_config.GOOGLE_CLIENT_ID,
  36. client_secret=dify_config.GOOGLE_CLIENT_SECRET,
  37. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",
  38. )
  39. OAUTH_PROVIDERS = {"github": github_oauth, "google": google_oauth}
  40. return OAUTH_PROVIDERS
  41. class OAuthLogin(Resource):
  42. def get(self, provider: str):
  43. invite_token = request.args.get("invite_token") or None
  44. OAUTH_PROVIDERS = get_oauth_providers()
  45. with current_app.app_context():
  46. oauth_provider = OAUTH_PROVIDERS.get(provider)
  47. print(vars(oauth_provider))
  48. if not oauth_provider:
  49. return {"error": "Invalid provider"}, 400
  50. auth_url = oauth_provider.get_authorization_url(invite_token=invite_token)
  51. return redirect(auth_url)
  52. class OAuthCallback(Resource):
  53. def get(self, provider: str):
  54. OAUTH_PROVIDERS = get_oauth_providers()
  55. with current_app.app_context():
  56. oauth_provider = OAUTH_PROVIDERS.get(provider)
  57. if not oauth_provider:
  58. return {"error": "Invalid provider"}, 400
  59. code = request.args.get("code")
  60. state = request.args.get("state")
  61. invite_token = None
  62. if state:
  63. invite_token = state
  64. try:
  65. token = oauth_provider.get_access_token(code)
  66. user_info = oauth_provider.get_user_info(token)
  67. except requests.exceptions.HTTPError as e:
  68. logging.exception(f"An error occurred during the OAuth process with {provider}: {e.response.text}")
  69. return {"error": "OAuth process failed"}, 400
  70. if invite_token and RegisterService.is_valid_invite_token(invite_token):
  71. invitation = RegisterService._get_invitation_by_token(token=invite_token)
  72. if invitation:
  73. invitation_email = invitation.get("email", None)
  74. if invitation_email != user_info.email:
  75. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Invalid invitation token.")
  76. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin/invite-settings?invite_token={invite_token}")
  77. try:
  78. account = _generate_account(provider, user_info)
  79. except AccountNotFoundError:
  80. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account not found.")
  81. except (WorkSpaceNotFoundError, WorkSpaceNotAllowedCreateError):
  82. return redirect(
  83. f"{dify_config.CONSOLE_WEB_URL}/signin"
  84. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  85. )
  86. # Check account status
  87. if account.status == AccountStatus.BANNED.value:
  88. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account is banned.")
  89. if account.status == AccountStatus.PENDING.value:
  90. account.status = AccountStatus.ACTIVE.value
  91. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  92. db.session.commit()
  93. try:
  94. TenantService.create_owner_tenant_if_not_exist(account)
  95. except Unauthorized:
  96. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Workspace not found.")
  97. except WorkSpaceNotAllowedCreateError:
  98. return redirect(
  99. f"{dify_config.CONSOLE_WEB_URL}/signin"
  100. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  101. )
  102. token_pair = AccountService.login(
  103. account=account,
  104. ip_address=extract_remote_ip(request),
  105. )
  106. return redirect(
  107. f"{dify_config.CONSOLE_WEB_URL}?access_token={token_pair.access_token}&refresh_token={token_pair.refresh_token}"
  108. )
  109. def _get_account_by_openid_or_email(provider: str, user_info: OAuthUserInfo) -> Optional[Account]:
  110. account = Account.get_by_openid(provider, user_info.id)
  111. if not account:
  112. account = Account.query.filter_by(email=user_info.email).first()
  113. return account
  114. def _generate_account(provider: str, user_info: OAuthUserInfo):
  115. # Get account by openid or email.
  116. account = _get_account_by_openid_or_email(provider, user_info)
  117. if account:
  118. tenant = TenantService.get_join_tenants(account)
  119. if not tenant:
  120. if not FeatureService.get_system_features().is_allow_create_workspace:
  121. raise WorkSpaceNotAllowedCreateError()
  122. else:
  123. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  124. TenantService.create_tenant_member(tenant, account, role="owner")
  125. account.current_tenant = tenant
  126. tenant_was_created.send(tenant)
  127. if not account:
  128. if not FeatureService.get_system_features().is_allow_register:
  129. raise AccountNotFoundError()
  130. account_name = user_info.name or "Dify"
  131. account = RegisterService.register(
  132. email=user_info.email, name=account_name, password=None, open_id=user_info.id, provider=provider
  133. )
  134. # Set interface language
  135. preferred_lang = request.accept_languages.best_match(languages)
  136. if preferred_lang and preferred_lang in languages:
  137. interface_language = preferred_lang
  138. else:
  139. interface_language = languages[0]
  140. account.interface_language = interface_language
  141. db.session.commit()
  142. # Link account
  143. AccountService.link_account_integrate(provider, user_info.id, account)
  144. return account
  145. api.add_resource(OAuthLogin, "/oauth/login/<provider>")
  146. api.add_resource(OAuthCallback, "/oauth/authorize/<provider>")