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.

2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
2 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 configs import dify_config
  8. from constants.languages import languages
  9. from extensions.ext_database import db
  10. from libs.helper import extract_remote_ip
  11. from libs.oauth import GitHubOAuth, GoogleOAuth, OAuthUserInfo
  12. from models import Account
  13. from models.account import AccountStatus
  14. from services.account_service import AccountService, RegisterService, TenantService
  15. from .. import api
  16. def get_oauth_providers():
  17. with current_app.app_context():
  18. if not dify_config.GITHUB_CLIENT_ID or not dify_config.GITHUB_CLIENT_SECRET:
  19. github_oauth = None
  20. else:
  21. github_oauth = GitHubOAuth(
  22. client_id=dify_config.GITHUB_CLIENT_ID,
  23. client_secret=dify_config.GITHUB_CLIENT_SECRET,
  24. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",
  25. )
  26. if not dify_config.GOOGLE_CLIENT_ID or not dify_config.GOOGLE_CLIENT_SECRET:
  27. google_oauth = None
  28. else:
  29. google_oauth = GoogleOAuth(
  30. client_id=dify_config.GOOGLE_CLIENT_ID,
  31. client_secret=dify_config.GOOGLE_CLIENT_SECRET,
  32. redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",
  33. )
  34. OAUTH_PROVIDERS = {"github": github_oauth, "google": google_oauth}
  35. return OAUTH_PROVIDERS
  36. class OAuthLogin(Resource):
  37. def get(self, provider: str):
  38. OAUTH_PROVIDERS = get_oauth_providers()
  39. with current_app.app_context():
  40. oauth_provider = OAUTH_PROVIDERS.get(provider)
  41. print(vars(oauth_provider))
  42. if not oauth_provider:
  43. return {"error": "Invalid provider"}, 400
  44. auth_url = oauth_provider.get_authorization_url()
  45. return redirect(auth_url)
  46. class OAuthCallback(Resource):
  47. def get(self, provider: str):
  48. OAUTH_PROVIDERS = get_oauth_providers()
  49. with current_app.app_context():
  50. oauth_provider = OAUTH_PROVIDERS.get(provider)
  51. if not oauth_provider:
  52. return {"error": "Invalid provider"}, 400
  53. code = request.args.get("code")
  54. try:
  55. token = oauth_provider.get_access_token(code)
  56. user_info = oauth_provider.get_user_info(token)
  57. except requests.exceptions.HTTPError as e:
  58. logging.exception(f"An error occurred during the OAuth process with {provider}: {e.response.text}")
  59. return {"error": "OAuth process failed"}, 400
  60. account = _generate_account(provider, user_info)
  61. # Check account status
  62. if account.status in {AccountStatus.BANNED.value, AccountStatus.CLOSED.value}:
  63. return {"error": "Account is banned or closed."}, 403
  64. if account.status == AccountStatus.PENDING.value:
  65. account.status = AccountStatus.ACTIVE.value
  66. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  67. db.session.commit()
  68. TenantService.create_owner_tenant_if_not_exist(account)
  69. token_pair = AccountService.login(
  70. account=account,
  71. ip_address=extract_remote_ip(request),
  72. )
  73. return redirect(
  74. f"{dify_config.CONSOLE_WEB_URL}?access_token={token_pair.access_token}&refresh_token={token_pair.refresh_token}"
  75. )
  76. def _get_account_by_openid_or_email(provider: str, user_info: OAuthUserInfo) -> Optional[Account]:
  77. account = Account.get_by_openid(provider, user_info.id)
  78. if not account:
  79. account = Account.query.filter_by(email=user_info.email).first()
  80. return account
  81. def _generate_account(provider: str, user_info: OAuthUserInfo):
  82. # Get account by openid or email.
  83. account = _get_account_by_openid_or_email(provider, user_info)
  84. if not account:
  85. # Create account
  86. account_name = user_info.name or "Dify"
  87. account = RegisterService.register(
  88. email=user_info.email, name=account_name, password=None, open_id=user_info.id, provider=provider
  89. )
  90. # Set interface language
  91. preferred_lang = request.accept_languages.best_match(languages)
  92. if preferred_lang and preferred_lang in languages:
  93. interface_language = preferred_lang
  94. else:
  95. interface_language = languages[0]
  96. account.interface_language = interface_language
  97. db.session.commit()
  98. # Link account
  99. AccountService.link_account_integrate(provider, user_info.id, account)
  100. return account
  101. api.add_resource(OAuthLogin, "/oauth/login/<provider>")
  102. api.add_resource(OAuthCallback, "/oauth/authorize/<provider>")