UtilisateurConnecteFactory.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.DirectoryServices;
  4. using System.Linq;
  5. using System.Security.Principal;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. namespace CD67.FicheCollege.MVC.Internal
  9. {
  10. public static class UtilisateurConnecteFactory
  11. {
  12. /// <summary>
  13. /// Retourne un objet UtilisateurConnecté avec les informations pronvenant de l'AD :
  14. /// nom , prenom , libellé (displayname), email , login, employéID (AstreRH), GUID, SID
  15. /// Une fois récupéré, les valeurs sont stockées en variable de session, et ne seront récupérées à nouveau depuis l'AD que si nécessaire
  16. /// </summary>
  17. /// <returns>L'utilisateur connecté</returns>
  18. public static Models.UtilisateurConnecte getUtilisateurConnecte()
  19. {
  20. //On récupère l'utilisateur depuis le cache de session
  21. Models.UtilisateurConnecte utilisateurConnecte = HttpContext.Current.Session["UtilisateurConnecte"] as Models.UtilisateurConnecte;
  22. //S'il est vide, on le met à jour
  23. if (utilisateurConnecte == null)
  24. {
  25. try
  26. {
  27. DirectoryEntry userEntry = getUserEntry();
  28. utilisateurConnecte = new Models.UtilisateurConnecte()
  29. {
  30. nom = userEntry.Properties["sn"].Value.ToString(),
  31. prenom = userEntry.Properties["givenName"].Value.ToString(),
  32. libelle = userEntry.Properties["displayName"].Value.ToString(),
  33. email = userEntry.Properties["mail"].Value.ToString(),
  34. login = userEntry.Properties["sAMAccountName"].Value.ToString(),
  35. employeeID = userEntry.Properties["employeeID"].Value == null ? (int?)null : int.Parse(userEntry.Properties["employeeID"].Value.ToString()),
  36. guid = userEntry.Properties["objectGUID"].Value == null ? (Guid?)null : new Guid((byte[])userEntry.Properties["objectGUID"].Value),
  37. sid = new SecurityIdentifier((byte[])userEntry.Properties["objectSid"].Value, 0).ToString(),
  38. structure = String.Join(@"\", getOUs(userEntry))
  39. };
  40. HttpContext.Current.Session["UtilisateurConnecte"] = utilisateurConnecte;
  41. }
  42. catch (Exception ex)
  43. {
  44. throw new Exception("Erreur lors de l'interrogation AD", ex);
  45. }
  46. }
  47. return utilisateurConnecte;
  48. }
  49. /// <summary>
  50. /// Retourne l'entrée dans l'AD de l'utilisateur courant.
  51. /// Exemple d'accès aux propriétés : userEntry.Properties["givenName"].Value
  52. /// </summary>
  53. /// <returns>Entrée utilisateur</returns>
  54. private static DirectoryEntry getUserEntry()
  55. {
  56. try
  57. {
  58. string login = HttpContext.Current.User.Identity.Name.ToLower().Replace("cg67\\", "");
  59. if (login == null) throw new Exception("Impossible de récupérer le login de l'utilisateur courant.");
  60. DirectoryEntry ldap = new DirectoryEntry("LDAP://CG67.fr/OU=Organisation,dc=CG67,dc=fr", "LectureAD", "Adlecture!");
  61. DirectorySearcher searcher = new DirectorySearcher(ldap);
  62. searcher.Filter = $"(sAMAccountName={login})";
  63. SearchResult result = searcher.FindOne();
  64. DirectoryEntry userEntry = result.GetDirectoryEntry();
  65. return userEntry;
  66. }
  67. catch (NullReferenceException ex)
  68. {
  69. throw new Exception("Le nom d'utilisateur courant n'a pas été retrouvé dans l'AD.", ex);
  70. }
  71. catch (Exception ex)
  72. {
  73. throw new Exception("Erreur dans la récupération des infos de l'utilisateur.", ex);
  74. }
  75. }
  76. public static List<string> getOUs(DirectoryEntry dirEntry)
  77. {
  78. List<string> res = Regex.Matches(dirEntry.Path, @"OU=[^,]+").Cast<Match>().Select(match => match.Value.Substring(3)).ToList();
  79. res.Reverse();
  80. res.RemoveAt(0); //Suppression du premier niveau "Organisation"
  81. return res;
  82. }
  83. }
  84. }