Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

oauth.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. try:
  67. token = oauth_provider.get_access_token(code)
  68. user_info = oauth_provider.get_user_info(token)
  69. except requests.RequestException as e:
  70. error_text = e.response.text if e.response else str(e)
  71. logger.exception("An error occurred during the OAuth process with %s: %s", provider, error_text)
  72. return {"error": "OAuth process failed"}, 400
  73. if invite_token and RegisterService.is_valid_invite_token(invite_token):
  74. invitation = RegisterService._get_invitation_by_token(token=invite_token)
  75. if invitation:
  76. invitation_email = invitation.get("email", None)
  77. if invitation_email != user_info.email:
  78. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Invalid invitation token.")
  79. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin/invite-settings?invite_token={invite_token}")
  80. try:
  81. account = _generate_account(provider, user_info)
  82. except AccountNotFoundError:
  83. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account not found.")
  84. except (WorkSpaceNotFoundError, WorkSpaceNotAllowedCreateError):
  85. return redirect(
  86. f"{dify_config.CONSOLE_WEB_URL}/signin"
  87. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  88. )
  89. except AccountRegisterError as e:
  90. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message={e.description}")
  91. # Check account status
  92. if account.status == AccountStatus.BANNED.value:
  93. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account is banned.")
  94. if account.status == AccountStatus.PENDING.value:
  95. account.status = AccountStatus.ACTIVE.value
  96. account.initialized_at = naive_utc_now()
  97. db.session.commit()
  98. try:
  99. TenantService.create_owner_tenant_if_not_exist(account)
  100. except Unauthorized:
  101. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Workspace not found.")
  102. except WorkSpaceNotAllowedCreateError:
  103. return redirect(
  104. f"{dify_config.CONSOLE_WEB_URL}/signin"
  105. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  106. )
  107. token_pair = AccountService.login(
  108. account=account,
  109. ip_address=extract_remote_ip(request),
  110. )
  111. return redirect(
  112. f"{dify_config.CONSOLE_WEB_URL}?access_token={token_pair.access_token}&refresh_token={token_pair.refresh_token}"
  113. )
  114. def _get_account_by_openid_or_email(provider: str, user_info: OAuthUserInfo) -> Optional[Account]:
  115. account: Optional[Account] = Account.get_by_openid(provider, user_info.id)
  116. if not account:
  117. with Session(db.engine) as session:
  118. account = session.execute(select(Account).filter_by(email=user_info.email)).scalar_one_or_none()
  119. return account
  120. def _generate_account(provider: str, user_info: OAuthUserInfo):
  121. # Get account by openid or email.
  122. account = _get_account_by_openid_or_email(provider, user_info)
  123. if account:
  124. tenants = TenantService.get_join_tenants(account)
  125. if not tenants:
  126. if not FeatureService.get_system_features().is_allow_create_workspace:
  127. raise WorkSpaceNotAllowedCreateError()
  128. else:
  129. new_tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  130. TenantService.create_tenant_member(new_tenant, account, role="owner")
  131. account.current_tenant = new_tenant
  132. tenant_was_created.send(new_tenant)
  133. if not account:
  134. if not FeatureService.get_system_features().is_allow_register:
  135. raise AccountNotFoundError()
  136. account_name = user_info.name or "Dify"
  137. account = RegisterService.register(
  138. email=user_info.email, name=account_name, password=None, open_id=user_info.id, provider=provider
  139. )
  140. # Set interface language
  141. preferred_lang = request.accept_languages.best_match(languages)
  142. if preferred_lang and preferred_lang in languages:
  143. interface_language = preferred_lang
  144. else:
  145. interface_language = languages[0]
  146. account.interface_language = interface_language
  147. db.session.commit()
  148. # Link account
  149. AccountService.link_account_integrate(provider, user_info.id, account)
  150. return account
  151. api.add_resource(OAuthLogin, "/oauth/login/<provider>")
  152. api.add_resource(OAuthCallback, "/oauth/authorize/<provider>")