Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active November 16, 2022 23:36
Show Gist options
  • Save dcomartin/b0fa1885e30c02dcca2c37f069cdc638 to your computer and use it in GitHub Desktop.
Save dcomartin/b0fa1885e30c02dcca2c37f069cdc638 to your computer and use it in GitHub Desktop.
public class LoginModel : PageModel
{
// Code Omitted
[BindProperty]
public InputModel Input { get; set; }
public async Task<IActionResult> OnPostAsync(string? returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, false, true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
await TransferAnonymousBasketToUserAsync(Input.Email);
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
return Page();
}
private async Task TransferAnonymousBasketToUserAsync(string userName)
{
if (Request.Cookies.ContainsKey(Constants.BASKET_COOKIENAME))
{
var anonymousId = Request.Cookies[Constants.BASKET_COOKIENAME];
if (Guid.TryParse(anonymousId, out var _))
{
await _basketService.TransferBasketAsync(new Username(anonymousId), new Username(userName));
}
Response.Cookies.Delete(Constants.BASKET_COOKIENAME);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment