From 3c5117c2d0389d84ec53e5b25fee2319c06fb90f Mon Sep 17 00:00:00 2001
From: Emmanuel Viennet <emmanuel.viennet@gmail.com>
Date: Fri, 29 Nov 2024 14:48:27 +0100
Subject: [PATCH] =?UTF-8?q?Edition=20compte=20user:=20am=C3=A9liore=20mess?=
 =?UTF-8?q?age=20erreur=20si=20cas=5Fid=20dupliqu=C3=A9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 app/auth/models.py | 21 ++++++++++-----------
 1 file changed, 10 insertions(+), 11 deletions(-)

diff --git a/app/auth/models.py b/app/auth/models.py
index b79ce703..a3a0c3e4 100644
--- a/app/auth/models.py
+++ b/app/auth/models.py
@@ -67,14 +67,6 @@ def is_valid_user_name(user_name: str) -> bool:
     )
 
 
-def is_new_cas_id(cas_id: str) -> bool:
-    "Check that cas_id is a valid new id (uniqueness, allow nulls)"
-    if not cas_id:
-        return True
-    nb_with_this_id = db.session.query(User).filter_by(cas_id=cas_id).count()
-    return nb_with_this_id == 0
-
-
 class User(UserMixin, ScoDocModel):
     """ScoDoc users, handled by Flask / SQLAlchemy"""
 
@@ -435,11 +427,18 @@ class User(UserMixin, ScoDocModel):
                 if cas_id:
                     new_cas_id = cas_id
         if new_cas_id != self.cas_id:
-            if is_new_cas_id(new_cas_id):
+            existing: User = (
+                db.session.query(User).filter_by(cas_id=new_cas_id).first()
+                if new_cas_id is not None
+                else None
+            )
+            if not existing:
                 self.cas_id = new_cas_id
             else:
-                log(f"User.from_dict: CAS id invalide pour {self.user_name}")
-                raise ScoValueError(f"CAS id invalide pour {self.user_name}")
+                msg = f"""CAS id invalide pour {self.user_name
+                    }, déjà utilisé par {existing.user_name}"""
+                log(f"User.from_dict: {msg}")
+                raise ScoValueError(msg)
 
     def get_token(self, expires_in=3600):
         "Un jeton pour cet user. Stocké en base, non commité."
-- 
GitLab