setup.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from functools import wraps
  2. from flask import current_app, request
  3. from flask_restful import Resource, reqparse
  4. from extensions.ext_database import db
  5. from libs.helper import email, str_len
  6. from libs.password import valid_password
  7. from models.model import DifySetup
  8. from services.account_service import AccountService, 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 current_app.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. # Register
  44. account = RegisterService.register(
  45. email=args['email'],
  46. name=args['name'],
  47. password=args['password']
  48. )
  49. TenantService.create_owner_tenant_if_not_exist(account)
  50. setup()
  51. AccountService.update_last_login(account, request)
  52. return {'result': 'success'}, 201
  53. def setup():
  54. dify_setup = DifySetup(
  55. version=current_app.config['CURRENT_VERSION']
  56. )
  57. db.session.add(dify_setup)
  58. def setup_required(view):
  59. @wraps(view)
  60. def decorated(*args, **kwargs):
  61. # check setup
  62. if not get_init_validate_status():
  63. raise NotInitValidateError()
  64. elif not get_setup_status():
  65. raise NotSetupError()
  66. return view(*args, **kwargs)
  67. return decorated
  68. def get_setup_status():
  69. if current_app.config['EDITION'] == 'SELF_HOSTED':
  70. return DifySetup.query.first()
  71. else:
  72. return True
  73. api.add_resource(SetupApi, '/setup')