Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

oauth.py 7.6KB

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