/// <summary> /// Login passed user /// </summary> /// <param name="customer">User to login</param> /// <param name="returnUrl">URL to which the user will return after authentication</param> /// <param name="isPersist">Is remember me</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the result of an authentication /// </returns> public virtual async Task <IActionResult> SignInCustomerAsync(Customer customer, string returnUrl, bool isPersist = false) { var currentCustomer = await _workContext.GetCurrentCustomerAsync(); if (currentCustomer?.Id != customer.Id) { //migrate shopping cart await _shoppingCartService.MigrateShoppingCartAsync(currentCustomer, customer, true); await _workContext.SetCurrentCustomerAsync(customer); } //sign in new customer await _authenticationService.SignInAsync(customer, isPersist); //raise event await _eventPublisher.PublishAsync(new CustomerLoggedinEvent(customer)); //activity log await _customerActivityService.InsertActivityAsync(customer, "PublicStore.Login", await _localizationService.GetResourceAsync("ActivityLog.PublicStore.Login"), customer); var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext); //redirect to the return URL if it's specified if (!string.IsNullOrEmpty(returnUrl) && urlHelper.IsLocalUrl(returnUrl)) { return(new RedirectResult(returnUrl)); } return(new RedirectToRouteResult("Homepage", null)); }
private async Task attachUserToContext(HttpContext context, ICustomerService userService, IWorkContext workContext, string token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Key); tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later) ClockSkew = TimeSpan.Zero }, out SecurityToken validatedToken); var jwtToken = (JwtSecurityToken)validatedToken; var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "UserId").Value); // attach user to context on successful jwt validation context.Items["User"] = await userService.GetCustomerByIdAsync(userId); await workContext.SetCurrentCustomerAsync(await userService.GetCustomerByIdAsync(userId)); } catch { // do nothing if jwt validation fails // user is not attached to context so request won't have access to secure routes } }
public async Task <IActionResult> Login([FromBody] LoginApiModel model) { if (!ModelState.IsValid) { return(Ok(new { success = false, message = GetModelErrors(ModelState) })); } var loginResult = await _customerRegistrationService.ValidateCustomerAsync(model.Email, model.Password); switch (loginResult) { case CustomerLoginResults.Successful: { var customer = await _customerService.GetCustomerByEmailAsync(model.Email); if (customer == null) { return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Customer.Not.Found") })); } customer.PushToken = model.PushToken; await _customerService.UpdateCustomerAsync(customer); await _workContext.SetCurrentCustomerAsync(customer); //migrate shopping cart await _shoppingCartService.MigrateShoppingCartAsync(await _workContext.GetCurrentCustomerAsync(), customer, true); //sign in new customer await _authenticationService.SignInAsync(customer, false); var jwt = new JwtService(_config); var token = jwt.GenerateSecurityToken(customer.Email, customer.Id); var shippingAddress = customer.ShippingAddressId.HasValue ? await _addressService.GetAddressByIdAsync(customer.ShippingAddressId.Value) : null; var firstName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FirstNameAttribute); var lastName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.LastNameAttribute); return(Ok(new { success = true, message = await _localizationService.GetResourceAsync("Customer.Login.Successfully"), token, pushToken = customer.PushToken, shippingAddress, firstName, lastName, RemindMeNotification = customer.RemindMeNotification, RateReminderNotification = customer.RateReminderNotification, OrderStatusNotification = customer.OrderStatusNotification, avatar = await _pictureService.GetPictureUrlAsync(await _genericAttributeService.GetAttributeAsync <int>(customer, NopCustomerDefaults.AvatarPictureIdAttribute), _mediaSettings.AvatarPictureSize, true) })); } case CustomerLoginResults.CustomerNotExist: return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.CustomerNotExist") })); case CustomerLoginResults.Deleted: return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.Deleted") })); case CustomerLoginResults.NotActive: return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.NotActive") })); case CustomerLoginResults.NotRegistered: return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.NotRegistered") })); case CustomerLoginResults.LockedOut: return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.LockedOut") })); case CustomerLoginResults.WrongPassword: default: return(Ok(new { success = false, message = await _localizationService.GetResourceAsync("Account.Login.WrongCredentials") })); } }