oauth.py 7.2 KB

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