public async Task EnsureOnlyRegisteredCustomersCanLogin()
        {
            var result = await _customerRegistrationService.ValidateCustomerAsync(NopTestsDefaults.AdminEmail, NopTestsDefaults.AdminPassword);

            result.Should().Be(CustomerLoginResults.Successful);

            var customer = await CreateCustomerAsync(PasswordFormat.Clear, false);

            result = await _customerRegistrationService.ValidateCustomerAsync("*****@*****.**", "password");
            await DeleteCustomerAsync(customer);

            result.Should().Be(CustomerLoginResults.NotRegistered);
        }
        public async Task <IActionResult> Login(LoginModel model, string returnUrl, bool captchaValid)
        {
            TempData["errors"] = await _localizationService.GetResourceAsync("Account.Login.Unsuccessful");

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage && !captchaValid)
            {
                AddErrorMessage(await _localizationService.GetResourceAsync("Common.WrongCaptchaMessage"));
                return(RedirectToAction("Display"));
            }

            if (ModelState.IsValid)
            {
                if (_customerSettings.UsernamesEnabled && model.Username != null)
                {
                    model.Username = model.Username.Trim();
                }
                var loginResult = await _customerRegistrationService.ValidateCustomerAsync(_customerSettings.UsernamesEnabled?model.Username : model.Email, model.Password);

                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    var customer = _customerSettings.UsernamesEnabled ? await _customerService.GetCustomerByUsernameAsync(model.Username) : await _customerService.GetCustomerByEmailAsync(model.Email);

                    //migrate shopping cart
                    await _shoppingCartService.MigrateShoppingCartAsync(await _workContext.GetCurrentCustomerAsync(), customer, true);

                    //sign in new customer
                    await _authenticationService.SignInAsync(customer, model.RememberMe);

                    //raise event
                    await _eventPublisher.PublishAsync(new CustomerLoggedinEvent(customer));

                    //activity log
                    await _customerActivityService.InsertActivityAsync("PublicStore.Login", await _localizationService.GetResourceAsync("ActivityLog.PublicStore.Login"), customer);

                    if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                    {
                        return(RedirectToRoute("HomePage"));
                    }

                    return(Redirect(returnUrl));
                }

                case CustomerLoginResults.CustomerNotExist:
                    AddErrorMessage(await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.CustomerNotExist"));
                    break;

                case CustomerLoginResults.Deleted:
                    AddErrorMessage(await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.Deleted"));
                    break;

                case CustomerLoginResults.NotActive:
                    AddErrorMessage(await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.NotActive"));
                    break;

                case CustomerLoginResults.NotRegistered:
                    AddErrorMessage(await _localizationService.GetResourceAsync("Account.Login.WrongCredentials.NotRegistered"));
                    break;

                case CustomerLoginResults.WrongPassword:
                default:
                    AddErrorMessage(await _localizationService.GetResourceAsync("Account.Login.WrongCredentials"));
                    break;
                }
            }

            //If we got this far, something failed, redirect to Display with error mesages in TempData
            return(RedirectToAction("Display"));
        }
        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") }));
            }
        }
예제 #4
0
        public async Task <IActionResult> SetStatus(string request)
        {
            // add a sequence number
            string email       = Request.Query["email"];
            string password    = Request.Query["password"];
            var    loginResult = await _customerRegistrationService.ValidateCustomerAsync(email, password);

            if (loginResult != CustomerLoginResults.Successful)
            {
                return(Forbid());
            }

            Customer apiCustomer = await _customerService.GetCustomerByEmailAsync(email);

            if (apiCustomer == null)
            {
                throw new NopException($"Unable to find customer with email {email}");
            }

            var adminCustomerRole = (await _customerService.GetCustomerRolesAsync(apiCustomer)).FirstOrDefault(cr => cr.SystemName == "Administrators");

            if (adminCustomerRole == null)
            {
                return(Forbid());
            }

            string statusId       = Request.Query["id"];
            string statusType     = Request.Query["statusType"];
            string statusValueStr = Request.Query["statusValue"];

            // update the chosen status
            bool   updateSuccess;
            string failureMessage = "403: Bad Request, ";

            int nopOrderId = -1;

            // id is in format <nopid>
            Int32.TryParse(statusId, out nopOrderId);

            // convert input status value -> int
            int statusValue = 0;

            if (statusType.Trim().ToLower() != "tracking")
            {
                statusValue = Int32.Parse(statusValueStr);
            }

            Order order = await _orderService.GetOrderByIdAsync(nopOrderId);

            if (order != null)
            {
                if (statusType.Trim().ToLower() == "order")
                {
                    // update order
                    updateSuccess = await UpdateOrderAsync(order, statusValue);

                    // failure message only used if update fails
                    // assign it every time in case of failure
                    failureMessage += $"status value {statusValueStr} not defined";
                }
                else if (statusType.Trim().ToLower() == "shipping")
                {
                    // update shipping
                    updateSuccess = await UpdateShippingAsync(order, statusValue);

                    failureMessage += $"status value {statusValueStr} not defined";
                }
                else if (statusType.Trim().ToLower() == "payment")
                {
                    // update payment status
                    updateSuccess = await UpdatePaymentAsync(order, statusValue);

                    failureMessage += $"status value {statusValueStr} not defined";
                }
                else if (statusType.Trim().ToLower() == "tracking")
                {
                    // update payment status
                    updateSuccess = await UpdateTrackingAsync(order, statusValueStr, Request.Query["itemSku"]);

                    failureMessage += $"status value {statusValueStr} not defined";
                }
                else
                {
                    updateSuccess   = false;
                    failureMessage += $"type {statusType} not defined";
                }
            }
            else
            {
                updateSuccess   = false;
                failureMessage += statusId + " is not a valid order id in nopcommerce";
            }

            // choose what to return to the sender
            if (updateSuccess)
            {
                return(Ok());
            }
            else
            {
                // if the update wasn't successful, throw 400 Bad Request
                return(new BadRequestObjectResult(failureMessage));
            }
        }
 private Task <CustomerLoginResults> LoginCustomerAsync(TokenRequest model)
 {
     return(_customerRegistrationService.ValidateCustomerAsync(model.Username, model.Password));
 }