public void Ensure_only_registered_customers_can_login()
        {
            var result = _customerRegistrationService.ValidateCustomer("*****@*****.**", "password");

            result.ShouldEqual(CustomerLoginResults.Successful);

            result = _customerRegistrationService.ValidateCustomer("*****@*****.**", "password");
            result.ShouldEqual(CustomerLoginResults.NotRegistered);
        }
Beispiel #2
0
        public void CanValidateClearPassword()
        {
            var customer = CreateCustomer(PasswordFormat.Clear);

            var result = _customerRegistrationService.ValidateCustomer("*****@*****.**", "password");
            DeleteCustomer(customer);

            result.Should().Be(CustomerLoginResults.Successful);
        }
Beispiel #3
0
        public void Ensure_only_registered_customers_can_login()
        {
            bool result = _customerRegistrationService.ValidateCustomer("*****@*****.**", "password");

            result.ShouldBeTrue();

            result = _customerRegistrationService.ValidateCustomer("*****@*****.**", "password");
            result.ShouldBeFalse();
        }
        public void Ensure_only_registered_customers_can_login()
        {
            Assert.AreEqual(
                CustomerLoginResults.Successful,
                _customerRegistrationService.ValidateCustomer("*****@*****.**", "password"));

            Assert.AreEqual(
                CustomerLoginResults.NotRegistered,
                _customerRegistrationService.ValidateCustomer("*****@*****.**", "password"));
        }
        public void EnsureOnlyRegisteredCustomersCanLogin()
        {
            var result = _customerRegistrationService.ValidateCustomer(NopTestsDefaults.AdminEmail, NopTestsDefaults.AdminPassword);

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

            var customer = CreateCustomer(PasswordFormat.Clear, false);

            result = _customerRegistrationService.ValidateCustomer("*****@*****.**", "password");
            DeleteCustomer(customer);

            result.Should().Be(CustomerLoginResults.NotRegistered);
        }
Beispiel #6
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_customerRegistrationService.ValidateCustomer(model.UserName, model.Password))
                {
                    var customer = _customerService.GetCustomerByUserName(model.UserName);

                    if (customer.TimeZoneId == null)
                    {
                        customer.TimeZoneId = DateTime.UtcNow.ToString();
                        _customerService.Update(customer);
                    }

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

                    return(RedirectToLocal(returnUrl));
                }
            }


            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return(View(model));
        }
Beispiel #7
0
        public virtual ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var loginResult =
                    _customerRegistrationService.ValidateCustomer(model.LoginName, model.Password);
                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    Customer customer = null;
                    switch (_customerSettings.CustomerAuthenticationType)
                    {
                    case AuthenticationType.Email:
                        customer = _customerService.GetCustomerByEmail(model.LoginName);
                        break;

                    case AuthenticationType.Username:
                        customer = _customerService.GetCustomerByUsername(model.LoginName);
                        break;

                    case AuthenticationType.UsernameOrEmail:
                        customer = _customerService.GetCustomerByUsernameOrEmail(model.LoginName);
                        break;
                    }

                    _authenticationService.SignIn(customer, model.RememberMe);

                    _eventPublisher.Publish(new CustomerLoggedinEvent(customer));

                    _customerActivityService.InsertActivity(customer, "Public.Login", _localizationService.GetResource("ActivityLog.Public.Login"));

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

                    return(Redirect(returnUrl));
                }

                case CustomerLoginResults.CustomerNotExist:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist"));
                    break;

                case CustomerLoginResults.NotActive:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotActive"));
                    break;

                case CustomerLoginResults.LockedOut:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut"));
                    break;

                case CustomerLoginResults.WrongPassword:
                default:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                    break;
                }
            }
            return(View(model));
        }
Beispiel #8
0
        private CustomerLoginResults LoginCustomer(TokenRequest model)
        {
            var loginResult = _customerRegistrationService
                              .ValidateCustomer(model.Email, model.Password);

            return(loginResult);
        }
