BaseController.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using log4net;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using SicboSub.Web.Helpers;
  5. using System.Security.Cryptography;
  6. namespace SicboSub.Web.Controllers
  7. {
  8. public class BaseController : Controller
  9. {
  10. protected static readonly ILog log = LogManager.GetLogger(typeof(BaseController));
  11. /// <summary>
  12. /// Generate random auth ID
  13. /// </summary>
  14. private string GenerateAuthId()
  15. {
  16. #pragma warning disable SYSLIB0023
  17. using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
  18. {
  19. byte[] tokenData = new byte[32];
  20. rng.GetBytes(tokenData);
  21. return Convert.ToBase64String(tokenData);
  22. }
  23. #pragma warning restore SYSLIB0023
  24. }
  25. /// <summary>
  26. /// Tạo auth token và lưu vào Session + Cookie
  27. /// </summary>
  28. protected void CreateAuthToken()
  29. {
  30. string authId = GenerateAuthId();
  31. HttpContext.Session.SetString("AuthorizationCookieId", authId);
  32. CookieOptions options = new CookieOptions()
  33. {
  34. Expires = DateTime.Now.AddMinutes(60)
  35. };
  36. HttpContext.Response.Cookies.Append("AuthorizationCookie", authId, options);
  37. }
  38. /// <summary>
  39. /// Kiểm tra auth token hợp lệ
  40. /// </summary>
  41. protected bool CheckAuthToken()
  42. {
  43. string? cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
  44. string? sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
  45. if (cookieValue == null || sessionValue == null || cookieValue != sessionValue)
  46. {
  47. return false;
  48. }
  49. return true;
  50. }
  51. /// <summary>
  52. /// Xóa cache/session/cookies
  53. /// </summary>
  54. protected bool ClearCache()
  55. {
  56. HttpContext.Session.Clear();
  57. foreach (var cookieKey in HttpContext.Request.Cookies.Keys)
  58. {
  59. HttpContext.Response.Cookies.Delete(cookieKey);
  60. }
  61. return true;
  62. }
  63. /// <summary>
  64. /// Check đã đăng nhập chưa (dựa vào token trong Session)
  65. /// </summary>
  66. protected bool IsAuthenticated()
  67. {
  68. var token = HttpContext.Session.GetComplexData<string>("token");
  69. return !string.IsNullOrEmpty(token);
  70. }
  71. /// <summary>
  72. /// Lấy MSISDN từ Session
  73. /// </summary>
  74. protected string? GetMsisdn()
  75. {
  76. return HttpContext.Session.GetComplexData<string>("msisdn");
  77. }
  78. /// <summary>
  79. /// Lấy token từ Session
  80. /// </summary>
  81. protected string? GetToken()
  82. {
  83. return HttpContext.Session.GetComplexData<string>("token");
  84. }
  85. /// <summary>
  86. /// Lấy ngôn ngữ từ Session
  87. /// </summary>
  88. protected string GetLanguage()
  89. {
  90. var lang = HttpContext.Session.GetComplexData<string>("culture") ?? "ht";
  91. HttpContext.Session.SetComplexData("culture", lang);
  92. return lang;
  93. }
  94. /// <summary>
  95. /// Set ngôn ngữ
  96. /// </summary>
  97. protected void SetLanguage(string lang)
  98. {
  99. HttpContext.Session.SetComplexData("culture", lang);
  100. }
  101. /// <summary>
  102. /// Redirect đến URL khi chưa đăng nhập
  103. /// Nếu không có RedirectUrl trong config thì về trang chủ Index
  104. /// </summary>
  105. protected IActionResult RedirectToLogin(IConfiguration configuration)
  106. {
  107. var redirectUrl = configuration.GetSection("RedirectUrl").Value;
  108. if (!string.IsNullOrEmpty(redirectUrl))
  109. {
  110. // Redirect ra URL external
  111. return Redirect(redirectUrl);
  112. }
  113. else
  114. {
  115. // Redirect về Index
  116. return RedirectToAction("Index", "Home");
  117. }
  118. }
  119. /// <summary>
  120. /// Check authentication - nếu chưa login thì redirect
  121. /// Dùng trong các action yêu cầu đăng nhập
  122. /// </summary>
  123. protected IActionResult? CheckAndRedirectIfNotAuthenticated(IConfiguration configuration)
  124. {
  125. if (!IsAuthenticated())
  126. {
  127. log.Warn("User not authenticated, redirecting...");
  128. return RedirectToLogin(configuration);
  129. }
  130. return null; // Đã đăng nhập, tiếp tục
  131. }
  132. }
  133. }