Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

oauth.py 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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.billing_service import BillingService
  20. from services.errors.account import AccountNotFoundError, AccountRegisterError
  21. from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkSpaceNotFoundError
  22. from services.feature_service import FeatureService
  23. from .. import api, console_ns
  24. logger = logging.getLogger(__name__)
  25. def get_oauth_providers():
  26. with current_app.app_context():
  27. if not dify_config.GITHUB_CLIENT_ID or not dify_config.GITHUB_CLIENT_SECRET:
  28. github_oauth = None
  29. else:
  30. github_oauth = GitHubOAuth(
  31. client_id=dify_config.GITHUB_CLIENT_ID,
  32. client_secret=dify_config.GITHUB_CLIENT_SECRET,
  33. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",
  34. )
  35. if not dify_config.GOOGLE_CLIENT_ID or not dify_config.GOOGLE_CLIENT_SECRET:
  36. google_oauth = None
  37. else:
  38. google_oauth = GoogleOAuth(
  39. client_id=dify_config.GOOGLE_CLIENT_ID,
  40. client_secret=dify_config.GOOGLE_CLIENT_SECRET,
  41. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",
  42. )
  43. OAUTH_PROVIDERS = {"github": github_oauth, "google": google_oauth}
  44. return OAUTH_PROVIDERS
  45. @console_ns.route("/oauth/login/<provider>")
  46. class OAuthLogin(Resource):
  47. @api.doc("oauth_login")
  48. @api.doc(description="Initiate OAuth login process")
  49. @api.doc(params={"provider": "OAuth provider name (github/google)", "invite_token": "Optional invitation token"})
  50. @api.response(302, "Redirect to OAuth authorization URL")
  51. @api.response(400, "Invalid provider")
  52. def get(self, provider: str):
  53. invite_token = request.args.get("invite_token") or None
  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. auth_url = oauth_provider.get_authorization_url(invite_token=invite_token)
  60. return redirect(auth_url)
  61. @console_ns.route("/oauth/authorize/<provider>")
  62. class OAuthCallback(Resource):
  63. @api.doc("oauth_callback")
  64. @api.doc(description="Handle OAuth callback and complete login process")
  65. @api.doc(
  66. params={
  67. "provider": "OAuth provider name (github/google)",
  68. "code": "Authorization code from OAuth provider",
  69. "state": "Optional state parameter (used for invite token)",
  70. }
  71. )
  72. @api.response(302, "Redirect to console with access token")
  73. @api.response(400, "OAuth process failed")
  74. def get(self, provider: str):
  75. OAUTH_PROVIDERS = get_oauth_providers()
  76. with current_app.app_context():
  77. oauth_provider = OAUTH_PROVIDERS.get(provider)
  78. if not oauth_provider:
  79. return {"error": "Invalid provider"}, 400
  80. code = request.args.get("code")
  81. state = request.args.get("state")
  82. invite_token = None
  83. if state:
  84. invite_token = state
  85. if not code:
  86. return {"error": "Authorization code is required"}, 400
  87. try:
  88. token = oauth_provider.get_access_token(code)
  89. user_info = oauth_provider.get_user_info(token)
  90. except requests.RequestException as e:
  91. error_text = e.response.text if e.response else str(e)
  92. logger.exception("An error occurred during the OAuth process with %s: %s", provider, error_text)
  93. return {"error": "OAuth process failed"}, 400
  94. if invite_token and RegisterService.is_valid_invite_token(invite_token):
  95. invitation = RegisterService.get_invitation_by_token(token=invite_token)
  96. if invitation:
  97. invitation_email = invitation.get("email", None)
  98. if invitation_email != user_info.email:
  99. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Invalid invitation token.")
  100. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin/invite-settings?invite_token={invite_token}")
  101. try:
  102. account = _generate_account(provider, user_info)
  103. except AccountNotFoundError:
  104. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account not found.")
  105. except (WorkSpaceNotFoundError, WorkSpaceNotAllowedCreateError):
  106. return redirect(
  107. f"{dify_config.CONSOLE_WEB_URL}/signin"
  108. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  109. )
  110. except AccountRegisterError as e:
  111. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message={e.description}")
  112. # Check account status
  113. if account.status == AccountStatus.BANNED.value:
  114. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account is banned.")
  115. if account.status == AccountStatus.PENDING.value:
  116. account.status = AccountStatus.ACTIVE.value
  117. account.initialized_at = naive_utc_now()
  118. db.session.commit()
  119. try:
  120. TenantService.create_owner_tenant_if_not_exist(account)
  121. except Unauthorized:
  122. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Workspace not found.")
  123. except WorkSpaceNotAllowedCreateError:
  124. return redirect(
  125. f"{dify_config.CONSOLE_WEB_URL}/signin"
  126. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  127. )
  128. token_pair = AccountService.login(
  129. account=account,
  130. ip_address=extract_remote_ip(request),
  131. )
  132. return redirect(
  133. f"{dify_config.CONSOLE_WEB_URL}?access_token={token_pair.access_token}&refresh_token={token_pair.refresh_token}"
  134. )
  135. def _get_account_by_openid_or_email(provider: str, user_info: OAuthUserInfo) -> Optional[Account]:
  136. account: Optional[Account] = Account.get_by_openid(provider, user_info.id)
  137. if not account:
  138. with Session(db.engine) as session:
  139. account = session.execute(select(Account).filter_by(email=user_info.email)).scalar_one_or_none()
  140. return account
  141. def _generate_account(provider: str, user_info: OAuthUserInfo):
  142. # Get account by openid or email.
  143. account = _get_account_by_openid_or_email(provider, user_info)
  144. if account:
  145. tenants = TenantService.get_join_tenants(account)
  146. if not tenants:
  147. if not FeatureService.get_system_features().is_allow_create_workspace:
  148. raise WorkSpaceNotAllowedCreateError()
  149. else:
  150. new_tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  151. TenantService.create_tenant_member(new_tenant, account, role="owner")
  152. account.current_tenant = new_tenant
  153. tenant_was_created.send(new_tenant)
  154. if not account:
  155. if not FeatureService.get_system_features().is_allow_register:
  156. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(user_info.email):
  157. raise AccountRegisterError(
  158. description=(
  159. "This email account has been deleted within the past "
  160. "30 days and is temporarily unavailable for new account registration"
  161. )
  162. )
  163. else:
  164. raise AccountRegisterError(description=("Invalid email or password"))
  165. account_name = user_info.name or "Dify"
  166. account = RegisterService.register(
  167. email=user_info.email, name=account_name, password=None, open_id=user_info.id, provider=provider
  168. )
  169. # Set interface language
  170. preferred_lang = request.accept_languages.best_match(languages)
  171. if preferred_lang and preferred_lang in languages:
  172. interface_language = preferred_lang
  173. else:
  174. interface_language = languages[0]
  175. account.interface_language = interface_language
  176. db.session.commit()
  177. # Link account
  178. AccountService.link_account_integrate(provider, user_info.id, account)
  179. return account