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 9.9KB

2 years ago
2 years ago
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
8 months ago
5 months ago
5 months ago
5 months ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
8 months ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
5 months ago
5 months ago
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>")