setup.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 email, get_remote_ip, str_len
  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 {
  19. 'step': 'finished',
  20. 'setup_at': setup_status.setup_at.isoformat()
  21. }
  22. return {'step': 'not_started'}
  23. return {'step': 'finished'}
  24. @only_edition_self_hosted
  25. def post(self):
  26. # is set up
  27. if get_setup_status():
  28. raise AlreadySetupError()
  29. # is tenant created
  30. tenant_count = TenantService.get_tenant_count()
  31. if tenant_count > 0:
  32. raise AlreadySetupError()
  33. if not get_init_validate_status():
  34. raise NotInitValidateError()
  35. parser = reqparse.RequestParser()
  36. parser.add_argument('email', type=email,
  37. required=True, location='json')
  38. parser.add_argument('name', type=str_len(
  39. 30), required=True, location='json')
  40. parser.add_argument('password', type=valid_password,
  41. required=True, location='json')
  42. args = parser.parse_args()
  43. # setup
  44. RegisterService.setup(
  45. email=args['email'],
  46. name=args['name'],
  47. password=args['password'],
  48. ip_address=get_remote_ip(request)
  49. )
  50. return {'result': 'success'}, 201
  51. def setup_required(view):
  52. @wraps(view)
  53. def decorated(*args, **kwargs):
  54. # check setup
  55. if not get_init_validate_status():
  56. raise NotInitValidateError()
  57. elif not get_setup_status():
  58. raise NotSetupError()
  59. return view(*args, **kwargs)
  60. return decorated
  61. def get_setup_status():
  62. if dify_config.EDITION == 'SELF_HOSTED':
  63. return DifySetup.query.first()
  64. else:
  65. return True
  66. api.add_resource(SetupApi, '/setup')