diff --git a/app/auth/models.py b/app/auth/models.py index 18709de04..e8e1be50b 100644 --- a/app/auth/models.py +++ b/app/auth/models.py @@ -22,6 +22,7 @@ import jwt from app import db, log, login from app.models import Departement from app.models import SHORT_STR_LEN +from app.models.config import ScoDocSiteConfig from app.scodoc.sco_exceptions import ScoValueError from app.scodoc.sco_permissions import Permission from app.scodoc.sco_roles_default import SCO_ROLES_DEFAULTS @@ -71,9 +72,8 @@ class User(UserMixin, db.Model): cas_allow_scodoc_login = db.Column( db.Boolean, default=False, server_default="false", nullable=False ) - """(not yet implemented XXX) - si CAS activé, peut-on se logguer sur ScoDoc directement ? - (le rôle ScoSuperAdmin peut toujours) + """Si CAS forcé (cas_force), peut-on se logguer sur ScoDoc directement ? + (le rôle ScoSuperAdmin peut toujours, mettre à True pour les utilisateur API) """ password_hash = db.Column(db.String(128)) @@ -133,28 +133,37 @@ class User(UserMixin, db.Model): self.password_hash = None self.passwd_temp = False - def check_password(self, password): + def check_password(self, password: str) -> bool: """Check given password vs current one. Returns `True` if the password matched, `False` otherwise. """ if not self.active: # inactived users can't login return False - if (not self.password_hash) and self.password_scodoc7: - # Special case: user freshly migrated from ScoDoc7 - if scu.check_scodoc7_password(self.password_scodoc7, password): - current_app.logger.warning( - f"migrating legacy ScoDoc7 password for {self}" - ) - self.set_password(password) - self.password_scodoc7 = None - db.session.add(self) - db.session.commit() - return True - return False + + # if CAS activated and forced, allow only super-user and users with cas_allow_scodoc_login + if ScoDocSiteConfig.is_cas_enabled() and ScoDocSiteConfig.get("cas_force"): + if (not self.is_administrator()) and not self.cas_allow_scodoc_login: + return False + if not self.password_hash: # user without password can't login + if self.password_scodoc7: + # Special case: user freshly migrated from ScoDoc7 + return self._migrate_scodoc7_password(password) return False + return check_password_hash(self.password_hash, password) + def _migrate_scodoc7_password(self, password) -> bool: + """After migration, rehash password.""" + if scu.check_scodoc7_password(self.password_scodoc7, password): + current_app.logger.warning(f"migrating legacy ScoDoc7 password for {self}") + self.set_password(password) + self.password_scodoc7 = None + db.session.add(self) + db.session.commit() + return True + return False + def get_reset_password_token(self, expires_in=600): "Un token pour réinitialiser son mot de passe" return jwt.encode( diff --git a/app/auth/routes.py b/app/auth/routes.py index 5c9848286..ab06dfb16 100644 --- a/app/auth/routes.py +++ b/app/auth/routes.py @@ -27,12 +27,8 @@ _ = lambda x: x # sans babel _l = _ -@bp.route("/login", methods=["GET", "POST"]) -def login(): - "ScoDoc Login form" - if current_user.is_authenticated: - return redirect(url_for("scodoc.index")) - +def _login_form(): + """le formulaire de login, avec un lien CAS s'il est configuré.""" form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(user_name=form.user_name.data).first() @@ -40,9 +36,12 @@ def login(): current_app.logger.info("login: invalid (%s)", form.user_name.data) flash(_("Nom ou mot de passe invalide")) return redirect(url_for("auth.login")) + login_user(user, remember=form.remember_me.data) + current_app.logger.info("login: success (%s)", form.user_name.data) return form.redirect("scodoc.index") + message = request.args.get("message", "") return render_template( "auth/login.j2", @@ -53,6 +52,32 @@ def login(): ) +@bp.route("/login", methods=["GET", "POST"]) +def login(): + """ScoDoc Login form + Si paramètre cas_force, redirige vers le CAS. + """ + if current_user.is_authenticated: + return redirect(url_for("scodoc.index")) + + if ScoDocSiteConfig.get("cas_force"): + current_app.logger.info("login: forcing CAS") + return redirect(url_for("cas.login")) + + return _login_form() + + +@bp.route("/login_scodoc", methods=["GET", "POST"]) +def login_scodoc(): + """ScoDoc Login form. + Formulaire login, sans redirection immédiate sur CAS si ce dernier est configuré. + Sans CAS, ce formulaire est identique à /login + """ + if current_user.is_authenticated: + return redirect(url_for("scodoc.index")) + return _login_form() + + @bp.route("/logout") def logout() -> flask.Response: "Logout a scodoc user. If CAS session, logout from CAS. Redirect." diff --git a/app/decorators.py b/app/decorators.py index 5338828f4..8ececa72f 100644 --- a/app/decorators.py +++ b/app/decorators.py @@ -96,7 +96,7 @@ def permission_required(permission): return decorator -def permission_required_compat_scodoc7(permission): +def permission_required_compat_scodoc7(permission): # XXX TODO A SUPPRIMER """Décorateur pour les fonctions utilisées comme API dans ScoDoc 7 Comme @permission_required mais autorise de passer directement les informations d'auth en paramètres: diff --git a/app/forms/main/config_cas.py b/app/forms/main/config_cas.py index ef8b84cf3..5b6020b84 100644 --- a/app/forms/main/config_cas.py +++ b/app/forms/main/config_cas.py @@ -26,17 +26,20 @@ ############################################################################## """ -Formulaires configuration Exports Apogée (codes) +Formulaire configuration CAS """ from flask_wtf import FlaskForm from wtforms import BooleanField, SubmitField -from wtforms.fields.simple import FileField, StringField, TextAreaField +from wtforms.fields.simple import FileField, StringField class ConfigCASForm(FlaskForm): "Formulaire paramétrage CAS" - cas_enable = BooleanField("activer le CAS") + cas_enable = BooleanField("Activer le CAS") + cas_force = BooleanField( + "Forcer l'utilisation de CAS (tous les utilisateurs seront redirigés vers le CAS)" + ) cas_server = StringField( label="URL du serveur CAS", diff --git a/app/models/config.py b/app/models/config.py index 131106308..de46f95b7 100644 --- a/app/models/config.py +++ b/app/models/config.py @@ -214,20 +214,6 @@ class ScoDocSiteConfig(db.Model): cfg = ScoDocSiteConfig.query.filter_by(name="cas_enable").first() return cfg is not None and cfg.value - @classmethod - def cas_enable(cls, enabled=True) -> bool: - """Active (ou déactive) le CAS. True si changement.""" - if enabled != ScoDocSiteConfig.is_cas_enabled(): - cfg = ScoDocSiteConfig.query.filter_by(name="cas_enable").first() - if cfg is None: - cfg = ScoDocSiteConfig(name="cas_enable", value="on" if enabled else "") - else: - cfg.value = "on" if enabled else "" - db.session.add(cfg) - db.session.commit() - return True - return False - @classmethod def is_entreprises_enabled(cls) -> bool: """True si on doit activer le module entreprise""" @@ -259,10 +245,11 @@ class ScoDocSiteConfig(db.Model): @classmethod def set(cls, name: str, value: str) -> bool: "Set parameter, returns True if change. Commit session." - if cls.get(name) != (value or ""): + value_str = str(value or "") + if (cls.get(name) or "") != value_str: cfg = ScoDocSiteConfig.query.filter_by(name=name).first() if cfg is None: - cfg = ScoDocSiteConfig(name=name, value=str(value)) + cfg = ScoDocSiteConfig(name=name, value=value_str) else: cfg.value = str(value or "") current_app.logger.info( diff --git a/app/scodoc/sco_etud.py b/app/scodoc/sco_etud.py index 4c87bc414..7ba017434 100644 --- a/app/scodoc/sco_etud.py +++ b/app/scodoc/sco_etud.py @@ -226,8 +226,6 @@ _identiteEditor = ndb.EditableTable( "nom_usuel", "prenom", "cas_id", - "cas_allow_login", - "cas_allow_scodoc_login", "civilite", # 'M", "F", or "X" "date_naissance", "lieu_naissance", diff --git a/app/scodoc/sco_import_users.py b/app/scodoc/sco_import_users.py index 2dd527319..e593b4ecc 100644 --- a/app/scodoc/sco_import_users.py +++ b/app/scodoc/sco_import_users.py @@ -31,7 +31,7 @@ import random import time from email.mime.multipart import MIMEMultipart -from flask import g, url_for +from flask import url_for from flask_login import current_user from app import db @@ -41,30 +41,34 @@ import app.scodoc.sco_utils as scu from app import log from app.scodoc.sco_exceptions import AccessDenied, ScoValueError from app.scodoc import sco_excel -from app.scodoc import sco_preferences from app.scodoc import sco_users -TITLES = ("user_name", "nom", "prenom", "email", "roles", "dept") +TITLES = ("user_name", "nom", "prenom", "email", "roles", "dept", "cas_id") COMMENTS = ( """user_name: + L'identifiant (login). Composé de lettres (minuscules ou majuscules), de chiffres ou du caractère _ """, """nom: - Maximum 64 caractères""", + Maximum 64 caractères.""", """prenom: - Maximum 64 caractères""", + Maximum 64 caractères.""", """email: - Maximum 120 caractères""", + 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) + chaque rôle est fait de 2 composantes séparées par _: + 1. Le rôle (Ens, Secr ou Admin) 2. Le département (en majuscule) - Exemple: "Ens_RT,Admin_INFO" + Exemple: "Ens_RT,Admin_INFO". """, """dept: - Le département d'appartenance du l'utillsateur. Laisser vide si l'utilisateur intervient dans plusieurs dépatements + Le département d'appartenance de l'utilisateur. Laisser vide si l'utilisateur intervient dans plusieurs départements. + """, + """cas_id: + + Identifiant de l'utilisateur sur CAS (optionnel). """, ) diff --git a/app/scodoc/sco_preferences.py b/app/scodoc/sco_preferences.py index 07ac4288b..0c9b4710c 100644 --- a/app/scodoc/sco_preferences.py +++ b/app/scodoc/sco_preferences.py @@ -423,9 +423,9 @@ class BasePreferences(object): "email_chefdpt", { "initvalue": "", - "title": "e-mail chef du département", + "title": "e-mail du chef du département", "size": 40, - "explanation": "utilisé pour envoi mail notification absences", + "explanation": "pour lui envoyer des notifications sur les absences", "category": "abs", "only_global": True, }, diff --git a/app/scodoc/sco_users.py b/app/scodoc/sco_users.py index f9bd56922..7da03f29c 100644 --- a/app/scodoc/sco_users.py +++ b/app/scodoc/sco_users.py @@ -63,7 +63,7 @@ def index_html(all_depts=False, with_inactives=False, format="html"): ) if current_user.is_administrator(): H.append( - """ Importer des utilisateurs
""" ) diff --git a/app/static/css/scodoc.css b/app/static/css/scodoc.css index 687fa156e..803855a5e 100644 --- a/app/static/css/scodoc.css +++ b/app/static/css/scodoc.css @@ -4545,6 +4545,11 @@ table.formation_table_recap td.heures_tp { text-align: right; } +div.cas_link { + margin-bottom: 8px; + margin-top: 16px; +} + div.cas_etat_certif_ssl { margin-top: 12px; font-style: italic; diff --git a/app/templates/auth/login.j2 b/app/templates/auth/login.j2 index 8f9f4a8cf..a974fdf3c 100644 --- a/app/templates/auth/login.j2 +++ b/app/templates/auth/login.j2 @@ -10,18 +10,20 @@