Fixes #293 : suppression utilisateur

This commit is contained in:
Emmanuel Viennet 2022-02-13 15:19:39 +01:00
parent 42511ba04c
commit 3cafbf5988
2 changed files with 28 additions and 8 deletions

View File

@ -76,7 +76,9 @@ class User(UserMixin, db.Model):
"Departement",
foreign_keys=[Departement.acronym],
primaryjoin=(dept == Departement.acronym),
lazy="dynamic",
lazy="select",
passive_deletes="all",
uselist=False,
)
def __init__(self, **kwargs):
@ -236,7 +238,7 @@ class User(UserMixin, db.Model):
def get_dept_id(self) -> int:
"returns user's department id, or None"
if self.dept:
return self._departement.first().id
return self._departement.id
return None
# Permissions management:

View File

@ -14,6 +14,8 @@ import click
import flask
from flask.cli import with_appcontext
from flask.templating import render_template
import psycopg2
import sqlalchemy
from app import create_app, cli, db
from app import initialize_scodoc_database
@ -133,11 +135,11 @@ def user_create(username, role, dept, nom=None, prenom=None): # user-create
"Create a new user"
r = Role.get_named_role(role)
if not r:
sys.stderr.write("user_create: role {r} does not exist\n".format(r=role))
sys.stderr.write(f"user_create: role {role} does not exist\n")
return 1
u = User.query.filter_by(user_name=username).first()
if u:
sys.stderr.write("user_create: user {u} already exists\n".format(u=u))
sys.stderr.write(f"user_create: user {u} already exists\n")
return 2
if dept == "@all":
dept = None
@ -145,11 +147,26 @@ def user_create(username, role, dept, nom=None, prenom=None): # user-create
u.add_role(r, dept)
db.session.add(u)
db.session.commit()
click.echo(
"created user, login: {u.user_name}, with role {r} in dept. {dept}".format(
u=u, r=r, dept=dept
click.echo(f"created user, login: {u.user_name}, with role {r} in dept. {dept}")
@app.cli.command()
@click.argument("username")
def user_delete(username): # user-delete
"Try to delete this user. Fails if it's associated to some scodoc objects."
u = User.query.filter_by(user_name=username).first()
if not u:
sys.stderr.write(f"user_delete: user {username} not found\n")
return 2
db.session.delete(u)
try:
db.session.commit()
except (sqlalchemy.exc.IntegrityError, psycopg2.errors.ForeignKeyViolation):
sys.stderr.write(
f"""\nuser_delete: ne peux pas supprimer l'utilisateur {username}\ncar il est associé à des objets dans ScoDoc (modules, notes, ...).\n"""
)
)
return 1
click.echo(f"deleted user, login: {username}")
@app.cli.command()
@ -485,6 +502,7 @@ def recursive_help(cmd, parent=None):
@app.cli.command()
def dumphelp():
"""Génère la page d'aide complète pour la doc."""
recursive_help(app.cli)