oauth.py 7.5 KB

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