Beispiel #9
0
        protected void CheckAccess(string usernameOrEmail, string userPassword)
        {
            //check whether web service plugin is installed
            var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName("Misc.WebServices");

            if (pluginDescriptor == null)
            {
                throw new ApplicationException("Web services plugin cannot be loaded");
            }
            if (!_pluginFinder.AuthenticateStore(pluginDescriptor, _storeContext.CurrentStore.Id))
            {
                throw new ApplicationException("Web services plugin is not available in this store");
            }

            if (_customerRegistrationService.ValidateCustomer(usernameOrEmail, userPassword) != CustomerLoginResults.Successful)
            {
                throw new ApplicationException("Not allowed");
            }

            var customer = _customerSettings.UsernamesEnabled ? _customerService.GetCustomerByUsername(usernameOrEmail) : _customerService.GetCustomerByEmail(usernameOrEmail);

            _workContext.CurrentCustomer = customer;
            _authenticationService.SignIn(customer, true);

            //valdiate whether we can access this web service
            if (!_permissionSettings.Authorize(WebServicePermissionProvider.AccessWebService))
            {
                throw new ApplicationException("Not allowed to access web service");
            }
        }
        public ActionResult Login(string Email, string Password)
        {
            //BienSoXe = BienSoXe + "@chonve.vn";
            var loginresult = _customerRegistrationService.ValidateCustomer(Email, Password);

            if (loginresult != CustomerLoginResults.Successful)
            {
                return(ErrorOccured("Tài khoản hoặc mật khẩu không đúng !"));
            }
            _customer = _customerService.GetCustomerByEmail(Email);

            //kiem tra co quyen ko
            if (!isRightAccess())
            {
                return(ErrorOccured("Bạn không có quyền vào chức năng này !"));
            }
            //kiem tra cac thong tin nha xe
            NhaXe currentNhaXe = _nhaxeService.GetNhaXeByCustommerId(currentCustomer.Id);

            if (currentNhaXe == null)
            {
                return(ErrorOccured("Không xác định nhà xe !"));
            }
            //luu nhat ky
            _customerActivityService.InsertActivity("PublicStore.Login", "Tài khoản nhà xe đăng nhập", currentCustomer);
            //lay thong tin van phong
            _nhanvien = _nhanvienService.GetByCustomerId(currentCustomer.Id);
            //OK, lay thong tin va truyen xuong client
            var loginInfo = new
            {
                Id         = currentCustomer.Id,
                NhaXeId    = currentNhaXe.Id,
                GuidId     = _settings.ApiToken,
                FullName   = currentCustomer.GetFullName(),
                TenNhaXe   = currentNhaXe.TenNhaXe,
                VanPhongId = _nhanvien.VanPhongID.GetValueOrDefault(0)
            };

            return(Successful(loginInfo));
        }
Beispiel #11
0
        public UserModel Authenticate(string username, string password)
        {
            //this code have to use after creating database
            var user = _customerRegistrationService.ValidateCustomer(username, password);

            //this is for Static User
            //var user = _users.SingleOrDefault(x => x.Username == username && x.Password == password);
            if (user == null)
            {
                ValidationMessages.MobileUserError = "Username or Password is Incorect";
                return(null);
            }
            //permissions
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMobileAdmin, user))
            {
                ValidationMessages.MobileUserError = "Unauthorise Access";
                return(null);
            }


            //// return null if user not found


            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var       token     = tokenHandler.CreateToken(tokenDescriptor);
            UserModel userModel = new UserModel();

            userModel.Token     = tokenHandler.WriteToken(token);
            userModel.Username  = user.Username;
            userModel.Password  = password;
            userModel.FirstName = user.BillingAddress.FirstName;
            userModel.LastName  = user.BillingAddress.LastName;
            userModel.Id        = user.Id;
            // remove password before returning

            return(userModel);
        }
Beispiel #12
0
        public OneCResponse IsLogin(string userName, string email, string password)
        {
            var response = new OneCResponse
            {
                Success = false
            };

            if (_customerSettings.UsernamesEnabled && userName != null)
            {
                userName = userName.Trim();
            }

            var loginResult = _customerRegistrationService.ValidateCustomer(_customerSettings.UsernamesEnabled ? userName : email, password);

            switch (loginResult)
            {
            case CustomerLoginResults.Successful:
                response.Success = true;
                break;

            case CustomerLoginResults.CustomerNotExist:
                response.Message = _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist");
                break;

            case CustomerLoginResults.Deleted:
                response.Message = _localizationService.GetResource("Account.Login.WrongCredentials.Deleted");
                break;

            case CustomerLoginResults.NotActive:
                response.Message = _localizationService.GetResource("Account.Login.WrongCredentials.NotActive");
                break;

            case CustomerLoginResults.NotRegistered:
                response.Message = _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered");
                break;

            case CustomerLoginResults.LockedOut:
                response.Message = _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut");
                break;

            case CustomerLoginResults.WrongPassword:
            default:
                response.Message = _localizationService.GetResource("Account.Login.WrongCredentials");
                break;
            }

            return(response);
        }
