您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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_login import current_user
  7. from flask_restful import Resource
  8. from sqlalchemy import select
  9. from sqlalchemy.orm import Session
  10. from werkzeug.exceptions import Forbidden, NotFound, Unauthorized
  11. from configs import dify_config
  12. from constants.languages import languages
  13. from controllers.console.wraps import account_initialization_required, setup_required
  14. from core.plugin.impl.oauth import OAuthHandler
  15. from events.tenant_event import tenant_was_created
  16. from extensions.ext_database import db
  17. from libs.helper import extract_remote_ip
  18. from libs.login import login_required
  19. from libs.oauth import GitHubOAuth, GoogleOAuth, OAuthUserInfo
  20. from models import Account
  21. from models.account import AccountStatus
  22. from models.oauth import DatasourceOauthParamConfig, DatasourceProvider
  23. from services.account_service import AccountService, RegisterService, TenantService
  24. from services.errors.account import AccountNotFoundError, AccountRegisterError
  25. from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkSpaceNotFoundError
  26. from services.feature_service import FeatureService
  27. from .. import api
  28. def get_oauth_providers():
  29. with current_app.app_context():
  30. if not dify_config.GITHUB_CLIENT_ID or not dify_config.GITHUB_CLIENT_SECRET:
  31. github_oauth = None
  32. else:
  33. github_oauth = GitHubOAuth(
  34. client_id=dify_config.GITHUB_CLIENT_ID,
  35. client_secret=dify_config.GITHUB_CLIENT_SECRET,
  36. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",
  37. )
  38. if not dify_config.GOOGLE_CLIENT_ID or not dify_config.GOOGLE_CLIENT_SECRET:
  39. google_oauth = None
  40. else:
  41. google_oauth = GoogleOAuth(
  42. client_id=dify_config.GOOGLE_CLIENT_ID,
  43. client_secret=dify_config.GOOGLE_CLIENT_SECRET,
  44. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",
  45. )
  46. OAUTH_PROVIDERS = {"github": github_oauth, "google": google_oauth}
  47. return OAUTH_PROVIDERS
  48. class OAuthLogin(Resource):
  49. def get(self, provider: str):
  50. invite_token = request.args.get("invite_token") or None
  51. OAUTH_PROVIDERS = get_oauth_providers()
  52. with current_app.app_context():
  53. oauth_provider = OAUTH_PROVIDERS.get(provider)
  54. if not oauth_provider:
  55. return {"error": "Invalid provider"}, 400
  56. auth_url = oauth_provider.get_authorization_url(invite_token=invite_token)
  57. return redirect(auth_url)
  58. class OAuthCallback(Resource):
  59. def get(self, provider: str):
  60. OAUTH_PROVIDERS = get_oauth_providers()
  61. with current_app.app_context():
  62. oauth_provider = OAUTH_PROVIDERS.get(provider)
  63. if not oauth_provider:
  64. return {"error": "Invalid provider"}, 400
  65. code = request.args.get("code")
  66. state = request.args.get("state")
  67. invite_token = None
  68. if state:
  69. invite_token = state
  70. try:
  71. token = oauth_provider.get_access_token(code)
  72. user_info = oauth_provider.get_user_info(token)
  73. except requests.exceptions.RequestException as e:
  74. error_text = e.response.text if e.response else str(e)
  75. logging.exception(f"An error occurred during the OAuth process with {provider}: {error_text}")
  76. return {"error": "OAuth process failed"}, 400
  77. if invite_token and RegisterService.is_valid_invite_token(invite_token):
  78. invitation = RegisterService._get_invitation_by_token(token=invite_token)
  79. if invitation:
  80. invitation_email = invitation.get("email", None)
  81. if invitation_email != user_info.email:
  82. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Invalid invitation token.")
  83. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin/invite-settings?invite_token={invite_token}")
  84. try:
  85. account = _generate_account(provider, user_info)
  86. except AccountNotFoundError:
  87. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account not found.")
  88. except (WorkSpaceNotFoundError, WorkSpaceNotAllowedCreateError):
  89. return redirect(
  90. f"{dify_config.CONSOLE_WEB_URL}/signin"
  91. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  92. )
  93. except AccountRegisterError as e:
  94. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message={e.description}")
  95. # Check account status
  96. if account.status == AccountStatus.BANNED.value:
  97. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Account is banned.")
  98. if account.status == AccountStatus.PENDING.value:
  99. account.status = AccountStatus.ACTIVE.value
  100. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  101. db.session.commit()
  102. try:
  103. TenantService.create_owner_tenant_if_not_exist(account)
  104. except Unauthorized:
  105. return redirect(f"{dify_config.CONSOLE_WEB_URL}/signin?message=Workspace not found.")
  106. except WorkSpaceNotAllowedCreateError:
  107. return redirect(
  108. f"{dify_config.CONSOLE_WEB_URL}/signin"
  109. "?message=Workspace not found, please contact system admin to invite you to join in a workspace."
  110. )
  111. token_pair = AccountService.login(
  112. account=account,
  113. ip_address=extract_remote_ip(request),
  114. )
  115. return redirect(
  116. f"{dify_config.CONSOLE_WEB_URL}?access_token={token_pair.access_token}&refresh_token={token_pair.refresh_token}"
  117. )
  118. def _get_account_by_openid_or_email(provider: str, user_info: OAuthUserInfo) -> Optional[Account]:
  119. account: Optional[Account] = Account.get_by_openid(provider, user_info.id)
  120. if not account:
  121. with Session(db.engine) as session:
  122. account = session.execute(select(Account).filter_by(email=user_info.email)).scalar_one_or_none()
  123. return account
  124. def _generate_account(provider: str, user_info: OAuthUserInfo):
  125. # Get account by openid or email.
  126. account = _get_account_by_openid_or_email(provider, user_info)
  127. if account:
  128. tenants = TenantService.get_join_tenants(account)
  129. if not tenants:
  130. if not FeatureService.get_system_features().is_allow_create_workspace:
  131. raise WorkSpaceNotAllowedCreateError()
  132. else:
  133. new_tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  134. TenantService.create_tenant_member(new_tenant, account, role="owner")
  135. account.current_tenant = new_tenant
  136. tenant_was_created.send(new_tenant)
  137. if not account:
  138. if not FeatureService.get_system_features().is_allow_register:
  139. raise AccountNotFoundError()
  140. account_name = user_info.name or "Dify"
  141. account = RegisterService.register(
  142. email=user_info.email, name=account_name, password=None, open_id=user_info.id, provider=provider
  143. )
  144. # Set interface language
  145. preferred_lang = request.accept_languages.best_match(languages)
  146. if preferred_lang and preferred_lang in languages:
  147. interface_language = preferred_lang
  148. else:
  149. interface_language = languages[0]
  150. account.interface_language = interface_language
  151. db.session.commit()
  152. # Link account
  153. AccountService.link_account_integrate(provider, user_info.id, account)
  154. return account
  155. class PluginOauthApi(Resource):
  156. @setup_required
  157. @login_required
  158. @account_initialization_required
  159. def get(self, provider, plugin_id):
  160. # Check user role first
  161. if not current_user.is_editor:
  162. raise Forbidden()
  163. # get all plugin oauth configs
  164. plugin_oauth_config = db.session.query(DatasourceOauthParamConfig).filter_by(
  165. provider=provider,
  166. plugin_id=plugin_id
  167. ).first()
  168. if not plugin_oauth_config:
  169. raise NotFound()
  170. oauth_handler = OAuthHandler()
  171. response = oauth_handler.get_authorization_url(
  172. current_user.current_tenant.id,
  173. current_user.id,
  174. plugin_id,
  175. provider,
  176. system_credentials=plugin_oauth_config.system_credentials
  177. )
  178. return response.model_dump()
  179. class PluginOauthCallback(Resource):
  180. @setup_required
  181. @login_required
  182. @account_initialization_required
  183. def get(self, provider, plugin_id):
  184. oauth_handler = OAuthHandler()
  185. plugin_oauth_config = db.session.query(DatasourceOauthParamConfig).filter_by(
  186. provider=provider,
  187. plugin_id=plugin_id
  188. ).first()
  189. if not plugin_oauth_config:
  190. raise NotFound()
  191. credentials = oauth_handler.get_credentials(
  192. current_user.current_tenant.id,
  193. current_user.id,
  194. plugin_id,
  195. provider,
  196. system_credentials=plugin_oauth_config.system_credentials,
  197. request=request
  198. )
  199. datasource_provider = DatasourceProvider(
  200. datasource_name=plugin_oauth_config.datasource_name,
  201. plugin_id=plugin_id,
  202. provider=provider,
  203. auth_type="oauth",
  204. encrypted_credentials=credentials
  205. )
  206. db.session.add(datasource_provider)
  207. db.session.commit()
  208. return redirect(f"{dify_config.CONSOLE_WEB_URL}")
  209. api.add_resource(OAuthLogin, "/oauth/login/<provider>")
  210. api.add_resource(OAuthCallback, "/oauth/authorize/<provider>")
  211. api.add_resource(PluginOauthApi, "/oauth/plugin/provider/<string:provider>/plugin/<string:plugin_id>")
  212. api.add_resource(PluginOauthCallback, "/oauth/plugin/callback/<string:provider>/plugin/<string:plugin_id>")