user.class.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. // Récupération des données de l'excel au format Json
  47. db::query("SELECT "
  48. . "" . DB_T_USER . ".id, "
  49. . "" . DB_T_USER . ".email, "
  50. . "" . DB_T_USER . ".prenom, "
  51. . "" . DB_T_USER . ".nom, "
  52. . "" . DB_T_USER . ".cree, "
  53. . "" . DB_T_USER . ".last_connect, "
  54. . "" . DB_T_USER . ".googleAuthenticator, "
  55. . "" . DB_T_USER . ".actif, "
  56. . "" . DB_T_USER . ".id_type, "
  57. . "" . DB_T_TYPE_USER . ".type "
  58. . "FROM " . DB_T_USER . " "
  59. . "INNER JOIN " . DB_T_TYPE_USER . " ON " . DB_T_USER . ".id_type = " . DB_T_TYPE_USER . ".id "
  60. . "WHERE " . DB_T_USER . ".deleted = 0");
  61. $return = db::resultset();
  62. foreach ($return as $key => $users) {
  63. $return[$key] = $users;
  64. $return[$key]["tags"] = self::getTags($users["id"]);
  65. }
  66. return $return;
  67. }
  68. /**
  69. * Récupère le nom complet d'un utilisateur par son identifiant.
  70. *
  71. * @param int $_id Identifiant de l'utilisateur.
  72. * @return string Nom complet de l'utilisateur.
  73. */
  74. public static function getNameById(int $_id) {
  75. db::query("SELECT "
  76. . "CONCAT (" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS 'name' "
  77. . "FROM " . DB_T_USER . " "
  78. . "WHERE " . DB_T_USER . ".id = :id");
  79. db::bind(':id', $_id);
  80. return db::single()["name"];
  81. }
  82. /**
  83. * Récupère le secret Google Authenticator d'un utilisateur.
  84. *
  85. * @param int $_id Identifiant de l'utilisateur.
  86. * @return string Secret Google Authenticator.
  87. */
  88. public static function getMyGoogleAuthenticator(int $_id){
  89. db::query("SELECT "
  90. . "" . DB_T_USER . ".googleAuthenticatorSecret "
  91. . "FROM " . DB_T_USER . " "
  92. . "WHERE " . DB_T_USER . ".id = :id");
  93. db::bind(':id', $_id);
  94. return db::single()["googleAuthenticatorSecret"];
  95. }
  96. /**
  97. * Vérifie si un utilisateur a activé Google Authenticator.
  98. *
  99. * @param string $_email Email de l'utilisateur.
  100. * @return int 1 si activé, 0 sinon.
  101. */
  102. public static function checkGoogleAuthenticator(string $_email){
  103. db::query("SELECT "
  104. . "" . DB_T_USER . ".googleAuthenticator "
  105. . "FROM " . DB_T_USER . " "
  106. . "WHERE " . DB_T_USER . ".email = :email");
  107. db::bind(':email', $_email);
  108. $return = db::single();
  109. return (isset($return["googleAuthenticator"])) ? $return["googleAuthenticator"] : 0;
  110. }
  111. /**
  112. * Insère un jeton JWT pour un utilisateur.
  113. *
  114. * @param int $_id_user Identifiant de l'utilisateur.
  115. * @param string $_jwt Jeton JWT à insérer.
  116. * @return bool TRUE si l'insertion est réussie, FALSE sinon.
  117. */
  118. private static function insertJWT($_id_user, $_jwt){
  119. self::deleteJWTbyUSer($_id_user);
  120. db::query("INSERT INTO " . DB_T_JWT . " (id_user, md5, jwt) VALUES (:id_user, :md5, :jwt)");
  121. db::bind(':id_user', $_id_user);
  122. db::bind(':md5', md5($_jwt));
  123. db::bind(':jwt', $_jwt);
  124. try {
  125. db::execute();
  126. return TRUE;
  127. } catch (Exception $ex) {
  128. return FALSE;
  129. }
  130. }
  131. /**
  132. * Supprime tous les jetons JWT d'un utilisateur.
  133. *
  134. * @param int $_id_user Identifiant de l'utilisateur.
  135. * @return bool TRUE si la suppression est réussie, FALSE sinon.
  136. */
  137. public static function deleteJWTbyUSer($_id_user){
  138. db::query("DELETE FROM " . DB_T_JWT . " WHERE id_user = :id_user");
  139. db::bind(':id_user', $_id_user);
  140. try {
  141. db::execute();
  142. return TRUE;
  143. } catch (Exception $ex) {
  144. return FALSE;
  145. }
  146. }
  147. /**
  148. * Met à jour un jeton JWT par son empreinte MD5.
  149. *
  150. * @param string $_md5 Empreinte MD5 du jeton existant.
  151. * @param string $_jwt Nouveau jeton JWT.
  152. * @return bool TRUE si la mise à jour est réussie, FALSE sinon.
  153. */
  154. public static function updateJWTbyMd5($_md5, $_jwt){
  155. db::query("UPDATE " . DB_T_JWT . " SET jwt = :jwt, md5 = :newmd5 WHERE md5 = :md5");
  156. db::bind(':md5', $_md5);
  157. db::bind(':jwt', $_jwt);
  158. db::bind(':newmd5', md5($_jwt));
  159. try {
  160. db::execute();
  161. return TRUE;
  162. } catch (Exception $ex) {
  163. return FALSE;
  164. }
  165. }
  166. /**
  167. * Récupère les informations d'un utilisateur à partir d'un jeton JWT.
  168. *
  169. * @param string $_jwt Jeton JWT.
  170. * @return array|bool Informations de l'utilisateur ou FALSE si non trouvé.
  171. */
  172. public static function getInfosByJWT($_jwt){
  173. db::query("SELECT id_user, creer FROM " . DB_T_JWT . " WHERE md5 = :md5");
  174. db::bind(':md5', md5($_jwt));
  175. $row = db::single();
  176. if(isset($row["id_user"])){
  177. return $row;
  178. } else {
  179. return FALSE;
  180. }
  181. }
  182. /**
  183. * Authentifie un utilisateur avec ses informations d'entrée.
  184. *
  185. * @param array $_input Données d'entrée pour l'authentification.
  186. * @return array Résultat de l'authentification avec les informations utilisateur.
  187. */
  188. public static function authenticator(array $_input)
  189. {
  190. db::query("SELECT id, email, password, prenom, nom, id_type, googleAuthenticator, googleAuthenticatorSecret, actif FROM " . DB_T_USER . " WHERE email = :email AND deleted = 0");
  191. db::bind(':email', $_input["email"]);
  192. $row = db::single();
  193. if (isset($row["id"])) {
  194. if ($row["actif"] == 0) {
  195. return [
  196. "status" => "error",
  197. "type" => "actif"
  198. ];
  199. } elseif (isset($_input["password"]) and md5($_input["password"]) == $row["password"]) {
  200. return [
  201. "status" => "success",
  202. "type" => "authent",
  203. "id" => $row["id"],
  204. "prenom" => $row["prenom"],
  205. "nom" => $row["nom"],
  206. "googleAuthenticator" => $row["googleAuthenticator"],
  207. "googleAuthenticatorSecret" => $row["googleAuthenticatorSecret"],
  208. "idType" => $row["id_type"],
  209. "email" => $row["email"],
  210. "actif" => $row["actif"],
  211. "iat" => time(),
  212. "exp" => time() + JWT_DURATION
  213. ];
  214. } else {
  215. return [
  216. "status" => "error",
  217. "type" => "authent"
  218. ];
  219. }
  220. } else {
  221. return [
  222. "status" => "error",
  223. "type" => "unknown"
  224. ];
  225. }
  226. }
  227. /**
  228. * Connecte un utilisateur en vérifiant ses informations d'entrée.
  229. *
  230. * @param array $_input Données d'entrée pour la connexion.
  231. * @return bool TRUE si la connexion est réussie, FALSE sinon.
  232. */
  233. public static function connect(array $_input) {
  234. $connect = jwt::authenticate($_input);
  235. if ($connect["googleAuthenticator"] == 1 and DOMAIN_CONTROL != $_SERVER['SERVER_NAME']) {
  236. if (googleAuthenticator::verifyCode($connect["googleAuthenticatorSecret"], $_input["authenticator"], 1) == FALSE) {
  237. $connect["id"] = NULL;
  238. }
  239. }
  240. if (isset($connect["id"])) {
  241. if ($connect["status"] == "success") {
  242. $_SESSION["user"] = array(
  243. "id" => $connect["id"],
  244. "prenom" => $connect["prenom"],
  245. "nom" => $connect["nom"],
  246. "googleAuthenticator" => $connect["googleAuthenticator"],
  247. "idType" => $connect["idType"],
  248. "email" => $connect["email"],
  249. "actif" => $connect["actif"],
  250. "token" => $connect["token"]
  251. );
  252. self::updateLastConnect($connect["id"]);
  253. self::insertJWT($connect["id"], $connect["token"]);
  254. return TRUE;
  255. } else {
  256. if ($connect["type"] == "actif") {
  257. alert::recError("Votre compte est désactivé");
  258. return FALSE;
  259. } elseif ($connect["type"] == "authent") {
  260. alert::recError("Erreur d'authentification");
  261. return FALSE;
  262. } elseif ($connect["type"] == "unknown") {
  263. alert::recError("Erreur d'authentification");
  264. return FALSE;
  265. }
  266. }
  267. } else {
  268. alert::recError("Erreur d'authentification");
  269. return FALSE;
  270. }
  271. }
  272. /**
  273. * Met à jour la date de dernière connexion d'un utilisateur.
  274. *
  275. * @param int $_id Identifiant de l'utilisateur.
  276. */
  277. private static function updateLastConnect(int $_id){
  278. db::query("UPDATE " . DB_T_USER . " SET `last_connect` = CURRENT_TIMESTAMP() WHERE id = :id");
  279. db::bind(':id', $_id);
  280. db::execute();
  281. }
  282. /**
  283. * Ajoute un nouvel utilisateur dans la base de données.
  284. *
  285. * @param array $_input Données de l'utilisateur à ajouter.
  286. */
  287. public static function add_user(array $_input){
  288. db::query("INSERT INTO " . DB_T_USER . " "
  289. . "(email, password, googleAuthenticator, googleAuthenticatorSecret, prenom, nom, id_type, actif) "
  290. . "VALUES (:email, :password, :googleAuthenticator, :googleAuthenticatorSecret, :prenom, :nom, :id_type, :actif)");
  291. db::bind(':email', $_input["email"]);
  292. db::bind(':password', md5($_input["password"]));
  293. db::bind(':prenom', $_input["prenom"]);
  294. db::bind(':nom', $_input["nom"]);
  295. db::bind(':googleAuthenticator', $_input["googleAuthenticator"]);
  296. db::bind(':googleAuthenticatorSecret', googleAuthenticator::createSecret());
  297. db::bind(':id_type', $_input["id_type"]);
  298. db::bind(':actif', $_input["actif"]);
  299. try {
  300. db::execute();
  301. $tags = tags::textToId($_input["tags"], 1);
  302. self::addTags(db::lastInsertId(), $tags);
  303. alert::recSuccess("La création a bien été prise en compte");
  304. } catch (Exception $ex) {
  305. alert::recError("Erreur lors de la création de l'utilisateur");
  306. header("Location: /add-user.html");
  307. exit();
  308. }
  309. }
  310. /**
  311. * Récupère l'identifiant du dernier utilisateur ajouté.
  312. *
  313. * @return int Identifiant du dernier utilisateur.
  314. */
  315. public static function lastUser(){
  316. db::query("SELECT MAX(id) AS id FROM ". DB_T_USER);
  317. return db::single()["id"];
  318. }
  319. /**
  320. * Met à jour les informations d'un utilisateur existant.
  321. *
  322. * @param array $_input Données mises à jour de l'utilisateur.
  323. */
  324. public static function maj_user(array $_input){
  325. if($_input["password"] != ""){
  326. db::query("UPDATE " . DB_T_USER . " SET password = :password WHERE id = :id");
  327. db::bind(':password', md5($_input["password"]));
  328. db::bind(':id', $_input["id"]);
  329. try {
  330. db::execute();
  331. } catch (Exception $ex) {
  332. alert::recError("Erreur lors de la modification du mot de passe");
  333. header("Location: /user-" . $_input["id"] .".html");
  334. exit();
  335. }
  336. }
  337. if(self::getMyGoogleAuthenticator($_input["id"]) == NULL){
  338. db::query("UPDATE " . DB_T_USER . " SET googleAuthenticatorSecret = :googleAuthenticatorSecret WHERE id = :id");
  339. db::bind(':googleAuthenticatorSecret', googleAuthenticator::createSecret());
  340. db::bind(':id', $_input["id"]);
  341. try {
  342. db::execute();
  343. } catch (Exception $ex) {
  344. alert::recError("Erreur lors de la création du token de Google Authenticator");
  345. header("Location: /user-" . $_input["id"] .".html");
  346. exit();
  347. }
  348. }
  349. $tags = tags::textToId($_input["tags"], 1);
  350. self::addTags($_input["id"], $tags);
  351. db::query("UPDATE " . DB_T_USER . " SET
  352. email = :email,
  353. prenom = :prenom,
  354. nom = :nom,
  355. id_type = :id_type,
  356. googleAuthenticator = :googleAuthenticator,
  357. actif = :actif
  358. WHERE id = :id");
  359. db::bind(':email', $_input["email"]);
  360. db::bind(':prenom', $_input["prenom"]);
  361. db::bind(':nom', $_input["nom"]);
  362. db::bind(':googleAuthenticator', $_input["googleAuthenticator"]);
  363. db::bind(':id_type', $_input["id_type"]);
  364. db::bind(':actif', $_input["actif"]);
  365. db::bind(':id', $_input["id"]);
  366. try {
  367. db::execute();
  368. alert::recSuccess("La modification a bien été prise en compte");
  369. } catch (Exception $ex) {
  370. alert::recError("Erreur lors de la modification de l'utilisateur");
  371. header("Location: /user-" . $_input["id"] . ".html");
  372. exit();
  373. }
  374. }
  375. /**
  376. * Récupère les tags associés à un utilisateur.
  377. *
  378. * @param float $_idUser Identifiant de l'utilisateur.
  379. * @return string|null Liste des tags sous forme de chaîne ou NULL si aucun tag.
  380. */
  381. static public function getTags(float $_idUser){
  382. db::query("SELECT "
  383. . "" . DB_T_TAGS . ".label "
  384. . "FROM " . DB_T_USER_TAGS . " "
  385. . "INNER JOIN " . DB_T_TAGS . " ON " . DB_T_TAGS . ".id = " . DB_T_USER_TAGS . ".id_tags "
  386. . "WHERE " . DB_T_USER_TAGS . ".id_user = :id "
  387. . "ORDER BY " . DB_T_USER_TAGS . ".creer");
  388. db::bind(':id', $_idUser);
  389. $tmp = db::resultset();
  390. if(isset($tmp[0])){
  391. $return = NULL;
  392. foreach ($tmp as $value) {
  393. $return .= $value["label"].",";
  394. }
  395. $return = substr($return, 0, -1);
  396. return $return;
  397. } else {
  398. return NULL;
  399. }
  400. }
  401. /**
  402. * Récupère les identifiants des tags associés à un utilisateur.
  403. *
  404. * @param float $_idUser Identifiant de l'utilisateur.
  405. * @return array|null Liste des identifiants des tags ou NULL si aucun tag.
  406. */
  407. static public function getIdTags(float $_idUser){
  408. db::query("SELECT "
  409. . "" . DB_T_USER_TAGS . ".id_tags "
  410. . "FROM " . DB_T_USER_TAGS . " "
  411. . "WHERE " . DB_T_USER_TAGS . ".id_user = :id "
  412. . "ORDER BY " . DB_T_USER_TAGS . ".creer");
  413. db::bind(':id', $_idUser);
  414. $tmp = db::resultset();
  415. if(isset($tmp[0])){
  416. $return = [];
  417. foreach ($tmp as $value) {
  418. $return[] = $value["id_tags"];
  419. }
  420. return $return;
  421. } else {
  422. return NULL;
  423. }
  424. }
  425. /**
  426. * Ajoute des tags à un utilisateur.
  427. *
  428. * @param float $_idUser Identifiant de l'utilisateur.
  429. * @param string|null $_tags Liste des tags sous forme de chaîne (séparés par des virgules).
  430. * @return bool TRUE si les tags sont ajoutés avec succès, FALSE en cas d'échec.
  431. */
  432. private static function addTags(float $_idUser, ?string $_tags = NULL)
  433. {
  434. db::query("DELETE FROM " . DB_T_USER_TAGS . " WHERE id_user = :id_user");
  435. db::bind(':id_user', $_idUser);
  436. db::execute();
  437. if($_tags != NULL){
  438. $tags = explode(",", $_tags);
  439. $sqlMaj = "";
  440. foreach ($tags as $tag) {
  441. $sqlMaj .= " (:id_user, ".$tag."),";
  442. }
  443. $sqlMaj = substr($sqlMaj, 0, -1);
  444. db::query("INSERT INTO " . DB_T_USER_TAGS . " (id_user, id_tags) VALUES" . $sqlMaj);
  445. db::bind(':id_user', $_idUser);
  446. try {
  447. db::execute();
  448. return TRUE;
  449. } catch (Exception $ex) {
  450. return FALSE;
  451. }
  452. }
  453. }
  454. /**
  455. * Marque un utilisateur comme supprimé.
  456. *
  457. * @param int $_id Identifiant de l'utilisateur.
  458. */
  459. public static function deleteUser(int $_id){
  460. db::query("UPDATE " . DB_T_USER . " SET deleted = 1 WHERE id = :id");
  461. db::bind(':id', $_id);
  462. try {
  463. db::execute();
  464. } catch (Exception $ex) {
  465. alert::recError("Erreur lors de la suppression");
  466. header("Location: /user-" . $_id .".html");
  467. exit();
  468. }
  469. }
  470. /**
  471. * Restaure un utilisateur précédemment supprimé.
  472. *
  473. * @param int $_id Identifiant de l'utilisateur.
  474. */
  475. public static function restoreUser(int $_id){
  476. db::query("UPDATE " . DB_T_USER . " SET deleted = 0 WHERE id = :id");
  477. db::bind(':id', $_id);
  478. try {
  479. db::execute();
  480. } catch (Exception $ex) {
  481. alert::recError("Erreur lors de la restauration");
  482. header("Location: /user-" . $_id .".html");
  483. exit();
  484. }
  485. }
  486. /**
  487. * Vérifie si l'utilisateur a activé la double authentification.
  488. *
  489. * @return bool TRUE si la double authentification est activée, FALSE sinon.
  490. */
  491. static public function checkSecur(){
  492. db::query("SELECT googleAuthenticator FROM " . DB_T_USER . " WHERE id = :id");
  493. db::bind(':id', session::getId());
  494. return db::single()["googleAuthenticator"] == 1 ? TRUE : FALSE;
  495. }
  496. /**
  497. * Affiche un message de sécurité si la double authentification n'est pas activée.
  498. */
  499. static public function printIsSecur(){
  500. if(ALERT_AUTHENTICATOR == TRUE){
  501. $_SESSION["CALLOUT"] ??= 0;
  502. if(self::checkSecur() == FALSE AND $_SESSION["CALLOUT"] < NB_ALERT_AUTHENTICATOR){
  503. $callout = [
  504. "type" => "danger",
  505. "size" => "tiny",
  506. "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>.",
  507. ];
  508. callout::print($callout);
  509. $_SESSION["CALLOUT"]++;
  510. }
  511. }
  512. }
  513. }