裕隆城折扣合作@中興低碳 折扣報表
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

134 wiersze
3.4KB

  1. using System.Diagnostics;
  2. using Microsoft.AspNetCore.Mvc;
  3. using CouponReport.Models;
  4. using Microsoft.AspNetCore.Authentication.Cookies;
  5. using Microsoft.AspNetCore.Authentication.OAuth;
  6. using Microsoft.AspNetCore.Authentication;
  7. using Microsoft.Extensions.Options;
  8. using System.Security.Claims;
  9. using System.Text.Json;
  10. using System.Text;
  11. using LaneFlowReport.Options;
  12. using LaneFlowReport.Models;
  13. namespace CouponReport.Controllers;
  14. public class HomeController : Controller
  15. {
  16. private readonly ILogger<HomeController> _logger;
  17. private readonly IHttpClientFactory _httpClientFactory;
  18. private readonly IOptions<OauthOption> _oauthOption;
  19. public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory, IOptions<OauthOption> oauthOption)
  20. {
  21. _logger = logger;
  22. _httpClientFactory = httpClientFactory;
  23. _oauthOption = oauthOption;
  24. }
  25. public IActionResult Index()
  26. {
  27. ViewBag.OauthUrl = _oauthOption.Value.ParkingOAuthUrl;
  28. return View(new LoginViewModel());
  29. }
  30. [HttpPost]
  31. public async Task<IActionResult> Index(LoginViewModel model)
  32. {
  33. ViewBag.OauthUrl = _oauthOption.Value.ParkingOAuthUrl;
  34. if (ModelState.IsValid)
  35. {
  36. if (await ValidateCredentialsAsync(model))
  37. {
  38. var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[]
  39. {
  40. new Claim(ClaimTypes.Name, model.Username),
  41. new Claim(ClaimTypes.Role, "Report"),
  42. }, "Cookies"));
  43. var authProperties = new AuthenticationProperties
  44. {
  45. IsPersistent = false
  46. };
  47. await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
  48. new ClaimsPrincipal(claimsPrincipal), authProperties);
  49. return RedirectToAction("Index", "Report", new { });
  50. }
  51. else
  52. {
  53. ModelState.AddModelError(string.Empty, "登入失敗!");
  54. model.Password = "";
  55. }
  56. }
  57. return View(model);
  58. }
  59. //驗證帳號
  60. private async Task<bool> ValidateCredentialsAsync(LoginViewModel model)
  61. {
  62. var client = _httpClientFactory.CreateClient();
  63. var endPoint = _oauthOption.Value.ParkingLoginUrl;
  64. var data = new
  65. {
  66. userNameOrEmailAddress = model.Username,
  67. password = model.Password,
  68. tenancyName = "Altob"
  69. };
  70. var json = JsonSerializer.Serialize(data);
  71. var content = new StringContent(json, Encoding.UTF8, "application/json");
  72. try
  73. {
  74. var response = await client.PostAsync(endPoint, content);
  75. var responseString = await response.Content.ReadAsStringAsync();
  76. _logger.LogInformation($"API Response: {responseString}");
  77. if (response.IsSuccessStatusCode)
  78. {
  79. //var result = JsonSerializer.Deserialize<AuthenticationResult>(responseString);
  80. //if (result != null && result.StatusCode == 200 && result.Msg == "成功")
  81. //{
  82. return true;
  83. //}
  84. }
  85. else
  86. {
  87. return false;
  88. }
  89. }
  90. catch (Exception ex)
  91. {
  92. _logger.LogError(ex, "驗證有誤");
  93. }
  94. return false;
  95. }
  96. //登出
  97. [HttpPost]
  98. [ValidateAntiForgeryToken]
  99. public async Task<IActionResult> Logout()
  100. {
  101. await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
  102. HttpContext.Session.Clear();
  103. return RedirectToAction("Index", "Home");
  104. }
  105. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  106. public IActionResult Error()
  107. {
  108. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  109. }
  110. public class AuthenticationResult
  111. {
  112. public string Msg { get; set; }
  113. public int StatusCode { get; set; }
  114. }
  115. }