AccountController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Identity;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.AspNetCore.Mvc.Rendering;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.Extensions.Options;
  12. using Winsoft.GOV.XF.WXCore.Models;
  13. using Winsoft.GOV.XF.WXCore.Models.AccountViewModels;
  14. using Winsoft.GOV.XF.WXCore.Services;
  15. namespace Winsoft.GOV.XF.WXCore.Controllers
  16. {
  17. [Authorize]
  18. public class AccountController : Controller
  19. {
  20. private readonly UserManager<ApplicationUser> _userManager;
  21. private readonly SignInManager<ApplicationUser> _signInManager;
  22. private readonly IEmailSender _emailSender;
  23. private readonly ISmsSender _smsSender;
  24. private readonly ILogger _logger;
  25. private readonly string _externalCookieScheme;
  26. public AccountController(
  27. UserManager<ApplicationUser> userManager,
  28. SignInManager<ApplicationUser> signInManager,
  29. IOptions<IdentityCookieOptions> identityCookieOptions,
  30. IEmailSender emailSender,
  31. ISmsSender smsSender,
  32. ILoggerFactory loggerFactory)
  33. {
  34. _userManager = userManager;
  35. _signInManager = signInManager;
  36. _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
  37. _emailSender = emailSender;
  38. _smsSender = smsSender;
  39. _logger = loggerFactory.CreateLogger<AccountController>();
  40. }
  41. //
  42. // GET: /Account/Login
  43. [HttpGet]
  44. [AllowAnonymous]
  45. public async Task<IActionResult> Login(string returnUrl = null)
  46. {
  47. // Clear the existing external cookie to ensure a clean login process
  48. await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);
  49. ViewData["ReturnUrl"] = returnUrl;
  50. return View();
  51. }
  52. //
  53. // POST: /Account/Login
  54. [HttpPost]
  55. [AllowAnonymous]
  56. [ValidateAntiForgeryToken]
  57. public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
  58. {
  59. ViewData["ReturnUrl"] = returnUrl;
  60. if (ModelState.IsValid)
  61. {
  62. // This doesn't count login failures towards account lockout
  63. // To enable password failures to trigger account lockout, set lockoutOnFailure: true
  64. var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
  65. if (result.Succeeded)
  66. {
  67. _logger.LogInformation(1, "User logged in.");
  68. return RedirectToLocal(returnUrl);
  69. }
  70. if (result.RequiresTwoFactor)
  71. {
  72. return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  73. }
  74. if (result.IsLockedOut)
  75. {
  76. _logger.LogWarning(2, "User account locked out.");
  77. return View("Lockout");
  78. }
  79. else
  80. {
  81. ModelState.AddModelError(string.Empty, "Invalid login attempt.");
  82. return View(model);
  83. }
  84. }
  85. // If we got this far, something failed, redisplay form
  86. return View(model);
  87. }
  88. //
  89. // GET: /Account/Register
  90. [HttpGet]
  91. [AllowAnonymous]
  92. public IActionResult Register(string returnUrl = null)
  93. {
  94. ViewData["ReturnUrl"] = returnUrl;
  95. return View();
  96. }
  97. //
  98. // POST: /Account/Register
  99. [HttpPost]
  100. [AllowAnonymous]
  101. [ValidateAntiForgeryToken]
  102. public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
  103. {
  104. ViewData["ReturnUrl"] = returnUrl;
  105. if (ModelState.IsValid)
  106. {
  107. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  108. var result = await _userManager.CreateAsync(user, model.Password);
  109. if (result.Succeeded)
  110. {
  111. // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
  112. // Send an email with this link
  113. //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  114. //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
  115. //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
  116. // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
  117. await _signInManager.SignInAsync(user, isPersistent: false);
  118. _logger.LogInformation(3, "User created a new account with password.");
  119. return RedirectToLocal(returnUrl);
  120. }
  121. AddErrors(result);
  122. }
  123. // If we got this far, something failed, redisplay form
  124. return View(model);
  125. }
  126. //
  127. // POST: /Account/Logout
  128. [HttpPost]
  129. [ValidateAntiForgeryToken]
  130. public async Task<IActionResult> Logout()
  131. {
  132. await _signInManager.SignOutAsync();
  133. _logger.LogInformation(4, "User logged out.");
  134. return RedirectToAction(nameof(HomeController.Index), "Home");
  135. }
  136. //
  137. // POST: /Account/ExternalLogin
  138. [HttpPost]
  139. [AllowAnonymous]
  140. [ValidateAntiForgeryToken]
  141. public IActionResult ExternalLogin(string provider, string returnUrl = null)
  142. {
  143. // Request a redirect to the external login provider.
  144. var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { ReturnUrl = returnUrl });
  145. var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
  146. return Challenge(properties, provider);
  147. }
  148. //
  149. // GET: /Account/ExternalLoginCallback
  150. [HttpGet]
  151. [AllowAnonymous]
  152. public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
  153. {
  154. if (remoteError != null)
  155. {
  156. ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
  157. return View(nameof(Login));
  158. }
  159. var info = await _signInManager.GetExternalLoginInfoAsync();
  160. if (info == null)
  161. {
  162. return RedirectToAction(nameof(Login));
  163. }
  164. // Sign in the user with this external login provider if the user already has a login.
  165. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
  166. if (result.Succeeded)
  167. {
  168. _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
  169. return RedirectToLocal(returnUrl);
  170. }
  171. if (result.RequiresTwoFactor)
  172. {
  173. return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
  174. }
  175. if (result.IsLockedOut)
  176. {
  177. return View("Lockout");
  178. }
  179. else
  180. {
  181. // If the user does not have an account, then ask the user to create an account.
  182. ViewData["ReturnUrl"] = returnUrl;
  183. ViewData["LoginProvider"] = info.LoginProvider;
  184. var email = info.Principal.FindFirstValue(ClaimTypes.Email);
  185. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
  186. }
  187. }
  188. //
  189. // POST: /Account/ExternalLoginConfirmation
  190. [HttpPost]
  191. [AllowAnonymous]
  192. [ValidateAntiForgeryToken]
  193. public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
  194. {
  195. if (ModelState.IsValid)
  196. {
  197. // Get the information about the user from the external login provider
  198. var info = await _signInManager.GetExternalLoginInfoAsync();
  199. if (info == null)
  200. {
  201. return View("ExternalLoginFailure");
  202. }
  203. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  204. var result = await _userManager.CreateAsync(user);
  205. if (result.Succeeded)
  206. {
  207. result = await _userManager.AddLoginAsync(user, info);
  208. if (result.Succeeded)
  209. {
  210. await _signInManager.SignInAsync(user, isPersistent: false);
  211. _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
  212. return RedirectToLocal(returnUrl);
  213. }
  214. }
  215. AddErrors(result);
  216. }
  217. ViewData["ReturnUrl"] = returnUrl;
  218. return View(model);
  219. }
  220. // GET: /Account/ConfirmEmail
  221. [HttpGet]
  222. [AllowAnonymous]
  223. public async Task<IActionResult> ConfirmEmail(string userId, string code)
  224. {
  225. if (userId == null || code == null)
  226. {
  227. return View("Error");
  228. }
  229. var user = await _userManager.FindByIdAsync(userId);
  230. if (user == null)
  231. {
  232. return View("Error");
  233. }
  234. var result = await _userManager.ConfirmEmailAsync(user, code);
  235. return View(result.Succeeded ? "ConfirmEmail" : "Error");
  236. }
  237. //
  238. // GET: /Account/ForgotPassword
  239. [HttpGet]
  240. [AllowAnonymous]
  241. public IActionResult ForgotPassword()
  242. {
  243. return View();
  244. }
  245. //
  246. // POST: /Account/ForgotPassword
  247. [HttpPost]
  248. [AllowAnonymous]
  249. [ValidateAntiForgeryToken]
  250. public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
  251. {
  252. if (ModelState.IsValid)
  253. {
  254. var user = await _userManager.FindByEmailAsync(model.Email);
  255. if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
  256. {
  257. // Don't reveal that the user does not exist or is not confirmed
  258. return View("ForgotPasswordConfirmation");
  259. }
  260. // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
  261. // Send an email with this link
  262. //var code = await _userManager.GeneratePasswordResetTokenAsync(user);
  263. //var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
  264. //await _emailSender.SendEmailAsync(model.Email, "Reset Password",
  265. // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
  266. //return View("ForgotPasswordConfirmation");
  267. }
  268. // If we got this far, something failed, redisplay form
  269. return View(model);
  270. }
  271. //
  272. // GET: /Account/ForgotPasswordConfirmation
  273. [HttpGet]
  274. [AllowAnonymous]
  275. public IActionResult ForgotPasswordConfirmation()
  276. {
  277. return View();
  278. }
  279. //
  280. // GET: /Account/ResetPassword
  281. [HttpGet]
  282. [AllowAnonymous]
  283. public IActionResult ResetPassword(string code = null)
  284. {
  285. return code == null ? View("Error") : View();
  286. }
  287. //
  288. // POST: /Account/ResetPassword
  289. [HttpPost]
  290. [AllowAnonymous]
  291. [ValidateAntiForgeryToken]
  292. public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
  293. {
  294. if (!ModelState.IsValid)
  295. {
  296. return View(model);
  297. }
  298. var user = await _userManager.FindByEmailAsync(model.Email);
  299. if (user == null)
  300. {
  301. // Don't reveal that the user does not exist
  302. return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
  303. }
  304. var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
  305. if (result.Succeeded)
  306. {
  307. return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
  308. }
  309. AddErrors(result);
  310. return View();
  311. }
  312. //
  313. // GET: /Account/ResetPasswordConfirmation
  314. [HttpGet]
  315. [AllowAnonymous]
  316. public IActionResult ResetPasswordConfirmation()
  317. {
  318. return View();
  319. }
  320. //
  321. // GET: /Account/SendCode
  322. [HttpGet]
  323. [AllowAnonymous]
  324. public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
  325. {
  326. var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
  327. if (user == null)
  328. {
  329. return View("Error");
  330. }
  331. var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
  332. var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
  333. return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
  334. }
  335. //
  336. // POST: /Account/SendCode
  337. [HttpPost]
  338. [AllowAnonymous]
  339. [ValidateAntiForgeryToken]
  340. public async Task<IActionResult> SendCode(SendCodeViewModel model)
  341. {
  342. if (!ModelState.IsValid)
  343. {
  344. return View();
  345. }
  346. var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
  347. if (user == null)
  348. {
  349. return View("Error");
  350. }
  351. // Generate the token and send it
  352. var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
  353. if (string.IsNullOrWhiteSpace(code))
  354. {
  355. return View("Error");
  356. }
  357. var message = "Your security code is: " + code;
  358. if (model.SelectedProvider == "Email")
  359. {
  360. await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
  361. }
  362. else if (model.SelectedProvider == "Phone")
  363. {
  364. await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
  365. }
  366. return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
  367. }
  368. //
  369. // GET: /Account/VerifyCode
  370. [HttpGet]
  371. [AllowAnonymous]
  372. public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
  373. {
  374. // Require that the user has already logged in via username/password or external login
  375. var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
  376. if (user == null)
  377. {
  378. return View("Error");
  379. }
  380. return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
  381. }
  382. //
  383. // POST: /Account/VerifyCode
  384. [HttpPost]
  385. [AllowAnonymous]
  386. [ValidateAntiForgeryToken]
  387. public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
  388. {
  389. if (!ModelState.IsValid)
  390. {
  391. return View(model);
  392. }
  393. // The following code protects for brute force attacks against the two factor codes.
  394. // If a user enters incorrect codes for a specified amount of time then the user account
  395. // will be locked out for a specified amount of time.
  396. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
  397. if (result.Succeeded)
  398. {
  399. return RedirectToLocal(model.ReturnUrl);
  400. }
  401. if (result.IsLockedOut)
  402. {
  403. _logger.LogWarning(7, "User account locked out.");
  404. return View("Lockout");
  405. }
  406. else
  407. {
  408. ModelState.AddModelError(string.Empty, "Invalid code.");
  409. return View(model);
  410. }
  411. }
  412. //
  413. // GET /Account/AccessDenied
  414. [HttpGet]
  415. public IActionResult AccessDenied()
  416. {
  417. return View();
  418. }
  419. #region Helpers
  420. private void AddErrors(IdentityResult result)
  421. {
  422. foreach (var error in result.Errors)
  423. {
  424. ModelState.AddModelError(string.Empty, error.Description);
  425. }
  426. }
  427. private IActionResult RedirectToLocal(string returnUrl)
  428. {
  429. if (Url.IsLocalUrl(returnUrl))
  430. {
  431. return Redirect(returnUrl);
  432. }
  433. else
  434. {
  435. return RedirectToAction(nameof(HomeController.Index), "Home");
  436. }
  437. }
  438. #endregion
  439. }
  440. }