1
0
Fork 0
mirror of https://codeberg.org/Mo8it/AdvLabDB.git synced 2024-11-08 21:21:06 +00:00
AdvLabDB/cli/maintain/reset_admin_password/main.py
2023-11-02 19:38:09 +01:00

50 lines
1.6 KiB
Python

import click
from flask_security.changeable import admin_change_password
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)
with app.app_context(), db.session.begin():
admins = db.session.scalars(select(Admin).join(User).where(User.active is True)).all()
activate_user = False
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
num_admins = len(admins)
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}]"
admin_index = click.prompt(
prompt,
type=click.IntRange(0, num_admins - 1),
)
chosen_admin_user = admins[admin_index].user
new_password = randomPassword()
admin_change_password(
chosen_admin_user, new_password, notify=False
) # Password is automatically hashed with this function
if activate_user:
chosen_admin_user.active = True
manage.box(f"New password: {new_password}")
click.echo(click.style("Done!", fg="green"))