setup.py 2.4 KB

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