commands.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import datetime
  2. import logging
  3. import random
  4. import string
  5. import click
  6. from flask import current_app
  7. from werkzeug.exceptions import NotFound
  8. from core.index.index import IndexBuilder
  9. from libs.password import password_pattern, valid_password, hash_password
  10. from libs.helper import email as email_validate
  11. from extensions.ext_database import db
  12. from libs.rsa import generate_key_pair
  13. from models.account import InvitationCode, Tenant
  14. from models.dataset import Dataset
  15. from models.model import Account
  16. import secrets
  17. import base64
  18. from models.provider import Provider
  19. @click.command('reset-password', help='Reset the account password.')
  20. @click.option('--email', prompt=True, help='The email address of the account whose password you need to reset')
  21. @click.option('--new-password', prompt=True, help='the new password.')
  22. @click.option('--password-confirm', prompt=True, help='the new password confirm.')
  23. def reset_password(email, new_password, password_confirm):
  24. if str(new_password).strip() != str(password_confirm).strip():
  25. click.echo(click.style('sorry. The two passwords do not match.', fg='red'))
  26. return
  27. account = db.session.query(Account). \
  28. filter(Account.email == email). \
  29. one_or_none()
  30. if not account:
  31. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  32. return
  33. try:
  34. valid_password(new_password)
  35. except:
  36. click.echo(
  37. click.style('sorry. The passwords must match {} '.format(password_pattern), fg='red'))
  38. return
  39. # generate password salt
  40. salt = secrets.token_bytes(16)
  41. base64_salt = base64.b64encode(salt).decode()
  42. # encrypt password with salt
  43. password_hashed = hash_password(new_password, salt)
  44. base64_password_hashed = base64.b64encode(password_hashed).decode()
  45. account.password = base64_password_hashed
  46. account.password_salt = base64_salt
  47. db.session.commit()
  48. click.echo(click.style('Congratulations!, password has been reset.', fg='green'))
  49. @click.command('reset-email', help='Reset the account email.')
  50. @click.option('--email', prompt=True, help='The old email address of the account whose email you need to reset')
  51. @click.option('--new-email', prompt=True, help='the new email.')
  52. @click.option('--email-confirm', prompt=True, help='the new email confirm.')
  53. def reset_email(email, new_email, email_confirm):
  54. if str(new_email).strip() != str(email_confirm).strip():
  55. click.echo(click.style('Sorry, new email and confirm email do not match.', fg='red'))
  56. return
  57. account = db.session.query(Account). \
  58. filter(Account.email == email). \
  59. one_or_none()
  60. if not account:
  61. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  62. return
  63. try:
  64. email_validate(new_email)
  65. except:
  66. click.echo(
  67. click.style('sorry. {} is not a valid email. '.format(email), fg='red'))
  68. return
  69. account.email = new_email
  70. db.session.commit()
  71. click.echo(click.style('Congratulations!, email has been reset.', fg='green'))
  72. @click.command('reset-encrypt-key-pair', help='Reset the asymmetric key pair of workspace for encrypt LLM credentials. '
  73. 'After the reset, all LLM credentials will become invalid, '
  74. 'requiring re-entry.'
  75. 'Only support SELF_HOSTED mode.')
  76. @click.confirmation_option(prompt=click.style('Are you sure you want to reset encrypt key pair?'
  77. ' this operation cannot be rolled back!', fg='red'))
  78. def reset_encrypt_key_pair():
  79. if current_app.config['EDITION'] != 'SELF_HOSTED':
  80. click.echo(click.style('Sorry, only support SELF_HOSTED mode.', fg='red'))
  81. return
  82. tenant = db.session.query(Tenant).first()
  83. if not tenant:
  84. click.echo(click.style('Sorry, no workspace found. Please enter /install to initialize.', fg='red'))
  85. return
  86. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  87. db.session.query(Provider).filter(Provider.provider_type == 'custom').delete()
  88. db.session.commit()
  89. click.echo(click.style('Congratulations! '
  90. 'the asymmetric key pair of workspace {} has been reset.'.format(tenant.id), fg='green'))
  91. @click.command('generate-invitation-codes', help='Generate invitation codes.')
  92. @click.option('--batch', help='The batch of invitation codes.')
  93. @click.option('--count', prompt=True, help='Invitation codes count.')
  94. def generate_invitation_codes(batch, count):
  95. if not batch:
  96. now = datetime.datetime.now()
  97. batch = now.strftime('%Y%m%d%H%M%S')
  98. if not count or int(count) <= 0:
  99. click.echo(click.style('sorry. the count must be greater than 0.', fg='red'))
  100. return
  101. count = int(count)
  102. click.echo('Start generate {} invitation codes for batch {}.'.format(count, batch))
  103. codes = ''
  104. for i in range(count):
  105. code = generate_invitation_code()
  106. invitation_code = InvitationCode(
  107. code=code,
  108. batch=batch
  109. )
  110. db.session.add(invitation_code)
  111. click.echo(code)
  112. codes += code + "\n"
  113. db.session.commit()
  114. filename = 'storage/invitation-codes-{}.txt'.format(batch)
  115. with open(filename, 'w') as f:
  116. f.write(codes)
  117. click.echo(click.style(
  118. 'Congratulations! Generated {} invitation codes for batch {} and saved to the file \'{}\''.format(count, batch,
  119. filename),
  120. fg='green'))
  121. def generate_invitation_code():
  122. code = generate_upper_string()
  123. while db.session.query(InvitationCode).filter(InvitationCode.code == code).count() > 0:
  124. code = generate_upper_string()
  125. return code
  126. def generate_upper_string():
  127. letters_digits = string.ascii_uppercase + string.digits
  128. result = ""
  129. for i in range(8):
  130. result += random.choice(letters_digits)
  131. return result
  132. @click.command('recreate-all-dataset-indexes', help='Recreate all dataset indexes.')
  133. def recreate_all_dataset_indexes():
  134. click.echo(click.style('Start recreate all dataset indexes.', fg='green'))
  135. recreate_count = 0
  136. page = 1
  137. while True:
  138. try:
  139. datasets = db.session.query(Dataset).filter(Dataset.indexing_technique == 'high_quality')\
  140. .order_by(Dataset.created_at.desc()).paginate(page=page, per_page=50)
  141. except NotFound:
  142. break
  143. page += 1
  144. for dataset in datasets:
  145. try:
  146. click.echo('Recreating dataset index: {}'.format(dataset.id))
  147. index = IndexBuilder.get_index(dataset, 'high_quality')
  148. if index and index._is_origin():
  149. index.recreate_dataset(dataset)
  150. recreate_count += 1
  151. else:
  152. click.echo('passed.')
  153. except Exception as e:
  154. click.echo(click.style('Recreate dataset index error: {} {}'.format(e.__class__.__name__, str(e)), fg='red'))
  155. continue
  156. click.echo(click.style('Congratulations! Recreate {} dataset indexes.'.format(recreate_count), fg='green'))
  157. def register_commands(app):
  158. app.cli.add_command(reset_password)
  159. app.cli.add_command(reset_email)
  160. app.cli.add_command(generate_invitation_codes)
  161. app.cli.add_command(reset_encrypt_key_pair)
  162. app.cli.add_command(recreate_all_dataset_indexes)