Beispiel #13
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            var loginResult = _customerRegistrationService.ValidateCustomer(model.Username, model.Password);

            switch (loginResult)
            {
            case CustomerLoginResults.Successful:
            {
                var customer = _customerService.GetCustomerByUsername(model.Username);

                _authenticationService.SignIn(customer, model.RememberMe);

                if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                {
                    return(RedirectToAction("Index", "Home"));
                }

                return(Redirect(returnUrl));
            }

            case CustomerLoginResults.CustomerNotExist:
                ModelState.AddModelError("", "用户不存在");
                break;

            case CustomerLoginResults.Deleted:
                ModelState.AddModelError("", "用户已删除");
                break;

            case CustomerLoginResults.NotActive:
                ModelState.AddModelError("", "用户未激活");
                break;

            case CustomerLoginResults.WrongPassword:
                ModelState.AddModelError("", "密码错误");
                break;

            default:
                ModelState.AddModelError("", "登录失败");
                break;
            }

            return(View(model));
        }
        public IActionResult LoginModal(LoginModel model)
        {
            try
            {
                ResponseModel response           = new ResponseModel();
                var           customerValidation = _customerRegistrationService.ValidateCustomer(model.Email, model.Password);

                switch (customerValidation)
                {
                case CustomerLoginResults.Successful:
                    var baseAR = _baseNopCustomerController.Login(model, "", true);
                    response.message = "Success";
                    return(Json(response));

                case CustomerLoginResults.WrongPassword:
                    response.message = "Wrong Password";
                    return(Json(response));

                case CustomerLoginResults.CustomerNotExist:
                    response.message = "Customer Not Exist";
                    return(Json(response));

                case CustomerLoginResults.NotRegistered:
                    response.message = "Customer Not Exist";
                    return(Json(response));

                default:
                    break;
                }

                response.message = "Failed";
                return(Json(response));
            }
            catch (Exception ex)
            {
                _logger.Error("Error in LoginModal", ex);
                ResponseModel response = new ResponseModel();
                response.status  = "failure";
                response.message = ex.Message;
                return(Json(response));
            }
        }
        public Task <LoginCustomerResponse> Handle(LoginCustomerCommand request, CancellationToken cancellationToken)
        {
            var isUserName     = !string.IsNullOrEmpty(request.Username);
            var passwordResult = _customerRegistrationService.ValidateCustomer(
                !isUserName ? request.Email : request.Username, request.Password);

            var response = new LoginCustomerResponse()
            {
                LoginResult = passwordResult,
            };

            if (passwordResult == CustomerLoginResults.Successful)
            {
                var customer      = isUserName ? _customerService.GetCustomerByUsername(request.Username) : _customerService.GetCustomerByEmail(request.Email);
                var customerRoles = _customerService.GetCustomerRoles(customer).Where(cr => cr.Active);
                response.Token = _jwtService.GenerateToken(customer, customerRoles);
                response.Roles.AddRange(customerRoles.Select(x => x.SystemName));
            }

            return(Task.FromResult(response));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //using (AuthRepository _repo = new AuthRepository())
            //{
            //    IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            //    if (user == null)
            //    {
            //        context.SetError("invalid_grant", "The user name or password is incorrect.");
            //        return;
            //    }
            //}

            var loginResult = _customerRegistrationService.ValidateCustomer(context.UserName.Trim(), context.Password);

            switch (loginResult)
            {
            case CustomerLoginResults.Successful:
            {
                Customer     customer = _customerService.GetCustomerByEmail(context.UserName);
                CustomerRole role     = _customerService.GetCustomerRoleById(customer.Id);



                //https://www.nopcommerce.com/boards/t/21617/how-to-check-if-the-user-has-a-role.aspx
                if (customer.IsVendor())
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim("sub", context.UserName));
                    identity.AddClaim(new Claim("role", "user"));

                    var props = new AuthenticationProperties(new Dictionary <string, string>
                        {
                            { "vendor_id", customer.VendorId.ToString() }
                        });

                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);

                    //context.Validated(identity);
                    return;
                }
                else
                {
                    context.SetError("invalid_grant", "Account.Login.WrongCredentials.NotVendor");
                    return;
                }
            }

            case CustomerLoginResults.CustomerNotExist:

                context.SetError("invalid_grant", "Account.Login.WrongCredentials.CustomerNotExist");
                return;

            case CustomerLoginResults.Deleted:
                context.SetError("invalid_grant", "Account.Login.WrongCredentials.Deleted");
                return;

            case CustomerLoginResults.NotActive:
                context.SetError("invalid_grant", "Account.Login.WrongCredentials.NotActive");
                return;

            case CustomerLoginResults.NotRegistered:
                context.SetError("invalid_grant", "Account.Login.WrongCredentials.NotRegistered");
                return;

            case CustomerLoginResults.LockedOut:
                context.SetError("invalid_grant", "Account.Login.WrongCredentials.LockedOut");
                return;

            case CustomerLoginResults.WrongPassword:
            default:
                context.SetError("invalid_grant", "Account.Login.WrongCredentials");
                return;
            }
        }
