Beispiel #1
0
        public void CanChangePassword()
        {
            var customer = CreateCustomer(PasswordFormat.Encrypted);

            var request = new ChangePasswordRequest("*****@*****.**", true, PasswordFormat.Clear, "password", "password");
            var unSuccess = _customerRegistrationService.ChangePassword(request);

            request = new ChangePasswordRequest("*****@*****.**", true, PasswordFormat.Hashed, "newpassword", "password");
            var success = _customerRegistrationService.ChangePassword(request);

            unSuccess.Success.Should().BeFalse();
            success.Success.Should().BeTrue();

            DeleteCustomer(customer);
        }
        public void Can_change_password()
        {
            var request = new ChangePasswordRequest("*****@*****.**", true, PasswordFormat.Clear, "password", "password");
            var result  = _customerRegistrationService.ChangePassword(request);

            result.Success.ShouldEqual(false);

            request = new ChangePasswordRequest("*****@*****.**", true, PasswordFormat.Hashed, "newpassword", "password");
            result  = _customerRegistrationService.ChangePassword(request);
            result.Success.ShouldEqual(true);

            //request = new ChangePasswordRequest("*****@*****.**", true, PasswordFormat.Encrypted, "password", "newpassword");
            //result = _customerRegistrationService.ChangePassword(request);
            //result.Success.ShouldEqual(true);
        }
        public HttpResponseMessage ChangePassword(ChangePasswordModel model)
        {
            var    response   = this.Request.CreateResponse();
            string jsonString = "";

            var customer = _customerService.GetCustomerById(model.CustomerId);

            if (model.CustomerId > 0)
            {
                _workContext.CurrentCustomer = customer;
            }

            try
            {
                //var customer = _customerService.GetCustomerById(customerid);
                if (ModelState.IsValid)
                {
                    var changePasswordRequest = new ChangePasswordRequest(customer.Email,
                                                                          true, _customerSettings.DefaultPasswordFormat, model.NewPassword, model.OldPassword);
                    var changePasswordResult = _customerRegistrationService.ChangePassword(changePasswordRequest);
                    if (changePasswordResult.Success)
                    {
                        model.Result        = _localizationService.GetResource("Account.ChangePassword.Success");
                        response.StatusCode = HttpStatusCode.OK;
                        //jsonString = JsonConvert.SerializeObject(model, Formatting.None);
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "success", data = model }));
                    }
                    else
                    {
                        foreach (var error in changePasswordResult.Errors)
                        {
                            jsonString = jsonString + error;
                        }

                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = jsonString }));
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { code = 0, Message = _localizationService.GetResource("Common.SomethingWentWrong") }));
            }
            catch (Exception Ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { code = 0, Message = _localizationService.GetResource("Common.SomethingWentWrong") }));
            }
        }
