setup.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # -*- coding:utf-8 -*-
  2. from functools import wraps
  3. from flask import current_app, request
  4. from flask_restful import Resource, reqparse
  5. from extensions.ext_database import db
  6. from libs.helper import email, str_len
  7. from libs.password import valid_password
  8. from models.model import DifySetup
  9. from services.account_service import AccountService, RegisterService, TenantService
  10. from . import api
  11. from .error import AlreadySetupError, NotInitValidateError, NotSetupError
  12. from .init_validate import get_init_validate_status
  13. from .wraps import only_edition_self_hosted
  14. class SetupApi(Resource):
  15. def get(self):
  16. if current_app.config['EDITION'] == 'SELF_HOSTED':
  17. setup_status = get_setup_status()
  18. if setup_status:
  19. return {
  20. 'step': 'finished',
  21. 'setup_at': setup_status.setup_at.isoformat()
  22. }
  23. return {'step': 'not_started'}
  24. return {'step': 'finished'}
  25. @only_edition_self_hosted
  26. def post(self):
  27. # is set up
  28. if get_setup_status():
  29. raise AlreadySetupError()
  30. # is tenant created
  31. tenant_count = TenantService.get_tenant_count()
  32. if tenant_count > 0:
  33. raise AlreadySetupError()
  34. if not get_init_validate_status():
  35. raise NotInitValidateError()
  36. parser = reqparse.RequestParser()
  37. parser.add_argument('email', type=email,
  38. required=True, location='json')
  39. parser.add_argument('name', type=str_len(
  40. 30), required=True, location='json')
  41. parser.add_argument('password', type=valid_password,
  42. required=True, location='json')
  43. args = parser.parse_args()
  44. # Register
  45. account = RegisterService.register(
  46. email=args['email'],
  47. name=args['name'],
  48. password=args['password']
  49. )
  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')