setup.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # -*- coding:utf-8 -*-
  2. from functools import wraps
  3. import flask_login
  4. from flask import request, current_app
  5. from flask_restful import Resource, reqparse
  6. from extensions.ext_database import db
  7. from models.model import DifySetup
  8. from services.account_service import AccountService, TenantService, RegisterService
  9. from libs.helper import email, str_len
  10. from libs.password import valid_password
  11. from . import api
  12. from .error import AlreadySetupError, NotSetupError
  13. from .wraps import only_edition_self_hosted
  14. class SetupApi(Resource):
  15. @only_edition_self_hosted
  16. def get(self):
  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_start'}
  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. parser = reqparse.RequestParser()
  34. parser.add_argument('email', type=email,
  35. required=True, location='json')
  36. parser.add_argument('name', type=str_len(
  37. 30), required=True, location='json')
  38. parser.add_argument('password', type=valid_password,
  39. required=True, location='json')
  40. args = parser.parse_args()
  41. # Register
  42. account = RegisterService.register(
  43. email=args['email'],
  44. name=args['name'],
  45. password=args['password']
  46. )
  47. setup()
  48. # Login
  49. flask_login.login_user(account)
  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_setup_status():
  62. raise NotSetupError()
  63. return view(*args, **kwargs)
  64. return decorated
  65. def get_setup_status():
  66. if current_app.config['EDITION'] == 'SELF_HOSTED':
  67. return DifySetup.query.first()
  68. else:
  69. return True
  70. api.add_resource(SetupApi, '/setup')