setup.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from functools import wraps
  2. from flask import request
  3. from flask_restful import Resource, reqparse
  4. from configs import dify_config
  5. from libs.helper import StrLen, email, extract_remote_ip
  6. from libs.password import valid_password
  7. from models.model import DifySetup
  8. from services.account_service import RegisterService, TenantService
  9. from . import api
  10. from .error import AlreadySetupError, NotInitValidateError, NotSetupError
  11. from .init_validate import get_init_validate_status
  12. from .wraps import only_edition_self_hosted
  13. class SetupApi(Resource):
  14. def get(self):
  15. if dify_config.EDITION == "SELF_HOSTED":
  16. setup_status = get_setup_status()
  17. if setup_status:
  18. return {"step": "finished", "setup_at": setup_status.setup_at.isoformat()}
  19. return {"step": "not_started"}
  20. return {"step": "finished"}
  21. @only_edition_self_hosted
  22. def post(self):
  23. # is set up
  24. if get_setup_status():
  25. raise AlreadySetupError()
  26. # is tenant created
  27. tenant_count = TenantService.get_tenant_count()
  28. if tenant_count > 0:
  29. raise AlreadySetupError()
  30. if not get_init_validate_status():
  31. raise NotInitValidateError()
  32. parser = reqparse.RequestParser()
  33. parser.add_argument("email", type=email, required=True, location="json")
  34. parser.add_argument("name", type=StrLen(30), required=True, location="json")
  35. parser.add_argument("password", type=valid_password, required=True, location="json")
  36. args = parser.parse_args()
  37. # setup
  38. RegisterService.setup(
  39. email=args["email"], name=args["name"], password=args["password"], ip_address=extract_remote_ip(request)
  40. )
  41. return {"result": "success"}, 201
  42. def setup_required(view):
  43. @wraps(view)
  44. def decorated(*args, **kwargs):
  45. # check setup
  46. if not get_init_validate_status():
  47. raise NotInitValidateError()
  48. elif not get_setup_status():
  49. raise NotSetupError()
  50. return view(*args, **kwargs)
  51. return decorated
  52. def get_setup_status():
  53. if dify_config.EDITION == "SELF_HOSTED":
  54. return DifySetup.query.first()
  55. else:
  56. return True
  57. api.add_resource(SetupApi, "/setup")