Beispiel #4
0
        public HttpResponseMessage PostChangePassword(ChangePasswordModel value)
        {
            if (!CheckTokenUser(value.id))
            {
                return(ReturnResult(string.Empty, 1, "数据读取方式不合规"));
            }

            if (string.IsNullOrWhiteSpace(value.OldPassword) || string.IsNullOrWhiteSpace(value.NewPassword))
            {
                return(ReturnResult(string.Empty, 1, "不能传入空的参数值"));
            }


            try
            {
                var customer = _customerService.GetCustomerById(value.id);

                if (customer != null && customer.Active && !customer.Deleted)
                {
                    var ResultStatus          = 0;
                    var ErrorMessage          = string.Empty;
                    var changePasswordRequest = new ChangePasswordRequest(customer.Username,
                                                                          true, _customerSettings.DefaultPasswordFormat, value.NewPassword, value.OldPassword);
                    var changePasswordResult = _customerRegistrationService.ChangePassword(changePasswordRequest);
                    if (changePasswordResult.Success)
                    {
                        ResultStatus = 0;
                        ErrorMessage = _localizationService.GetResource("Account.ChangePassword.Success");
                        return(ReturnResult(string.Empty, ResultStatus, ErrorMessage));
                    }
                    ResultStatus = 1;
                    ErrorMessage = changePasswordResult.Errors[0];
                    //If we got this far, something failed, redisplay form
                    return(ReturnResult(string.Empty, ResultStatus, ErrorMessage));
                }
                else
                {
                    return(ReturnResult(string.Empty, 1, "未找到相应用户"));
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                return(ReturnResult(string.Empty, 1, "读取数据出现错误"));
            }
        }
        public IActionResult SetPassword(string key, [FromBody] ODataActionParameters parameters)
        {
            if (!_permissionService.Authorize(PermissionSystemName.Customers))
            {
                return(Forbid());
            }

            var password = parameters.FirstOrDefault(x => x.Key == "password").Value;

            if (password == null)
            {
                return(NotFound());
            }

            var changePassRequest = new ChangePasswordRequest(key, false, _customerSettings.DefaultPasswordFormat, password.ToString());
            var changePassResult  = _customerRegistrationService.ChangePassword(changePassRequest);

            if (!changePassResult.Success)
            {
                return(BadRequest(string.Join(',', changePassResult.Errors)));
            }
            return(Ok(true));
        }
        public async Task <IActionResult> Create(CustomerModel model, bool continueEditing, IFormCollection form)
        {
            if (!string.IsNullOrWhiteSpace(model.Email))
            {
                var cust2 = await _customerService.GetCustomerByEmail(model.Email);

                if (cust2 != null)
                {
                    ModelState.AddModelError("", "Email is already registered");
                }
            }

            if (!string.IsNullOrWhiteSpace(model.Username) & _customerSettings.UsernamesEnabled)
            {
                var cust2 = await _customerService.GetCustomerByUsername(model.Username);

                if (cust2 != null)
                {
                    ModelState.AddModelError("", "Username is already registered");
                }
            }

            //validate customer roles
            var allCustomerRoles = await _customerService.GetAllCustomerRoles(showHidden : true);

            var newCustomerRoles = new List <CustomerRole>();

            foreach (var customerRole in allCustomerRoles)
            {
                if (model.SelectedCustomerRoleIds != null && model.SelectedCustomerRoleIds.Contains(customerRole.Id))
                {
                    newCustomerRoles.Add(customerRole);
                }
            }
            var customerRolesError = _customerViewModelService.ValidateCustomerRoles(newCustomerRoles);

            if (!string.IsNullOrEmpty(customerRolesError))
            {
                ModelState.AddModelError("", customerRolesError);
                ErrorNotification(customerRolesError, false);
            }

            if (ModelState.IsValid)
            {
                model.CustomAttributes = await ParseCustomCustomerAttributes(form);

                var customer = await _customerViewModelService.InsertCustomerModel(model);

                //password
                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
                    var changePassResult  = await _customerRegistrationService.ChangePassword(changePassRequest);

                    if (!changePassResult.Success)
                    {
                        foreach (var changePassError in changePassResult.Errors)
                        {
                            ErrorNotification(changePassError);
                        }
                    }
                }

                if (customer.IsAdmin() && !string.IsNullOrEmpty(model.VendorId))
                {
                    ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.AdminCouldNotbeVendor"));
                }

                if (newCustomerRoles.Any(x => x.SystemName == SystemCustomerRoleNames.Vendors) && string.IsNullOrEmpty(model.VendorId))
                {
                    ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.CannotBeInVendoRoleWithoutVendorAssociated"));
                }
                if (newCustomerRoles.Any(x => x.SystemName == SystemCustomerRoleNames.Staff) && string.IsNullOrEmpty(model.StaffStoreId))
                {
                    ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.CannotBeInStaffRoleWithoutStaffAssociated"));
                }
                if (customer.IsStaff() && customer.IsVendor())
                {
                    ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff"));
                }

                SuccessNotification(_localizationService.GetResource("Admin.Customers.Customers.Added"));
                return(continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            await _customerViewModelService.PrepareCustomerModel(model, null, true);

            return(View(model));
        }
Beispiel #7
0
        public virtual ActionResult Create(CustomerModel model, bool continueEditing, FormCollection form)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
            {
                return(AccessDeniedView());
            }

            if (!string.IsNullOrWhiteSpace(model.Email))
            {
                var cust2 = _customerService.GetCustomerByEmail(model.Email);
                if (cust2 != null)
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Admin.Customers.Customer.EmailAlreadyRegistered"));
                }
            }
            if (!string.IsNullOrWhiteSpace(model.Username))
            {
                var cust2 = _customerService.GetCustomerByUsername(model.Username);
                if (cust2 != null)
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Admin.Customers.Customer.UsernameAlreadyRegistered"));
                }
            }

            //验证用户角色
            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
            var newCustomerRoles = new List <CustomerRole>();

            foreach (var customerRole in allCustomerRoles)
            {
                if (model.SelectedCustomerRoleIds.Contains(customerRole.Id))
                {
                    newCustomerRoles.Add(customerRole);
                }
            }
            var customerRolesError = ValidateCustomerRoles(newCustomerRoles);

            if (!string.IsNullOrEmpty(customerRolesError))
            {
                ModelState.AddModelError("", customerRolesError);
                ErrorNotification(customerRolesError, false);
            }

            //如果用户角色为"注册用户",需要确保输入的电子邮箱有效性
            if (newCustomerRoles.Any() &&
                newCustomerRoles.FirstOrDefault(c => c.SystemName == SystemCustomerRoleNames.Registered) != null &&
                !CommonHelper.IsValidEmail(model.Email))
            {
                ModelState.AddModelError("", _localizationService.GetResource("Admin.Customers.Customers.ValidEmailRequiredRegisteredRole"));
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.ValidEmailRequiredRegisteredRole"), false);
            }

            if (ModelState.IsValid)
            {
                var customer = new Customer
                {
                    Email               = model.Email,
                    Username            = model.Username,
                    AdminComment        = model.AdminComment,
                    Active              = model.Active,
                    CreatedOnUtc        = DateTime.UtcNow,
                    LastActivityDateUtc = DateTime.UtcNow
                };
                _customerService.InsertCustomer(customer);

                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Name, model.Name);
                if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                }
                if (_customerSettings.GenderEnabled)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                }
                if (_customerSettings.DateOfBirthEnabled)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, model.DateOfBirth);
                }
                if (_customerSettings.CompanyEnabled)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
                }
                if (_customerSettings.PhoneEnabled)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                }

                //用户密码
                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
                    var changePassResult  = _customerRegistrationService.ChangePassword(changePassRequest);
                    if (!changePassResult.Success)
                    {
                        foreach (var changePassError in changePassResult.Errors)
                        {
                            ErrorNotification(changePassError);
                        }
                    }
                }

                //用户角色
                foreach (var customerRole in newCustomerRoles)
                {
                    //确保当前用户不为"管理员"时,添加的角色将不能为"管理员"
                    if (customerRole.SystemName == SystemCustomerRoleNames.Administrators &&
                        !_workContext.CurrentCustomer.IsAdmin())
                    {
                        continue;
                    }

                    customer.CustomerRoles.Add(customerRole);
                }
                _customerService.UpdateCustomer(customer);

                _customerActivityService.InsertActivity("AddNewCustomer", _localizationService.GetResource("ActivityLog.AddNewCustomer"), customer.Id);

                SuccessNotification(_localizationService.GetResource("Admin.Customers.Customers.Added"));

                if (continueEditing)
                {
                    SaveSelectedTabName();
                    return(RedirectToAction("Edit", new { id = customer.Id }));
                }
                return(RedirectToAction("List"));
            }

            PrepareCustomerModel(model, null, true);
            return(View(model));
        }
 /// <summary>
 /// Change password
 /// </summary>
 /// <param name="request">Request</param>
 /// <returns>Result</returns>
 public ChangePasswordResult ChangePassword(ChangePasswordRequest request)
 {
     return(_customerRegistrationService.ChangePassword(request));
 }
        public virtual ActionResult Create(UserModel model, bool continueEditing, FormCollection form)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageUsers))
            {
                return(AccessDeniedView());
            }

            if (!String.IsNullOrWhiteSpace(model.Email))
            {
                var cust2 = _customerService.GetCustomerByEmail(model.Email);

                if (cust2 != null)
                {
                    ModelState.AddModelError("", "Email is already registered");
                }
            }

            //validate customer roles
            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
            var newCustomerRoles = new List <CustomerRole>();

            foreach (var customerRole in allCustomerRoles)
            {
                if (model.SelectedCustomerRoleIds.Contains(customerRole.Id))
                {
                    newCustomerRoles.Add(customerRole);
                }
            }

            // Trick to include this customer always as Registered :)
            newCustomerRoles.Add(
                allCustomerRoles.Where(t => t.SystemName == SystemCustomerRoleNames.Registered).FirstOrDefault()
                );

            var customerRolesError = ValidateCustomerRoles(newCustomerRoles);

            if (!String.IsNullOrEmpty(customerRolesError))
            {
                ModelState.AddModelError("", customerRolesError);
                ErrorNotification(customerRolesError, false);
            }

            // Ensure that valid email address is entered if Registered role is checked to avoid registered customers with empty email address
            if (newCustomerRoles.Any() &&
                newCustomerRoles.FirstOrDefault(c => c.SystemName == SystemCustomerRoleNames.Registered) != null &&
                !CommonHelper.IsValidEmail(model.Email))
            {
                ModelState.AddModelError("", _localizationService.GetResource("Admin.Customers.Customers.ValidEmailRequiredRegisteredRole"));
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.ValidEmailRequiredRegisteredRole"), false);
            }

            if (!ModelState.IsValid)
            {
                PrepareCustomerModel(model, null, true);
                return(View(model));
            }

            var customer = new Customer
            {
                CustomerGuid        = Guid.NewGuid(),
                Email               = model.Email,
                Active              = model.Active,
                CreatedOnUtc        = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow,
                RegisteredInStoreId = _storeContext.CurrentStore.Id,
                VendorId            = 1 // Default Moveleiros Loja (URGENT: CHANGE IT)
            };

            _customerService.InsertCustomer(customer);

            // Map user automatically with
            _storeMappingService.InsertStoreMapping(
                customerId: customer.Id,
                entityName: SystemCustomerRoleNames.Stores,
                storeId: _storeContext.CurrentStore.Id
                );

            //form fields
            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);

            //password
            if (!String.IsNullOrWhiteSpace(model.Password))
            {
                var changePassRequest = new ChangePasswordRequest(model.Email,
                                                                  false,
                                                                  _customerSettings.DefaultPasswordFormat,
                                                                  model.Password
                                                                  );

                var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest);

                if (!changePassResult.Success)
                {
                    foreach (var changePassError in changePassResult.Errors)
                    {
                        ErrorNotification(changePassError);
                    }
                }
            }

            //customer roles
            foreach (var customerRole in newCustomerRoles)
            {
                //ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself
                if (customerRole.SystemName == SystemCustomerRoleNames.Administrators &&
                    !_workContext.CurrentCustomer.IsAdmin())
                {
                    continue;
                }

                customer.CustomerRoles.Add(customerRole);
            }
            _customerService.UpdateCustomer(customer);

            //ensure that a customer with a vendor associated is not in "Administrators" role
            //otherwise, he won't have access to other functionality in admin area
            if (customer.IsAdmin() && customer.VendorId > 0)
            {
                customer.VendorId = 0;
                _customerService.UpdateCustomer(customer);
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.AdminCouldNotbeVendor"));
            }

            //ensure that a customer in the Vendors role has a vendor account associated.
            //otherwise, he will have access to ALL products
            if (customer.IsVendor() && customer.VendorId == 0)
            {
                var vendorRole = customer
                                 .CustomerRoles
                                 .FirstOrDefault(x => x.SystemName == SystemCustomerRoleNames.Vendors);

                customer.CustomerRoles.Remove(vendorRole);
                _customerService.UpdateCustomer(customer);
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.CannotBeInVendoRoleWithoutVendorAssociated"));
            }

            //activity log
            _customerActivityService.InsertActivity("AddNewCustomer", _localizationService.GetResource("ActivityLog.AddNewCustomer"), customer.Id);

            SuccessNotification(_localizationService.GetResource("Moveleiros.Admin.Settings.Users.Added"));

            if (continueEditing)
            {
                //selected tab
                SaveSelectedTabName();

                return(RedirectToAction("Edit", new { id = customer.Id }));
            }

            return(RedirectToAction("List"));
        }
        public ActionResult Create(CustomerModel model, bool continueEditing, FormCollection form)
        {
            if (!String.IsNullOrEmpty(model.Email))
            {
                var cust = _customerService.GetCustomerByEmail(model.Email);
                if (cust != null)
                {
                    ModelState.AddModelError("", "Email is already registered");
                }
            }
            //validate customer roles
            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
            var newCustomerRoles = new List <CustomerRole>();

            foreach (var role in allCustomerRoles)
            {
                if (model.SelectedCustomerRoleIds.Contains(role.Id))
                {
                    newCustomerRoles.Add(role);
                }
            }
            if (ModelState.IsValid)
            {
                var customer = new Customer
                {
                    CustomerGuid     = Guid.NewGuid(),
                    Email            = model.Email,
                    CreatedOn        = DateTime.Now,
                    LastActivityDate = DateTime.Now,
                    IsActive         = model.Active,
                    UserName         = model.UserName,
                    AdminComment     = model.AdminComment
                };
                _customerService.InsertCustomer(customer);

                foreach (var role in newCustomerRoles)
                {
                    if (role.SystemName == SystemCustomerRoleNames.Administrators &&
                        !_workContext.CurrentCustomer.IsAdmin())
                    {
                        continue;
                    }

                    customer.CustomerRoles.Add(role);
                }
                //password
                if (!String.IsNullOrWhiteSpace(model.Password))
                {
                    var changePassReqeust = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat
                                                                      , model.Password);
                    var changePassResult = _customerRegistrationService.ChangePassword(changePassReqeust);
                    if (!changePassResult.Success)
                    {
                        foreach (var changePassError in changePassResult.Errors)
                        {
                            ErrorNotification(changePassError);
                        }
                    }
                }
                _customerService.UpdateCustomer(customer);
            }

            return(View(model));
        }
        public HttpResponseMessage PasswordRecoverySend(PasswordRecoveryModel model)
        {
            var    response   = this.Request.CreateResponse();
            string jsonString = "";


            string accountSid = "ACc887bcf83d1f79d47ed76860c6dd288f";          //Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
            string authToken  = "9ef4bc2a45051f3e79a85ffbb19bfd61";            //Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

            TwilioClient.Init(accountSid, authToken);

            var customer = _customerService.GetCustomerByUsername(model.Email);

            if (customer.Id > 0)
            {
                _workContext.CurrentCustomer = customer;
            }
            else
            {
                model.ResultMessage = "Invalid Phone number";
                model.ResultState   = PasswordRecoveryResultState.Success;
                response.StatusCode = HttpStatusCode.OK;
                return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "invalidusername", data = model.ResultMessage }));
            }

            var Phone = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone);

            if (model.Phone != Phone)
            {
                model.ResultMessage = "Invalid Phone number";
                model.ResultState   = PasswordRecoveryResultState.Success;
                response.StatusCode = HttpStatusCode.OK;
                return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "invalidphone", data = model.ResultMessage }));
            }

            //string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
            //string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

            //TwilioClient.Init(accountSid, authToken);

            //if (string.IsNullOrEmpty(model.OTP))
            //{
            //	var message1 = MessageResource.Create(
            //		body: "This is the ship that made the Kessel Run in fourteen parsecs?",
            //		from: new Twilio.Types.PhoneNumber("+17192498304"),
            //		to: new Twilio.Types.PhoneNumber("+919974242686")
            //	);
            //}

            try
            {
                if (customer != null && customer.Active && !customer.Deleted)
                {
                    var passwordRecoveryToken = Guid.NewGuid();

                    if (!string.IsNullOrEmpty(model.OTP))
                    {
                        var OTP = customer.GetAttribute <string>(SystemCustomerAttributeNames.PasswordResetOTP);

                        if (OTP == model.OTP)
                        {
                            Random generator         = new Random();
                            String newpassword       = generator.Next(0, 1000000).ToString("D6");
                            var    changePassRequest = new ChangePasswordRequest(customer.Email, false, _customerSettings.DefaultPasswordFormat, newpassword);
                            var    changePassResult  = _customerRegistrationService.ChangePassword(changePassRequest);

                            if (changePassResult.Success)
                            {
                                var message1 = MessageResource.Create(
                                    body: "Your new Magic Booster Password : "******"+17192498304"),
                                    to: new Twilio.Types.PhoneNumber(Phone)
                                    );
                            }

                            //_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.PasswordRecoveryToken, passwordRecoveryToken.ToString());
                            //Services.MessageFactory.SendCustomerPasswordRecoveryMessage(customer, _workContext.WorkingLanguage.Id);

                            model.ResultMessage = "New Password sent to your phone";
                            model.ResultState   = PasswordRecoveryResultState.Success;
                            response.StatusCode = HttpStatusCode.OK;
                            return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "success", data = model.ResultMessage }));
                        }
                        else
                        {
                            model.ResultMessage = _localizationService.GetResource("Enter Valid OTP");
                            return(Request.CreateResponse(HttpStatusCode.OK, new { code = 1, Message = model.ResultMessage }));
                        }
                    }
                    else
                    {
                        Random generator = new Random();
                        String r         = generator.Next(0, 1000000).ToString("D6");

                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.PasswordResetOTP, r);

                        var message1 = MessageResource.Create(
                            body: "Reset Password OTP : " + r,
                            from: new Twilio.Types.PhoneNumber("+17192498304"),
                            to: new Twilio.Types.PhoneNumber(Phone)
                            );

                        model.ResultMessage = _localizationService.GetResource("OTP Sent on your registered Phone Number");
                        model.ResultState   = PasswordRecoveryResultState.Success;
                        response.StatusCode = HttpStatusCode.OK;
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "otpsent", data = model.ResultMessage }));
                    }
                }
                else
                {
                    model.ResultMessage = _localizationService.GetResource("Account.PasswordRecovery.EmailHasBeenSent");
                    model.ResultState   = PasswordRecoveryResultState.Success;
                    //model.ResultMessage = _localizationService.GetResource("Account.PasswordRecovery.EmailNotFound");
                    //model.ResultState = PasswordRecoveryResultState.Error;
                    return(Request.CreateResponse(HttpStatusCode.OK, new { code = 1, Message = model.ResultMessage }));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, new { code = 1, Message = "something went wrong" }));
            }
        }
        public ActionResult TaoTaiKhoan(XuLyHopDongModel.KhachHangModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.CVLeTanHopDong))
            {
                return(AccessDeniedView());
            }
            var khachhangrole = new CustomerRole();
            var customer      = new Customer
            {
                CustomerGuid        = Guid.NewGuid(),
                Email               = model.Email,
                Active              = true,
                CreatedOnUtc        = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow,
            };
            var item = _customerService.GetCustomerByEmail(model.Email);

            if (item == null)
            {
                _customerService.InsertCustomer(customer);


                //firstname,lastname
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                //mã hóa password
                if (!String.IsNullOrWhiteSpace(model.Password))
                {
                    var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
                    var changePassResult  = _customerRegistrationService.ChangePassword(changePassRequest);
                    if (!changePassResult.Success)
                    {
                        foreach (var changePassError in changePassResult.Errors)
                        {
                            ErrorNotification(changePassError);
                        }
                    }
                }
                //update khách hàng cho hop dong
                var _hopdong = _chonveService.GetHopDongById(model.HopDongId);

                if (_hopdong != null)
                {
                    if (_hopdong.KhachHangID > 0 && _hopdong.KhachHangID != customer.Id)
                    {
                        var khachhang   = _customerService.GetCustomerById(_hopdong.KhachHangID);
                        var newitemrole = new CustomerRole();
                        foreach (var _item in khachhang.CustomerRoles)
                        {
                            if (_item.SystemName == SystemCustomerRoleNames.HTNhaXeManager)
                            {
                                newitemrole = _item;
                            }
                        }
                        khachhang.CustomerRoles.Remove(newitemrole);
                        _customerService.UpdateCustomer(khachhang);
                    }
                    _hopdong.KhachHangID = customer.Id;
                    _chonveService.UpdateHopDong(_hopdong);
                }
                //customerrole

                var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
                var newCustomerRoles = new List <CustomerRole>();
                foreach (var customerRole in allCustomerRoles)
                {
                    if (customerRole.SystemName == SystemCustomerRoleNames.Registered)
                    {
                        newCustomerRoles.Add(customerRole);
                    }
                    if (customerRole.SystemName == SystemCustomerRoleNames.HTNhaXeManager)
                    {
                        newCustomerRoles.Add(customerRole);
                    }
                }
                foreach (var _customerRole in newCustomerRoles)
                {
                    customer.CustomerRoles.Add(_customerRole);
                }
                _customerService.UpdateCustomer(customer);
                //tạo văn phong với địa chỉ của nhà xe là trụ sở chính
                var truso = new VanPhong();
                truso.NhaXeId = _hopdong.NhaXeID;
                var nhaxe = _nhaxeService.GetNhaXeById(_hopdong.NhaXeID);
                truso.TenVanPhong    = nhaxe.TenNhaXe;
                truso.KieuVanPhongID = (int)ENKieuVanPhong.TruSo;
                truso.DiaChiID       = nhaxe.DiaChiID;
                _nhaxeService.InsertVanPhong(truso);
                // tao nhan vien thuoc van phong
                var nhanvien = new NhanVien();
                nhanvien.HoVaTen           = nhaxe.TenNhaXe;
                nhanvien.Email             = nhaxe.Email;
                nhanvien.CustomerID        = customer.Id;
                nhanvien.KieuNhanVienID    = (int)ENKieuNhanVien.QuanLy;
                nhanvien.GioiTinhID        = (int)ENGioiTinh.Nam;
                nhanvien.TrangThaiID       = (int)ENTrangThaiNhanVien.DangLamViec;
                nhanvien.NgayBatDauLamViec = DateTime.Now;

                nhanvien.VanPhongID = truso.Id;
                nhanvien.NhaXeID    = _hopdong.NhaXeID;
                nhanvien.DiaChiID   = nhaxe.DiaChiID;
                _nhanvienService.Insert(nhanvien);
                return(RedirectToAction("ChiTietHopDong", new { id = model.HopDongId }));
            }
            return(View());
        }
