You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oauth.py 8.8KB

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