setup.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. setup()
  50. AccountService.update_last_login(account, request)
  51. return {'result': 'success'}, 201
  52. def setup():
  53. dify_setup = DifySetup(
  54. version=current_app.config['CURRENT_VERSION']
  55. )
  56. db.session.add(dify_setup)
  57. def setup_required(view):
  58. @wraps(view)
  59. def decorated(*args, **kwargs):
  60. # check setup
  61. if not get_init_validate_status():
  62. raise NotInitValidateError()
  63. elif not get_setup_status():
  64. raise NotSetupError()
  65. return view(*args, **kwargs)
  66. return decorated
  67. def get_setup_status():
  68. if current_app.config['EDITION'] == 'SELF_HOSTED':
  69. return DifySetup.query.first()
  70. else:
  71. return True
  72. api.add_resource(SetupApi, '/setup')