Beispiel #17
0
        public IActionResult SignIn(SignInPostModel model, string returnUrl, bool captchaValid)
        {
            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (ModelState.IsValid)
            {
                Customer customer    = null;
                var      loginResult = _customerRegistrationService.ValidateCustomer(model.Username, model.Password, out customer);
                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    //sign in new customer
                    _authenticationService.SignIn(customer, model.RememberMe);

                    //raise event
                    _eventPublisher.Publish(new CustomerLoggedinEvent(customer));

                    //activity log
                    _customerActivityService.InsertActivity(customer, "PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"));

                    if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                    {
                        return(RedirectToAction("Index", "Profile", new { area = "" }));
                    }

                    return(Redirect(returnUrl));
                }

                case CustomerLoginResults.CustomerNotExist:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist"));
                    break;

                case CustomerLoginResults.Deleted:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.Deleted"));
                    break;

                case CustomerLoginResults.NotActive:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotActive"));
                    break;

                case CustomerLoginResults.NotRegistered:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));
                    break;

                case CustomerLoginResults.LockedOut:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut"));
                    break;

                case CustomerLoginResults.WrongPassword:
                default:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                    break;
                }
            }


            var returnModel = _customerModelFactory.PrepareLoginModel();

            returnModel.Username   = model.Username;
            returnModel.RememberMe = model.RememberMe;
            return(View(model));
        }
        public async void SendTextByStep(byte type, Update update, FaraBotUser user = null)
        {
            var bot = await Models.Bot.GetBotClientAsync();

            var chatId = update.Message.Chat.Id;

            switch (type)
            {
            case 0:
                user.Step = 1;
                _BotUserService.Update(user);
                await bot.SendTextMessageAsync(chatId, "نام کاربری خود را وارد نمایید.");

                break;

            case 1:
                user.username = update.Message.Text;
                user.Step     = 2;
                _BotUserService.Update(user);
                await bot.SendTextMessageAsync(chatId, "رمز عبور خود را وارد نمایید.");

                break;

            case 2:
                var loginResult = _CustomerService.ValidateCustomer(_customerSettings.UsernamesEnabled ? user.username : user.username, update.Message.Text);
                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                    user.Step = 3;
                    _BotUserService.Update(user);
                    await bot.SendTextMessageAsync(chatId, "ثبت اطلاع رسانی برای شما با موفیت انجام شد");

                    break;

                case CustomerLoginResults.Deleted:
                case CustomerLoginResults.NotRegistered:
                case CustomerLoginResults.CustomerNotExist:
                    user.Step = 1;
                    _BotUserService.Update(user);
                    await bot.SendTextMessageAsync(chatId, "نام کاربری شما صحیح نمی باشد.");

                    await bot.SendTextMessageAsync(chatId, "نام کاربری خود را وارد نمایید.");

                    break;

                case CustomerLoginResults.WrongPassword:
                    user.Step = 1;
                    _BotUserService.Update(user);
                    await bot.SendTextMessageAsync(chatId, "رمز عبور شما صحیح نمی باشد.");

                    await bot.SendTextMessageAsync(chatId, "نام کاربری خود را وارد نمایید.");

                    break;

                case CustomerLoginResults.LockedOut:
                case CustomerLoginResults.NotActive:
                    user.Step = 1;
                    _BotUserService.Update(user);
                    await bot.SendTextMessageAsync(chatId, "اکانت وارد شده غیرفعال می باشد.");

                    await bot.SendTextMessageAsync(chatId, "نام کاربری خود را وارد نمایید.");

                    break;
                }
                break;

            default:
                break;
            }
        }
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                var customerLoginResult = _customerRegistrationService.ValidateCustomer(model.Username, model.Password);

                if (customerLoginResult == Nop.Core.Domain.Customers.CustomerLoginResults.Successful)
                {
                    var customer = _customerService.GetCustomerByUsername(model.Username);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(customer.Username, customer.Email, customer.Username));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(customer.Email, customer.Username, props);

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Beispiel #20
0
        public virtual IActionResult Index(LoginModel model, string returnUrl, bool captchaValid)
        {
            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (ModelState.IsValid)
            {
                if (_customerSettings.UsernamesEnabled && model.Username != null)
                {
                    model.Username = model.Username.Trim();
                }
                var loginResult = _customerRegistrationService.ValidateCustomer(_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password);
                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    var customer = _customerSettings.UsernamesEnabled
                                ? _customerService.GetCustomerByUsername(model.Username)
                                : _customerService.GetCustomerByEmail(model.Email);


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

                    //raise event
                    _eventPublisher.Publish(new CustomerLoggedinEvent(customer));

                    //activity log
                    _customerActivityService.InsertActivity(customer, "PublicStore.Login",
                                                            _localizationService.GetResource("ActivityLog.PublicStore.Login"), customer);
                    //tao notification
                    var notifyItem = Notification.CreateSimple(customer.Id
                                                               , _localizationService.GetResource("Account.Login.Notification.Subject")
                                                               , string.Format(_localizationService.GetResource("Account.Login.Notification.Body"), DateTime.Now.toDateVNString(true), _webHelper.GetCurrentIpAddress())
                                                               );
                    _notificationService.InsertNotification(notifyItem);

                    if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect("AppWork/Index"));
                    }

                    return(Redirect(returnUrl));
                }

                case CustomerLoginResults.CustomerNotExist:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist"));
                    model.messageResult = _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist");
                    break;

                case CustomerLoginResults.Deleted:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.Deleted"));
                    model.messageResult = _localizationService.GetResource("Account.Login.WrongCredentials.Deleted");
                    break;

                case CustomerLoginResults.NotActive:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotActive"));
                    model.messageResult = _localizationService.GetResource("Account.Login.WrongCredentials.NotActive");
                    break;

                case CustomerLoginResults.NotRegistered:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));
                    model.messageResult = _localizationService.GetResource("Account.Login.WrongCredentials.NotActive");
                    break;

                case CustomerLoginResults.LockedOut:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut"));
                    model.messageResult = _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut");
                    break;

                case CustomerLoginResults.WrongPassword:
                default:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                    model.messageResult = _localizationService.GetResource("Account.Login.WrongCredentials.WrongCredentials");
                    break;
                }
            }
            //If we got this far, something failed, redisplay form
            //model = _customerModelFactory.PrepareLoginModel(model.CheckoutAsGuest);
            return(View(model));
        }
