ScoDoc/scodoc.py

120 lines
2.9 KiB
Python
Raw Normal View History

2021-05-29 18:22:51 +02:00
# -*- coding: UTF-8 -*
"""Application Flask: ScoDoc
"""
from __future__ import print_function
from pprint import pprint as pp
import sys
2021-05-29 18:22:51 +02:00
import click
import flask
from app import create_app, cli, db
from app.auth.models import User, Role, UserRole
from config import Config
app = create_app()
cli.register(app)
@app.shell_context_processor
def make_shell_context():
return {
"db": db,
"User": User,
"Role": Role,
"UserRole": UserRole,
"pp": pp,
"flask": flask,
"current_app": flask.current_app,
}
@app.cli.command()
def user_db_init():
2021-05-29 18:22:51 +02:00
"""Initialize the users database."""
click.echo("Init the db")
# Create roles:
Role.insert_roles()
click.echo("created initial roles")
# Ensure that admin exists
if Config.SCODOC_ADMIN_MAIL:
admin_username = Config.SCODOC_ADMIN_LOGIN
user = User.query.filter_by(username=admin_username).first()
if not user:
user = User(username=admin_username, email=Config.SCODOC_ADMIN_MAIL)
db.session.add(user)
db.session.commit()
click.echo(
"created initial admin user, login: {u.username}, email: {u.email}".format(
u=user
)
)
@app.cli.command()
def user_db_clear():
2021-05-29 18:22:51 +02:00
"""Erase (drop) all tables of users database !"""
click.echo("Erasing the users database !")
_clear_users_db()
2021-05-29 18:22:51 +02:00
def _clear_users_db():
2021-05-29 18:22:51 +02:00
"""Erase (drop) all tables of users database !"""
click.confirm("This will erase all users.\nDo you want to continue?", abort=True)
2021-05-29 18:22:51 +02:00
db.reflect()
db.drop_all()
db.session.commit()
@app.cli.command()
@click.argument("username")
@click.argument("role")
@click.argument("dept")
def user_create(username, role, dept):
"Create a new user"
r = Role.get_named_role(role)
if not r:
sys.stderr.write("user_create: role {r} does not exists".format(r=r))
return 1
u = User.query.filter_by(username=username).first()
if u:
sys.stderr.write("user_create: user {u} already exists".format(u=u))
return 2
u = User(username=username)
u.add_role(r, dept)
db.session.add(u)
db.session.commit()
click.echo(
"created user, login: {u.username}, with role {r} in dept. {dept}".format(
u=u, r=r, dept=dept
)
)
@app.cli.command()
@click.argument("username")
@click.password_option()
def user_password(username, password=None):
"Set (or change) user's password"
if not password:
sys.stderr.write("user_password: missing password")
return 1
u = User.query.filter_by(username=username).first()
if not u:
sys.stderr.write("user_password: user {} does not exists".format(username))
return 1
u.set_password(password)
db.session.add(u)
db.session.commit()
click.echo("changed password for user {}".format(u))