user.class.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. <?php
  2. /**
  3. * Classe `user`
  4. *
  5. * Cette classe gère les utilisateurs et leurs actions, telles que la récupération
  6. * des informations utilisateur, la gestion des jetons JWT, l'authentification,
  7. * la gestion des tags associés aux utilisateurs, et bien plus encore.
  8. */
  9. class user
  10. {
  11. /**
  12. * Récupère les informations d'un utilisateur.
  13. *
  14. * @param int $userId L'ID de l'utilisateur.
  15. * @return array|bool Les informations de l'utilisateur ou FALSE en cas d'erreur.
  16. */
  17. public static function getUser(int $_id)
  18. {
  19. // Récupération des données de l'excel au format Json
  20. db::query("SELECT "
  21. . "" . DB_T_USER . ".id AS id, "
  22. . "" . DB_T_USER . ".email ,"
  23. . "" . DB_T_USER . ".prenom, "
  24. . "" . DB_T_USER . ".nom, "
  25. . "" . DB_T_USER . ".cree, "
  26. . "" . DB_T_USER . ".last_connect, "
  27. . "" . DB_T_USER . ".googleAuthenticator, "
  28. . "" . DB_T_USER . ".actif, "
  29. . "" . DB_T_USER . ".deleted, "
  30. . "" . DB_T_USER . ".id_type, "
  31. . "" . DB_T_TYPE_USER . ".type "
  32. . "FROM " . DB_T_USER . " "
  33. . "INNER JOIN " . DB_T_TYPE_USER . " ON " . DB_T_USER . ".id_type = " . DB_T_TYPE_USER . ".id "
  34. . "WHERE " . DB_T_USER . ".id = :id");
  35. db::bind(':id', $_id);
  36. $return = db::single();
  37. $return["tags"] = self::getTags($_id);
  38. return $return;
  39. }
  40. /**
  41. * Récupère la liste des utilisateurs.
  42. *
  43. * @return array Liste des utilisateurs avec leurs informations et tags associés.
  44. */
  45. public static function getUsers()
  46. {
  47. // Récupération des données de l'excel au format Json
  48. db::query("SELECT "
  49. . "" . DB_T_USER . ".id, "
  50. . "" . DB_T_USER . ".email, "
  51. . "" . DB_T_USER . ".prenom, "
  52. . "" . DB_T_USER . ".nom, "
  53. . "" . DB_T_USER . ".cree, "
  54. . "" . DB_T_USER . ".last_connect, "
  55. . "" . DB_T_USER . ".googleAuthenticator, "
  56. . "" . DB_T_USER . ".actif, "
  57. . "" . DB_T_USER . ".id_type, "
  58. . "" . DB_T_TYPE_USER . ".type "
  59. . "FROM " . DB_T_USER . " "
  60. . "INNER JOIN " . DB_T_TYPE_USER . " ON " . DB_T_USER . ".id_type = " . DB_T_TYPE_USER . ".id "
  61. . "WHERE " . DB_T_USER . ".deleted = 0");
  62. $return = db::resultset();
  63. foreach ($return as $key => $users) {
  64. $return[$key] = $users;
  65. $return[$key]["tags"] = self::getTags($users["id"]);
  66. }
  67. return $return;
  68. }
  69. /**
  70. * Récupère le nom complet d'un utilisateur par son identifiant.
  71. *
  72. * @param int $_id Identifiant de l'utilisateur.
  73. * @return string Nom complet de l'utilisateur.
  74. */
  75. public static function getNameById(int $_id)
  76. {
  77. db::query("SELECT "
  78. . "CONCAT (" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS 'name' "
  79. . "FROM " . DB_T_USER . " "
  80. . "WHERE " . DB_T_USER . ".id = :id");
  81. db::bind(':id', $_id);
  82. return db::single()["name"];
  83. }
  84. /**
  85. * Récupère le secret Google Authenticator d'un utilisateur.
  86. *
  87. * @param int $_id Identifiant de l'utilisateur.
  88. * @return string Secret Google Authenticator.
  89. */
  90. public static function getMyGoogleAuthenticator(int $_id)
  91. {
  92. db::query("SELECT "
  93. . "" . DB_T_USER . ".googleAuthenticatorSecret "
  94. . "FROM " . DB_T_USER . " "
  95. . "WHERE " . DB_T_USER . ".id = :id");
  96. db::bind(':id', $_id);
  97. return db::single()["googleAuthenticatorSecret"];
  98. }
  99. /**
  100. * Vérifie si un utilisateur a activé Google Authenticator.
  101. *
  102. * @param string $_email Email de l'utilisateur.
  103. * @return int 1 si activé, 0 sinon.
  104. */
  105. public static function checkGoogleAuthenticator(string $_email)
  106. {
  107. db::query("SELECT "
  108. . "" . DB_T_USER . ".googleAuthenticator "
  109. . "FROM " . DB_T_USER . " "
  110. . "WHERE " . DB_T_USER . ".email = :email");
  111. db::bind(':email', $_email);
  112. $return = db::single();
  113. return (isset($return["googleAuthenticator"])) ? $return["googleAuthenticator"] : 0;
  114. }
  115. /**
  116. * Vérifie le statut du 2FA d'un utilisateur par son ID.
  117. *
  118. * @param int $_id Identifiant de l'utilisateur.
  119. * @return int 1 si activé, 0 sinon.
  120. */
  121. public static function check2FAStatus(int $_id): int
  122. {
  123. db::query("SELECT googleAuthenticator FROM " . DB_T_USER . " WHERE id = :id");
  124. db::bind(':id', $_id);
  125. $result = db::single();
  126. return isset($result["googleAuthenticator"]) ? (int)$result["googleAuthenticator"] : 0;
  127. }
  128. /**
  129. * Insère un jeton JWT pour un utilisateur.
  130. *
  131. * @param int $_id_user Identifiant de l'utilisateur.
  132. * @param string $_jwt Jeton JWT à insérer.
  133. * @return bool TRUE si l'insertion est réussie, FALSE sinon.
  134. */
  135. private static function insertJWT($_id_user, $_jwt)
  136. {
  137. self::deleteJWTbyUSer($_id_user);
  138. db::query("INSERT INTO " . DB_T_JWT . " (id_user, md5, jwt) VALUES (:id_user, :md5, :jwt)");
  139. db::bind(':id_user', $_id_user);
  140. db::bind(':md5', md5($_jwt));
  141. db::bind(':jwt', $_jwt);
  142. try {
  143. db::execute();
  144. return TRUE;
  145. } catch (Exception $ex) {
  146. return FALSE;
  147. }
  148. }
  149. /**
  150. * Supprime tous les jetons JWT d'un utilisateur.
  151. *
  152. * @param int $_id_user Identifiant de l'utilisateur.
  153. * @return bool TRUE si la suppression est réussie, FALSE sinon.
  154. */
  155. public static function deleteJWTbyUSer($_id_user)
  156. {
  157. db::query("DELETE FROM " . DB_T_JWT . " WHERE id_user = :id_user");
  158. db::bind(':id_user', $_id_user);
  159. try {
  160. db::execute();
  161. return TRUE;
  162. } catch (Exception $ex) {
  163. return FALSE;
  164. }
  165. }
  166. /**
  167. * Met à jour un jeton JWT par son empreinte MD5.
  168. *
  169. * @param string $_md5 Empreinte MD5 du jeton existant.
  170. * @param string $_jwt Nouveau jeton JWT.
  171. * @return bool TRUE si la mise à jour est réussie, FALSE sinon.
  172. */
  173. public static function updateJWTbyMd5($_md5, $_jwt)
  174. {
  175. db::query("UPDATE " . DB_T_JWT . " SET jwt = :jwt, md5 = :newmd5 WHERE md5 = :md5");
  176. db::bind(':md5', $_md5);
  177. db::bind(':jwt', $_jwt);
  178. db::bind(':newmd5', md5($_jwt));
  179. try {
  180. db::execute();
  181. return TRUE;
  182. } catch (Exception $ex) {
  183. return FALSE;
  184. }
  185. }
  186. /**
  187. * Récupère les informations d'un utilisateur à partir d'un jeton JWT.
  188. *
  189. * @param string $_jwt Jeton JWT.
  190. * @return array|bool Informations de l'utilisateur ou FALSE si non trouvé.
  191. */
  192. public static function getInfosByJWT($_jwt)
  193. {
  194. db::query("SELECT id_user, creer FROM " . DB_T_JWT . " WHERE md5 = :md5");
  195. db::bind(':md5', md5($_jwt));
  196. $row = db::single();
  197. if (isset($row["id_user"])) {
  198. return $row;
  199. } else {
  200. return FALSE;
  201. }
  202. }
  203. /**
  204. * Authentifie un utilisateur avec ses informations d'entrée.
  205. *
  206. * @param array $_input Données d'entrée pour l'authentification.
  207. * @return array Résultat de l'authentification avec les informations utilisateur.
  208. */
  209. public static function authenticator(array $_input)
  210. {
  211. db::query("SELECT id, email, password, prenom, nom, id_type, googleAuthenticator, googleAuthenticatorSecret, actif FROM " . DB_T_USER . " WHERE email = :email AND deleted = 0");
  212. db::bind(':email', $_input["email"]);
  213. $row = db::single();
  214. if (isset($row["id"])) {
  215. if ($row["actif"] == 0) {
  216. return [
  217. "status" => "error",
  218. "type" => "actif"
  219. ];
  220. } elseif (isset($_input["password"]) and md5($_input["password"]) == $row["password"]) {
  221. return [
  222. "status" => "success",
  223. "type" => "authent",
  224. "id" => $row["id"],
  225. "prenom" => $row["prenom"],
  226. "nom" => $row["nom"],
  227. "googleAuthenticator" => $row["googleAuthenticator"],
  228. "googleAuthenticatorSecret" => $row["googleAuthenticatorSecret"],
  229. "idType" => $row["id_type"],
  230. "email" => $row["email"],
  231. "actif" => $row["actif"],
  232. "iat" => time(),
  233. "exp" => time() + JWT_DURATION
  234. ];
  235. } else {
  236. return [
  237. "status" => "error",
  238. "type" => "authent"
  239. ];
  240. }
  241. } else {
  242. return [
  243. "status" => "error",
  244. "type" => "unknown"
  245. ];
  246. }
  247. }
  248. /**
  249. * Connecte un utilisateur en vérifiant ses informations d'entrée.
  250. *
  251. * @param array $_input Données d'entrée pour la connexion.
  252. * @return bool TRUE si la connexion est réussie, FALSE sinon.
  253. */
  254. public static function connect(array $_input)
  255. {
  256. $connect = jwt::authenticate($_input);
  257. if ($connect["googleAuthenticator"] == 1 and DOMAIN_CONTROL != $_SERVER['SERVER_NAME']) {
  258. if (googleAuthenticator::verifyCode($connect["googleAuthenticatorSecret"], $_input["authenticator"], 1) == FALSE) {
  259. $connect["id"] = NULL;
  260. }
  261. }
  262. if (isset($connect["id"])) {
  263. if ($connect["status"] == "success") {
  264. $_SESSION["user"] = array(
  265. "id" => $connect["id"],
  266. "prenom" => $connect["prenom"],
  267. "nom" => $connect["nom"],
  268. "googleAuthenticator" => $connect["googleAuthenticator"],
  269. "idType" => $connect["idType"],
  270. "email" => $connect["email"],
  271. "actif" => $connect["actif"],
  272. "token" => $connect["token"]
  273. );
  274. self::updateLastConnect($connect["id"]);
  275. self::insertJWT($connect["id"], $connect["token"]);
  276. return TRUE;
  277. } else {
  278. if ($connect["type"] == "actif") {
  279. alert::recError("Votre compte est désactivé");
  280. return FALSE;
  281. } elseif ($connect["type"] == "authent") {
  282. alert::recError("Erreur d'authentification");
  283. return FALSE;
  284. } elseif ($connect["type"] == "unknown") {
  285. alert::recError("Erreur d'authentification");
  286. return FALSE;
  287. }
  288. }
  289. } else {
  290. alert::recError("Erreur d'authentification");
  291. return FALSE;
  292. }
  293. }
  294. /**
  295. * Met à jour la date de dernière connexion d'un utilisateur.
  296. *
  297. * @param int $_id Identifiant de l'utilisateur.
  298. */
  299. private static function updateLastConnect(int $_id)
  300. {
  301. db::query("UPDATE " . DB_T_USER . " SET `last_connect` = CURRENT_TIMESTAMP() WHERE id = :id");
  302. db::bind(':id', $_id);
  303. db::execute();
  304. }
  305. /**
  306. * Ajoute un nouvel utilisateur dans la base de données.
  307. *
  308. * @param array $_input Données de l'utilisateur à ajouter.
  309. */
  310. public static function add_user(array $_input)
  311. {
  312. db::query("INSERT INTO " . DB_T_USER . " "
  313. . "(email, password, googleAuthenticator, googleAuthenticatorSecret, prenom, nom, id_type, actif) "
  314. . "VALUES (:email, :password, :googleAuthenticator, :googleAuthenticatorSecret, :prenom, :nom, :id_type, :actif)");
  315. db::bind(':email', $_input["email"]);
  316. db::bind(':password', md5($_input["password"]));
  317. db::bind(':prenom', $_input["prenom"]);
  318. db::bind(':nom', $_input["nom"]);
  319. db::bind(':googleAuthenticator', $_input["googleAuthenticator"]);
  320. db::bind(':googleAuthenticatorSecret', googleAuthenticator::createSecret());
  321. db::bind(':id_type', $_input["id_type"]);
  322. db::bind(':actif', $_input["actif"]);
  323. try {
  324. db::execute();
  325. $tags = tags::textToId($_input["tags"], 1);
  326. self::addTags(db::lastInsertId(), $tags);
  327. alert::recSuccess("La création a bien été prise en compte");
  328. } catch (Exception $ex) {
  329. alert::recError("Erreur lors de la création de l'utilisateur");
  330. header("Location: /add-user.html");
  331. exit();
  332. }
  333. }
  334. /**
  335. * Récupère l'identifiant du dernier utilisateur ajouté.
  336. *
  337. * @return int Identifiant du dernier utilisateur.
  338. */
  339. public static function lastUser()
  340. {
  341. db::query("SELECT MAX(id) AS id FROM " . DB_T_USER);
  342. return db::single()["id"];
  343. }
  344. /**
  345. * Met à jour les informations d'un utilisateur existant.
  346. *
  347. * @param array $_input Données mises à jour de l'utilisateur.
  348. */
  349. public static function maj_user(array $_input)
  350. {
  351. if ($_input["password"] != "") {
  352. db::query("UPDATE " . DB_T_USER . " SET password = :password WHERE id = :id");
  353. db::bind(':password', md5($_input["password"]));
  354. db::bind(':id', $_input["id"]);
  355. try {
  356. db::execute();
  357. } catch (Exception $ex) {
  358. alert::recError("Erreur lors de la modification du mot de passe");
  359. header("Location: /user-" . $_input["id"] . ".html");
  360. exit();
  361. }
  362. }
  363. if (self::getMyGoogleAuthenticator($_input["id"]) == NULL) {
  364. db::query("UPDATE " . DB_T_USER . " SET googleAuthenticatorSecret = :googleAuthenticatorSecret WHERE id = :id");
  365. db::bind(':googleAuthenticatorSecret', googleAuthenticator::createSecret());
  366. db::bind(':id', $_input["id"]);
  367. try {
  368. db::execute();
  369. } catch (Exception $ex) {
  370. alert::recError("Erreur lors de la création du token de Google Authenticator");
  371. header("Location: /user-" . $_input["id"] . ".html");
  372. exit();
  373. }
  374. }
  375. $tags = tags::textToId($_input["tags"], 1);
  376. self::addTags($_input["id"], $tags);
  377. // Vérifier si on active le 2FA (passage de 0 à 1)
  378. $current2FA = self::check2FAStatus($_input["id"]);
  379. $new2FA = isset($_input["googleAuthenticator"]) ? (int)$_input["googleAuthenticator"] : 0;
  380. // Si on veut activer le 2FA et qu'il n'est pas déjà actif, on le met en pending
  381. if ($new2FA == 1 && $current2FA == 0) {
  382. self::set2FAPending($_input["id"]);
  383. $googleAuthValue = 0; // Reste à 0 jusqu'à validation
  384. } else {
  385. $googleAuthValue = $new2FA;
  386. // Si on désactive le 2FA, on supprime aussi le pending
  387. if ($new2FA == 0) {
  388. self::cancel2FAPending($_input["id"]);
  389. }
  390. }
  391. db::query("UPDATE " . DB_T_USER . " SET
  392. email = :email,
  393. prenom = :prenom,
  394. nom = :nom,
  395. id_type = :id_type,
  396. googleAuthenticator = :googleAuthenticator,
  397. actif = :actif
  398. WHERE id = :id");
  399. db::bind(':email', $_input["email"]);
  400. db::bind(':prenom', $_input["prenom"]);
  401. db::bind(':nom', $_input["nom"]);
  402. db::bind(':googleAuthenticator', $googleAuthValue);
  403. db::bind(':id_type', $_input["id_type"]);
  404. db::bind(':actif', $_input["actif"]);
  405. db::bind(':id', $_input["id"]);
  406. try {
  407. db::execute();
  408. alert::recSuccess("La modification a bien été prise en compte");
  409. } catch (Exception $ex) {
  410. alert::recError("Erreur lors de la modification de l'utilisateur");
  411. header("Location: /user-" . $_input["id"] . ".html");
  412. exit();
  413. }
  414. }
  415. /**
  416. * Récupère les tags associés à un utilisateur.
  417. *
  418. * @param float $_idUser Identifiant de l'utilisateur.
  419. * @return string|null Liste des tags sous forme de chaîne ou NULL si aucun tag.
  420. */
  421. static public function getTags(float $_idUser)
  422. {
  423. db::query("SELECT "
  424. . "" . DB_T_TAGS . ".label "
  425. . "FROM " . DB_T_USER_TAGS . " "
  426. . "INNER JOIN " . DB_T_TAGS . " ON " . DB_T_TAGS . ".id = " . DB_T_USER_TAGS . ".id_tags "
  427. . "WHERE " . DB_T_USER_TAGS . ".id_user = :id "
  428. . "ORDER BY " . DB_T_USER_TAGS . ".creer");
  429. db::bind(':id', $_idUser);
  430. $tmp = db::resultset();
  431. if (isset($tmp[0])) {
  432. $return = NULL;
  433. foreach ($tmp as $value) {
  434. $return .= $value["label"] . ",";
  435. }
  436. $return = substr($return, 0, -1);
  437. return $return;
  438. } else {
  439. return NULL;
  440. }
  441. }
  442. /**
  443. * Récupère les identifiants des tags associés à un utilisateur.
  444. *
  445. * @param float $_idUser Identifiant de l'utilisateur.
  446. * @return array|null Liste des identifiants des tags ou NULL si aucun tag.
  447. */
  448. static public function getIdTags(float $_idUser)
  449. {
  450. db::query("SELECT "
  451. . "" . DB_T_USER_TAGS . ".id_tags "
  452. . "FROM " . DB_T_USER_TAGS . " "
  453. . "WHERE " . DB_T_USER_TAGS . ".id_user = :id "
  454. . "ORDER BY " . DB_T_USER_TAGS . ".creer");
  455. db::bind(':id', $_idUser);
  456. $tmp = db::resultset();
  457. if (isset($tmp[0])) {
  458. $return = [];
  459. foreach ($tmp as $value) {
  460. $return[] = $value["id_tags"];
  461. }
  462. return $return;
  463. } else {
  464. return NULL;
  465. }
  466. }
  467. /**
  468. * Ajoute des tags à un utilisateur.
  469. *
  470. * @param float $_idUser Identifiant de l'utilisateur.
  471. * @param string|null $_tags Liste des tags sous forme de chaîne (séparés par des virgules).
  472. * @return bool TRUE si les tags sont ajoutés avec succès, FALSE en cas d'échec.
  473. */
  474. private static function addTags(float $_idUser, ?string $_tags = NULL)
  475. {
  476. db::query("DELETE FROM " . DB_T_USER_TAGS . " WHERE id_user = :id_user");
  477. db::bind(':id_user', $_idUser);
  478. db::execute();
  479. if ($_tags != NULL) {
  480. $tags = explode(",", $_tags);
  481. $sqlMaj = "";
  482. foreach ($tags as $tag) {
  483. $sqlMaj .= " (:id_user, " . $tag . "),";
  484. }
  485. $sqlMaj = substr($sqlMaj, 0, -1);
  486. db::query("INSERT INTO " . DB_T_USER_TAGS . " (id_user, id_tags) VALUES" . $sqlMaj);
  487. db::bind(':id_user', $_idUser);
  488. try {
  489. db::execute();
  490. return TRUE;
  491. } catch (Exception $ex) {
  492. return FALSE;
  493. }
  494. }
  495. }
  496. /**
  497. * Marque un utilisateur comme supprimé.
  498. *
  499. * @param int $_id Identifiant de l'utilisateur.
  500. */
  501. public static function deleteUser(int $_id)
  502. {
  503. db::query("UPDATE " . DB_T_USER . " SET deleted = 1 WHERE id = :id");
  504. db::bind(':id', $_id);
  505. try {
  506. db::execute();
  507. } catch (Exception $ex) {
  508. alert::recError("Erreur lors de la suppression");
  509. header("Location: /user-" . $_id . ".html");
  510. exit();
  511. }
  512. }
  513. /**
  514. * Restaure un utilisateur précédemment supprimé.
  515. *
  516. * @param int $_id Identifiant de l'utilisateur.
  517. */
  518. public static function restoreUser(int $_id)
  519. {
  520. db::query("UPDATE " . DB_T_USER . " SET deleted = 0 WHERE id = :id");
  521. db::bind(':id', $_id);
  522. try {
  523. db::execute();
  524. } catch (Exception $ex) {
  525. alert::recError("Erreur lors de la restauration");
  526. header("Location: /user-" . $_id . ".html");
  527. exit();
  528. }
  529. }
  530. /**
  531. * Vérifie si l'utilisateur a activé la double authentification.
  532. *
  533. * @return bool TRUE si la double authentification est activée, FALSE sinon.
  534. */
  535. static public function checkSecur()
  536. {
  537. db::query("SELECT googleAuthenticator FROM " . DB_T_USER . " WHERE id = :id");
  538. db::bind(':id', session::getId());
  539. return db::single()["googleAuthenticator"] == 1 ? TRUE : FALSE;
  540. }
  541. /**
  542. * Affiche un message de sécurité si la double authentification n'est pas activée.
  543. */
  544. static public function printIsSecur()
  545. {
  546. if (ALERT_AUTHENTICATOR == TRUE) {
  547. $_SESSION["CALLOUT"] ??= 0;
  548. if (self::checkSecur() == FALSE and $_SESSION["CALLOUT"] < NB_ALERT_AUTHENTICATOR) {
  549. $callout = [
  550. "type" => "danger",
  551. "size" => "tiny",
  552. "p" => "Pour sécuriser l'accès au CMS, il est fortement recommandé d'activer la double authentification (Google Authenticator) sur votre profil. Pour l'activer sur votre profil en <a href=\"/user.html\">cliquant ici</a>.",
  553. ];
  554. callout::print($callout);
  555. $_SESSION["CALLOUT"]++;
  556. }
  557. }
  558. }
  559. /**
  560. * Vérifie si le 2FA est en attente de validation pour un utilisateur.
  561. *
  562. * @param int $_id Identifiant de l'utilisateur.
  563. * @return bool TRUE si le 2FA est en attente de validation, FALSE sinon.
  564. */
  565. public static function is2FAPending(int $_id): bool
  566. {
  567. try {
  568. db::query("SELECT googleAuthenticatorPending FROM " . DB_T_USER . " WHERE id = :id");
  569. db::bind(':id', $_id);
  570. $result = db::single();
  571. return isset($result["googleAuthenticatorPending"]) && $result["googleAuthenticatorPending"] == 1;
  572. } catch (Exception $ex) {
  573. // La colonne n'existe pas encore, retourner false
  574. return false;
  575. }
  576. }
  577. /**
  578. * Définit le 2FA en mode pending (en attente de validation du premier code).
  579. *
  580. * @param int $_id Identifiant de l'utilisateur.
  581. * @return bool TRUE si la mise à jour est réussie, FALSE sinon.
  582. */
  583. public static function set2FAPending(int $_id): bool
  584. {
  585. db::query("UPDATE " . DB_T_USER . " SET googleAuthenticatorPending = 1, googleAuthenticator = 0 WHERE id = :id");
  586. db::bind(':id', $_id);
  587. try {
  588. db::execute();
  589. return true;
  590. } catch (Exception $ex) {
  591. return false;
  592. }
  593. }
  594. /**
  595. * Valide le code TOTP et active définitivement le 2FA.
  596. *
  597. * @param int $_id Identifiant de l'utilisateur.
  598. * @param string $_code Code TOTP à vérifier.
  599. * @return array Résultat de la validation avec status et message.
  600. */
  601. public static function validate2FAActivation(int $_id, string $_code): array
  602. {
  603. // Récupérer le secret de l'utilisateur
  604. $secret = self::getMyGoogleAuthenticator($_id);
  605. if (empty($secret)) {
  606. return [
  607. "status" => "error",
  608. "message" => "Aucun secret Google Authenticator configuré."
  609. ];
  610. }
  611. // Vérifier le code TOTP
  612. if (googleAuthenticator::verifyCode($secret, $_code, 1)) {
  613. // Code valide, activer le 2FA et supprimer le pending
  614. db::query("UPDATE " . DB_T_USER . " SET googleAuthenticator = 1, googleAuthenticatorPending = 0 WHERE id = :id");
  615. db::bind(':id', $_id);
  616. try {
  617. db::execute();
  618. return [
  619. "status" => "success",
  620. "message" => "La double authentification a été activée avec succès."
  621. ];
  622. } catch (Exception $ex) {
  623. return [
  624. "status" => "error",
  625. "message" => "Erreur lors de l'activation de la double authentification."
  626. ];
  627. }
  628. } else {
  629. return [
  630. "status" => "error",
  631. "message" => "Code invalide. Veuillez réessayer."
  632. ];
  633. }
  634. }
  635. /**
  636. * Annule le mode pending du 2FA.
  637. *
  638. * @param int $_id Identifiant de l'utilisateur.
  639. * @return bool TRUE si l'annulation est réussie, FALSE sinon.
  640. */
  641. public static function cancel2FAPending(int $_id): bool
  642. {
  643. db::query("UPDATE " . DB_T_USER . " SET googleAuthenticatorPending = 0 WHERE id = :id");
  644. db::bind(':id', $_id);
  645. try {
  646. db::execute();
  647. return true;
  648. } catch (Exception $ex) {
  649. return false;
  650. }
  651. }
  652. }