Beispiel #21
0
        public virtual ActionResult Login(LoginModel model, string returnUrl, bool captchaValid)
        {
            //validate CAPTCHA
            //if (_captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage && !captchaValid)
            //{
            //    ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            //}

            if (ModelState.IsValid)
            {
                model.Username = model.Username.Trim();

                var loginResult = _customerRegistrationService.ValidateCustomer(model.Username, model.Password);

                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    var customer = _customerService.GetCustomerByUsername(model.Username);


                    //登录新客户
                    _authenticationService.SignIn(customer, model.RememberMe);

                    //触发事件
                    _eventPublisher.Publish(new CustomerLoggedinEvent(customer));

                    //activity log
                    _customerActivityService.InsertActivity(customer, "PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"));

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

                    return(Redirect(returnUrl));
                }

                case CustomerLoginResults.CustomerNotExist:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist"));
                    break;

                case CustomerLoginResults.Deleted:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.Deleted"));
                    break;

                case CustomerLoginResults.NotActive:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotActive"));
                    break;

                case CustomerLoginResults.NotRegistered:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));
                    break;

                case CustomerLoginResults.LockedOut:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut"));
                    break;

                case CustomerLoginResults.WrongPassword:
                default:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                    break;
                }
            }

            //If we got this far, something failed, redisplay form
            model = _customerModelFactory.PrepareLoginModel(model.CheckoutAsGuest);
            return(View(model));
        }
        public virtual async Task <IActionResult> Index(LoginModel model, bool captchaValid)
        {
            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

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

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

                    //sign in
                    return(await SignInAction(customer, model.RememberMe));
                }

                case CustomerLoginResults.RequiresTwoFactor:
                {
                    var userName = _customerSettings.UsernamesEnabled ? model.Username : model.Email;

                    HttpContext.Session.SetString("AdminRequiresTwoFactor", userName);

                    return(RedirectToAction("TwoFactorAuthorization"));
                }

                case CustomerLoginResults.CustomerNotExist:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist"));
                    break;

                case CustomerLoginResults.Deleted:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.Deleted"));
                    break;

                case CustomerLoginResults.NotActive:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotActive"));
                    break;

                case CustomerLoginResults.NotRegistered:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered"));
                    break;

                case CustomerLoginResults.LockedOut:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials.LockedOut"));
                    break;

                case CustomerLoginResults.WrongPassword:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                    break;

                default:
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                    break;
                }
            }

            //If we got this far, something failed, redisplay form
            model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
            model.DisplayCaptcha   = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;

            return(View(model));
        }
