MonScoDocEssai/app/scodoc/sco_import_users.py

313 lines
10 KiB
Python
Raw Normal View History

2020-09-26 16:19:37 +02:00
# -*- mode: python -*-
# -*- coding: utf-8 -*-
##############################################################################
#
# Gestion scolarite IUT
#
2021-01-01 17:51:08 +01:00
# Copyright (c) 1999 - 2021 Emmanuel Viennet. All rights reserved.
2020-09-26 16:19:37 +02:00
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Emmanuel Viennet emmanuel.viennet@viennet.net
#
##############################################################################
"""Import d'utilisateurs via fichier Excel
"""
2021-07-19 19:53:01 +02:00
import random, time
2021-08-22 13:24:36 +02:00
import re
2021-07-19 19:53:01 +02:00
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
2020-09-26 16:19:37 +02:00
2021-08-22 13:24:36 +02:00
from app import db, Departement
2021-06-21 10:17:16 +02:00
from app.scodoc import sco_emails
import app.scodoc.sco_utils as scu
from app.scodoc.notes_log import log
from app.scodoc.sco_exceptions import AccessDenied, ScoValueError, ScoException
from app.scodoc import sco_excel
from app.scodoc import sco_preferences
2021-07-03 16:19:42 +02:00
from app.scodoc import sco_users
2020-09-26 16:19:37 +02:00
2021-08-22 13:24:36 +02:00
from flask import g
from flask_login import current_user
from app.auth.models import User, UserRole
2020-09-26 16:19:37 +02:00
TITLES = ("user_name", "nom", "prenom", "email", "roles", "dept")
2021-08-22 13:24:36 +02:00
COMMENTS = (
"""user_name:
Composé de lettres (minuscules ou majuscules), de chiffres ou du caractère _
""",
"""nom:
Maximum 64 caractères""",
"""prenom:
Maximum 64 caractères""",
"""email:
Maximum 120 caractères""",
"""roles:
un plusieurs rôles séparés par ','
chaque role est fait de 2 composantes séparées par _:
1. Le role (Ens, Secr ou Admin)
2. Le département (en majuscule)
Exemple: "Ens_RT,Admin_INFO"
""",
"""dept:
Le département d'appartenance du l'utillsateur. Laisser vide si l'utilisateur intervient dans plusieurs dépatements
""",
)
2020-09-26 16:19:37 +02:00
def generate_excel_sample():
2020-12-15 08:48:29 +01:00
"""generates an excel document suitable to import users"""
2021-08-12 14:55:25 +02:00
style = sco_excel.excel_make_style(bold=True)
2020-09-26 16:19:37 +02:00
titles = TITLES
2021-08-22 13:24:36 +02:00
titles_styles = [style] * len(titles)
2021-08-12 14:49:53 +02:00
return sco_excel.excel_simple_table(
2021-08-22 13:24:36 +02:00
titles=titles,
titles_styles=titles_styles,
sheet_name="Utilisateurs ScoDoc",
comments=COMMENTS,
2020-09-26 16:19:37 +02:00
)
2021-08-22 13:24:36 +02:00
def import_excel_file(datafile):
2020-09-26 16:19:37 +02:00
"Create users from Excel file"
2021-08-22 13:24:36 +02:00
# Check current user privilege
auth_dept = current_user.dept
auth_name = str(current_user)
if not current_user.is_administrator():
raise AccessDenied("invalid user (%s) must be SuperAdmin" % auth_name)
# Récupération des informations sur l'utilisateur courant
2020-09-26 16:19:37 +02:00
log("sco_import_users.import_excel_file by %s" % auth_name)
exceldata = datafile.read()
if not exceldata:
raise ScoValueError("Ficher excel vide ou invalide")
2021-08-22 13:24:36 +02:00
_, data = sco_excel.excel_bytes_to_list(exceldata)
2020-09-26 16:19:37 +02:00
if not data: # probably a bug
raise ScoException("import_excel_file: empty file !")
# 1- --- check title line
fs = [scu.stripquotes(s).lower() for s in data[0]]
2020-09-26 16:19:37 +02:00
log("excel: fs='%s'\ndata=%s" % (str(fs), str(data)))
# check cols
cols = {}.fromkeys(TITLES)
unknown = []
for tit in fs:
2021-07-09 17:47:06 +02:00
if tit not in cols:
2020-09-26 16:19:37 +02:00
unknown.append(tit)
else:
del cols[tit]
if cols or unknown:
raise ScoValueError(
"colonnes incorrectes (on attend %d, et non %d) <br/> (colonnes manquantes: %s, colonnes invalides: %s)"
2021-07-09 17:47:06 +02:00
% (len(TITLES), len(fs), list(cols.keys()), unknown)
2020-09-26 16:19:37 +02:00
)
# ok, same titles...
U = []
for line in data[1:]:
d = {}
for i in range(len(fs)):
d[fs[i]] = line[i]
U.append(d)
2021-08-22 13:24:36 +02:00
return import_users(U, auth_dept=auth_dept)
2020-09-26 16:19:37 +02:00
2021-08-22 13:24:36 +02:00
def import_users(users, auth_dept=""):
2020-09-26 16:19:37 +02:00
"""Import des utilisateurs:
Pour chaque utilisateur à créer:
- vérifier données
- générer mot de passe aléatoire
- créer utilisateur et mettre le mot de passe
- envoyer mot de passe par mail
2020-12-15 08:48:29 +01:00
En cas d'erreur: supprimer tous les utilisateurs que l'on vient de créer.
2020-09-26 16:19:37 +02:00
"""
2021-08-22 13:24:36 +02:00
def append_msg(msg):
msg_list.append("Ligne %s : %s" % (line, msg))
if len(users) == 0:
import_ok = False
msg_list = ["Feuilles vide ou illisible"]
else:
created = [] # liste de uid créés
msg_list = []
line = 1 # satr from excel line #2
import_ok = True
try:
for u in users:
user_ok = True
line = line + 1
user_ok, msg = sco_users.check_modif_user(
0,
user_name=u["user_name"],
nom=u["nom"],
prenom=u["prenom"],
email=u["email"],
roles=u["roles"].split(","),
2021-08-22 13:24:36 +02:00
)
if not user_ok:
append_msg("identifiant '%s' %s" % (u["user_name"], msg))
# raise ScoValueError(
# "données invalides pour %s: %s" % (u["user_name"], msg)
# )
u["passwd"] = generate_password()
#
# check identifiant
if not re.match(r"^[a-zA-Z0-9@\\\-_\\\.]*$", u["user_name"]):
user_ok = False
append_msg(
"identifiant '%s' invalide (pas d'accents ni de caractères spéciaux)"
% u["user_name"]
)
elif len(u["user_name"]) > 64:
user_ok = False
append_msg(
"identifiant '%s' trop long (64 caractères)" % u["user_name"]
)
if len(u["nom"]) > 64:
user_ok = False
append_msg("nom '%s' trop long (64 caractères)" % u["nom"])
if len(u["prenom"]) > 64:
user_ok = False
append_msg("prenom '%s' trop long (64 caractères)" % u["prenom"])
if len(u["email"]) > 120:
user_ok = False
append_msg("email '%s' trop long (120 caractères)" % u["email"])
# check département
if u["dept"] != "":
dept = Departement.query.filter_by(acronym=u["dept"]).first()
if dept is None:
user_ok = False
append_msg("département '%s' inexistant" % u["dept"])
for role in u["roles"].split(","):
try:
_, _ = UserRole.role_dept_from_string(role)
except ScoValueError as value_error:
user_ok = False
append_msg("role : %s " % role)
# Création de l'utilisateur (via SQLAlchemy)
if user_ok:
created.append(u)
else:
import_ok = False
except ScoValueError as value_error:
log("import_users: exception: abort create %s" % str(created))
raise ScoValueError(msg) # re-raise exception
if import_ok:
for u in created:
u["roles_string"] = u["roles"]
user = User()
user.from_dict(u, new_user=True)
db.session.add(user)
db.session.commit()
mail_password(u)
else:
created = [] # reset # of created users to 0
return import_ok, msg_list, len(created)
2020-09-26 16:19:37 +02:00
# --------- Génération du mot de passe initial -----------
# Adapté de http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440564
# Alphabet tres simple pour des mots de passe simples...
ALPHABET = r"""ABCDEFGHIJKLMNPQRSTUVWXYZ123456789123456789AEIOU"""
PASSLEN = 6
RNG = random.Random(time.time())
def generate_password():
"""This function creates a pseudo random number generator object, seeded with
the cryptographic hash of the passString. The contents of the character set
is then shuffled and a selection of passLength words is made from this list.
This selection is returned as the generated password."""
l = list(ALPHABET) # make this mutable so that we can shuffle the characters
RNG.shuffle(l) # shuffle the character set
# pick up only a subset from the available characters:
return "".join(RNG.sample(l, PASSLEN))
def mail_password(u, context=None, reset=False):
"Send password by email"
if not u["email"]:
return
2021-08-22 13:24:36 +02:00
u[
"url"
] = (
scu.ScoURL()
) # TODO set auth page URL ? (shared by all departments) ../auth/login
2020-09-26 16:19:37 +02:00
txt = (
"""
Bonjour %(prenom)s %(nom)s,
"""
% u
)
if reset:
txt += (
"""
votre mot de passe ScoDoc a été -initialisé.
Le nouveau mot de passe est: %(passwd)s
Votre nom d'utilisateur est %(user_name)s
Vous devrez changer ce mot de passe lors de votre première connexion
sur %(url)s
"""
% u
)
else:
txt += (
"""
vous avez été déclaré comme utilisateur du logiciel de gestion de scolarité ScoDoc.
Votre nom d'utilisateur est %(user_name)s
Votre mot de passe est: %(passwd)s
Le logiciel est accessible sur: %(url)s
Vous êtes invité à changer ce mot de passe au plus vite (cliquez sur
votre nom en haut à gauche de la page d'accueil).
"""
% u
)
txt += (
"""
ScoDoc est un logiciel libre développé à l'Université Paris 13 par Emmanuel Viennet.
Pour plus d'informations sur ce logiciel, voir %s
"""
2021-02-04 20:02:44 +01:00
% scu.SCO_WEBSITE
2020-09-26 16:19:37 +02:00
)
msg = MIMEMultipart()
if reset:
2021-02-04 20:02:44 +01:00
msg["Subject"] = Header("Mot de passe ScoDoc", scu.SCO_ENCODING)
2020-09-26 16:19:37 +02:00
else:
2021-02-04 20:02:44 +01:00
msg["Subject"] = Header("Votre accès ScoDoc", scu.SCO_ENCODING)
msg["From"] = sco_preferences.get_preference("email_from_addr")
2020-09-26 16:19:37 +02:00
msg["To"] = u["email"]
msg.epilogue = ""
2021-02-04 20:02:44 +01:00
txt = MIMEText(txt, "plain", scu.SCO_ENCODING)
2020-09-26 16:19:37 +02:00
msg.attach(txt)
2021-08-22 13:24:36 +02:00
# sco_emails.sendEmail(msg) # TODO ScoDoc9 pending function