setup.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. 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_start'}
  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. 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. # Register
  43. account = RegisterService.register(
  44. email=args['email'],
  45. name=args['name'],
  46. password=args['password']
  47. )
  48. setup()
  49. # Login
  50. flask_login.login_user(account)
  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_setup_status():
  63. raise NotSetupError()
  64. return view(*args, **kwargs)
  65. return decorated
  66. def get_setup_status():
  67. if current_app.config['EDITION'] == 'SELF_HOSTED':
  68. return DifySetup.query.first()
  69. else:
  70. return True
  71. api.add_resource(SetupApi, '/setup')