Beispiel #23
0
 public HttpResponseMessage ValidateCustomer([FromBody] ValidateCustomerModel model)
 {
     return(Request.CreateResponse(HttpStatusCode.OK, _customerRegistrationService.ValidateCustomer(model.usernameOrEmail, model.password)));
 }
Beispiel #24
0
        public HttpResponseMessage PostLogin(CustomerLoginModel value)
        {
            if (string.IsNullOrWhiteSpace(value.UserName) || string.IsNullOrWhiteSpace(value.Password))
            {
                return(ReturnResult(string.Empty, 1, "不能传入空的参数值"));
            }

            try
            {
                var checkResult = ValidateSignature(value.Signature, value.timestamp, value.Nonce, value.AppCode);

                if (!checkResult)
                {
                    return(ReturnResult(string.Empty, 1, "不合法的登录方式,您的IP将会被限制访问"));
                }
                var      loginResult = _customerRegistrationService.ValidateCustomer(value.UserName, value.Password);
                var      errorMessge = string.Empty;
                Customer customer    = new Customer();
                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    //if (customer == null){
                    customer = _customerService.GetCustomerByUsername(value.UserName);
                    //}
                    //sign in new customer
                    _authenticationService.SignIn(customer, true);
                }
                break;

                case CustomerLoginResults.CustomerNotExist:
                    errorMessge = _localizationService.GetResource("Account.Login.WrongCredentials.CustomerNotExist");
                    break;

                case CustomerLoginResults.Deleted:
                    errorMessge = _localizationService.GetResource("Account.Login.WrongCredentials.Deleted");
                    break;

                case CustomerLoginResults.NotActive:
                    errorMessge = _localizationService.GetResource("Account.Login.WrongCredentials.NotActive");
                    break;

                case CustomerLoginResults.NotRegistered:
                    errorMessge = _localizationService.GetResource("Account.Login.WrongCredentials.NotRegistered");
                    break;

                case CustomerLoginResults.WrongPassword:
                default:
                    errorMessge = _localizationService.GetResource("Account.Login.WrongCredentials");
                    break;
                }
                if (!string.IsNullOrWhiteSpace(errorMessge))
                {
                    return(ReturnResult(string.Empty, 1, errorMessge));
                }
                else
                {
                    var result = new
                    {
                        token     = WebApiValidate.GetApiValidateToken(customer.Id),
                        id        = customer.Id,
                        username  = customer.Username,
                        email     = customer.Email.ConvertToString(),
                        firstname = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName).ConvertToString(),
                        lastname  = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName).ConvertToString(),
                        imageurl  = _pictureService.GetPictureUrl(
                            customer.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId),
                            _mediaSettings.AvatarPictureSize,
                            false).ConvertToString()
                    };

                    return(ReturnResult(result, 0, string.Empty));
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                return(ReturnResult(string.Empty, 1, "读取数据出现错误"));
            }
        }
        public HttpResponseMessage Login(LoginModel model)//string returnUrl, bool captchaValid, bool RememberMe, string Username = null, string Email = null, string Password = null)
        {
            var    response   = this.Request.CreateResponse(HttpStatusCode.OK);
            string jsonString = "";

            try
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        var addr = new System.Net.Mail.MailAddress(model.Email);
                    }
                    catch
                    {
                        model.Username = model.Email;
                        model.Email    = null;
                    }

                    if (_customerSettings.UsernamesEnabled && model.Username != null)
                    {
                        model.Username = model.Username.Trim();
                    }

                    if (_customerRegistrationService.ValidateCustomer(_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password))
                    {
                        var customer = _customerSettings.UsernamesEnabled
                                                        ? _customerService.GetCustomerByUsername(model.Username)
                                                        : _customerService.GetCustomerByEmail(model.Email);

                        if (customer.Id != 0)
                        {
                            _workContext.CurrentCustomer = customer;
                        }

                        var Enable2FA = customer.GetAttribute <bool>(SystemCustomerAttributeNames.Enable2FA);
                        if (Enable2FA)
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "success", data = new { Enable2FA = true } }));
                        }
                        _shoppingCartService.MigrateShoppingCart(customer, customer);
                        if (customer != null)
                        {
                            var tokenString = GenerateJSONWebToken(customer.Email);
                            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"), customer);
                            var c = JsonConvert.SerializeObject(customer, new JsonSerializerSettings
                            {
                                Formatting            = Newtonsoft.Json.Formatting.Indented,
                                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                            });
                            c = c.Replace(System.Environment.NewLine, string.Empty);
                            return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "success", data = JObject.Parse(c), token = tokenString }));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = _localizationService.GetResource("Account.Login.WrongCredentials") }));
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "invalid model" }));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = _localizationService.GetResource("Common.SomethingWentWrong") }));
            }
        }
        public IActionResult Login([FromBody] LoginRequest model)
        {
            var response = new LoginResponse {
                Result = ResultType.Error
            };

            if (ModelState.IsValid)
            {
                model.Mobile = model.Mobile;
                var loginResult = _customerRegistrationService.ValidateCustomer(model.Mobile, model.Password);

                switch (loginResult)
                {
                case CustomerLoginResults.Successful:
                {
                    var customer = _customerService.GetCustomerByPhone(model.Mobile);

                    //sign in new customer
                    var token = _tokenFactoryService.CreateJwtTokens(customer);
                    _tokenStoreService.AddCustomerToken(customer, token.RefreshTokenSerial, token.AccessToken, null);

                    //raise event
                    _eventPublisher.Publish(new CustomerLoggedinEvent(customer));

                    response.Result       = ResultType.Success;
                    response.AccessToken  = token.AccessToken;
                    response.RefreshToken = token.RefreshToken;

                    return(Ok(response));
                }

                case CustomerLoginResults.CustomerNotExist:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials.customernotexist"));
                    break;

                case CustomerLoginResults.Deleted:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials.deleted"));
                    break;

                case CustomerLoginResults.NotActive:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials.notactive"));
                    break;

                case CustomerLoginResults.NotRegistered:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials.notregistered"));
                    break;

                case CustomerLoginResults.LockedOut:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials.lockedout"));
                    break;

                case CustomerLoginResults.WrongPassword:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials.wrongcustomernameorpassword"));
                    break;

                default:
                    response.Messages.Add(
                        _localizationService.GetResource("account.login.wrongcredentials"));
                    break;
                }
            }
            response.Messages.AddRange(ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
            return(Unauthorized(response));
        }