裕隆城折扣合作@中興低碳 折扣報表
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

140 行
3.5KB

  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. //如果已經登入,直接導向報表頁面
  28. if (User.Identity?.IsAuthenticated == true)
  29. {
  30. return RedirectToAction("Index", "Report");
  31. }
  32. ViewBag.OauthUrl = _oauthOption.Value.ParkingOAuthUrl;
  33. return View(new LoginViewModel());
  34. }
  35. [HttpPost]
  36. public async Task<IActionResult> Index(LoginViewModel model)
  37. {
  38. ViewBag.OauthUrl = _oauthOption.Value.ParkingOAuthUrl;
  39. if (ModelState.IsValid)
  40. {
  41. if (await ValidateCredentialsAsync(model))
  42. {
  43. var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[]
  44. {
  45. new Claim(ClaimTypes.Name, model.Username),
  46. new Claim(ClaimTypes.Role, "Report"),
  47. }, "Cookies"));
  48. var authProperties = new AuthenticationProperties
  49. {
  50. IsPersistent = false
  51. };
  52. await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
  53. new ClaimsPrincipal(claimsPrincipal), authProperties);
  54. return RedirectToAction("Index", "Report", new { });
  55. }
  56. else
  57. {
  58. ModelState.AddModelError(string.Empty, "登入失敗!");
  59. model.Password = "";
  60. }
  61. }
  62. return View(model);
  63. }
  64. //驗證帳號
  65. private async Task<bool> ValidateCredentialsAsync(LoginViewModel model)
  66. {
  67. var client = _httpClientFactory.CreateClient();
  68. var endPoint = _oauthOption.Value.ParkingLoginUrl;
  69. var data = new
  70. {
  71. userNameOrEmailAddress = model.Username,
  72. password = model.Password,
  73. tenancyName = "Altob"
  74. };
  75. var json = JsonSerializer.Serialize(data);
  76. var content = new StringContent(json, Encoding.UTF8, "application/json");
  77. try
  78. {
  79. var response = await client.PostAsync(endPoint, content);
  80. var responseString = await response.Content.ReadAsStringAsync();
  81. _logger.LogInformation($"API Response: {responseString}");
  82. if (response.IsSuccessStatusCode)
  83. {
  84. //var result = JsonSerializer.Deserialize<AuthenticationResult>(responseString);
  85. //if (result != null && result.StatusCode == 200 && result.Msg == "成功")
  86. //{
  87. return true;
  88. //}
  89. }
  90. else
  91. {
  92. return false;
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. _logger.LogError(ex, "驗證有誤");
  98. }
  99. return false;
  100. }
  101. //登出
  102. [HttpPost]
  103. [ValidateAntiForgeryToken]
  104. public async Task<IActionResult> Logout()
  105. {
  106. await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
  107. HttpContext.Session.Clear();
  108. return RedirectToAction("Index", "Home");
  109. }
  110. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  111. public IActionResult Error()
  112. {
  113. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  114. }
  115. public class AuthenticationResult
  116. {
  117. public string Msg { get; set; }
  118. public int StatusCode { get; set; }
  119. }
  120. }