2022-08-14 00:54:22 +00:00
|
|
|
import click
|
2022-08-15 20:22:36 +00:00
|
|
|
from flask_security.changeable import admin_change_password
|
2022-08-14 00:54:22 +00:00
|
|
|
from sqlalchemy import select
|
|
|
|
|
|
|
|
from advlabdb import create_app
|
|
|
|
from advlabdb.model_independent_funs import randomPassword
|
|
|
|
from advlabdb.models import Admin, User, db
|
|
|
|
|
|
|
|
|
|
|
|
def _reset_admin_password(manage):
|
|
|
|
click.echo("This script will generate a new random password for a chosen admin.\n")
|
|
|
|
|
|
|
|
app = create_app(create_for_server=False)
|
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
with app.app_context(), db.session.begin():
|
|
|
|
admins = db.session.scalars(select(Admin).join(User).where(User.active is True)).all()
|
|
|
|
activate_user = False
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
if len(admins) == 0:
|
|
|
|
click.echo("There is no admin with an active user. The user of the chosen admin will be activated.")
|
|
|
|
admins = db.session.scalars(select(Admin)).all()
|
|
|
|
activate_user = True
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
num_admins = len(admins)
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
prompt = "Admins:\n"
|
|
|
|
for ind, admin in enumerate(admins):
|
|
|
|
user = admin.user
|
|
|
|
prompt += f"[{ind}] {user.first_name} {user.last_name}: {user.email}\n"
|
|
|
|
prompt += f"Enter number [0-{num_admins - 1}]"
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
admin_index = click.prompt(
|
|
|
|
prompt,
|
|
|
|
type=click.IntRange(0, num_admins - 1),
|
|
|
|
)
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
chosen_admin_user = admins[admin_index].user
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
new_password = randomPassword()
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
admin_change_password(
|
|
|
|
chosen_admin_user, new_password, notify=False
|
|
|
|
) # Password is automatically hashed with this function
|
2022-08-14 00:54:22 +00:00
|
|
|
|
2023-11-02 18:38:09 +00:00
|
|
|
if activate_user:
|
|
|
|
chosen_admin_user.active = True
|
2022-08-14 00:54:22 +00:00
|
|
|
|
|
|
|
manage.box(f"New password: {new_password}")
|
|
|
|
|
|
|
|
click.echo(click.style("Done!", fg="green"))
|