Beispiel #13
0
        public virtual ActionResult Create(VendorModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageVendors))
            {
                return(AccessDeniedView());
            }

            if (ModelState.IsValid)
            {
                var cust1 = _customerService.GetCustomerByEmail(model.Email);
                if (cust1 != null)
                {
                    ModelState.AddModelError("Email", "Email is already registered");
                }

                var cust2 = _customerService.GetCustomerByUsername(model.AccountId);
                if (cust2 != null)
                {
                    ModelState.AddModelError("AccountId", "Vendor account ID is already registered");
                }

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                var vendor = model.ToEntity();
                _vendorService.InsertVendor(vendor);

                var customer = new Customer
                {
                    CustomerGuid        = Guid.NewGuid(),
                    Email               = model.Email,
                    Username            = model.AccountId,
                    VendorId            = vendor.Id,
                    AdminComment        = model.AdminComment,
                    Active              = model.Active,
                    CreatedOnUtc        = DateTime.UtcNow,
                    LastActivityDateUtc = DateTime.UtcNow,
                    RegisteredInStoreId = 0
                };
                _customerService.InsertCustomer(customer);
                var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
                //customer roles
                foreach (var customerRole in allCustomerRoles)
                {
                    //ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself
                    if (customerRole.SystemName == SystemCustomerRoleNames.Registered ||
                        customerRole.SystemName == SystemCustomerRoleNames.Vendors)
                    {
                        customer.CustomerRoles.Add(customerRole);
                    }
                }

                //password
                if (!String.IsNullOrWhiteSpace(model.Password))
                {
                    var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password);
                    var changePassResult  = _customerRegistrationService.ChangePassword(changePassRequest);
                    if (!changePassResult.Success)
                    {
                        foreach (var changePassError in changePassResult.Errors)
                        {
                            ErrorNotification(changePassError);
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(model.Address.Address1))
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.Address.Address1);
                }
                if (string.IsNullOrWhiteSpace(model.Address.Address2))
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.Address.Address2);
                }
                if (string.IsNullOrWhiteSpace(model.Address.ZipPostalCode))
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.Address.ZipPostalCode);
                }
                if (string.IsNullOrWhiteSpace(model.Address.City))
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.Address.City);
                }
                if (model.Address.CountryId > 0)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.Address.CountryId);
                }
                if (model.Address.StateProvinceId > 0)
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.Address.StateProvinceId);
                }
                if (string.IsNullOrWhiteSpace(model.Address.PhoneNumber))
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Address.PhoneNumber);
                }
                if (string.IsNullOrWhiteSpace(model.Address.FaxNumber))
                {
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Address.FaxNumber);
                }

                _customerService.UpdateCustomer(customer);

                //activity log
                _customerActivityService.InsertActivity("AddNewVendor", _localizationService.GetResource("ActivityLog.AddNewVendor"), vendor.Id);

                //search engine name
                model.SeName = vendor.ValidateSeName(model.SeName, vendor.Name, true);
                _urlRecordService.SaveSlug(vendor, model.SeName, 0);

                //address
                var address = model.Address.ToEntity();
                address.CreatedOnUtc = DateTime.UtcNow;
                //some validation
                if (address.CountryId == 0)
                {
                    address.CountryId = null;
                }
                if (address.StateProvinceId == 0)
                {
                    address.StateProvinceId = null;
                }
                _addressService.InsertAddress(address);
                vendor.AddressId = address.Id;
                _vendorService.UpdateVendor(vendor);

                //locales
                UpdateLocales(vendor, model);
                //update picture seo file name
                UpdatePictureSeoNames(vendor);



                SuccessNotification(_localizationService.GetResource("Admin.Vendors.Added"));

                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabName();

                    return(RedirectToAction("Edit", new { id = vendor.Id }));
                }
                return(RedirectToAction("List"));
            }

            //If we got this far, something failed, redisplay form
            PrepareVendorModel(model, null, true, true);
            return(View(model));
        }