Esempio n. 1
0
        public ActionResult Create(CustomerCreateModel model)
        {
            var roles = _customerService.GetAllCustomerRoles();

            model.AvailableRoles = roles.ToSelectItems();

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

            var customer = new Customer
            {
                Username         = model.UserName,
                CreatedOn        = DateTime.Now,
                MobilePhone      = model.PhoneNumber,
                RealName         = model.RealName,
                CustomerRoleId   = model.CustomerRoleId,
                Active           = model.IsActive,
                LastActivityDate = DateTime.Now
            };
            var customerRequest = new CustomerRegistrationRequest(customer, model.UserName, model.PassWord,
                                                                  PasswordFormat.Hashed);
            var reponse = _customerRegistrationService.RegisterCustomer(customerRequest);

            if (reponse.Success)
            {
                return(RedirectToAction("ListCustomer"));
            }

            reponse.Errors.ForEach(d => { ModelState.AddModelError(string.Empty, d); });
            return(View(model));
        }
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual IActionResult RegisterNewUser(ExternalAuthenticationParameters parameters, string returnUrl)
        {
            //check whether the specified email has been already registered
            if (_customerService.GetCustomerByEmail(parameters.Email) != null)
            {
                var alreadyExistsError = string.Format("Email地址“{0}”已经存在", parameters.ExternalDisplayIdentifier);
                return(ErrorAuthentication(new[] { alreadyExistsError }, returnUrl));
            }

            //registration is approved if validation isn't required
            var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                                         (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && !_externalAuthenticationSettings.RequireEmailValidation);

            //create registration request
            var registrationRequest = new CustomerRegistrationRequest(_workContext.CurrentCustomer,
                                                                      parameters.Email, parameters.Email,
                                                                      CommonHelper.GenerateRandomDigitCode(20),
                                                                      PasswordFormat.Clear,
                                                                      registrationIsApproved);

            //whether registration request has been completed successfully
            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (!registrationResult.Success)
            {
                return(ErrorAuthentication(registrationResult.Errors, returnUrl));
            }

            //allow to save other customer values by consuming this event
            _eventPublisher.Publish(new CustomerAutoRegisteredByExternalMethodEvent(_workContext.CurrentCustomer, parameters));

            //raise vustomer registered event
            _eventPublisher.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));

            //associate external account with registered user
            AssociateExternalAccountWithUser(_workContext.CurrentCustomer, parameters);

            //authenticate
            if (registrationIsApproved)
            {
                _authenticationService.SignIn(_workContext.CurrentCustomer, false);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }));
            }

            //registration is succeeded but isn't activated
            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            return(ErrorAuthentication(new[] { "Error on registration" }, returnUrl));
        }
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound = _openAuthenticationService.GetUser(parameters);

            var userLoggedIn = _workContext.CurrentCustomer;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                _authenticationService.SignIn(userFound, false);
            }
            else
            {
                #region Register user

                var currentCustomer = _workContext.CurrentCustomer;
                var details         = new Nop.Plugin.ExternalAuth.Weixin.Authentication.External.RegistrationDetails(parameters);
                var randomPassword  = CommonHelper.GenerateRandomDigitCode(20);

                var registrationRequest = new CustomerRegistrationRequest(currentCustomer, string.Empty, details.UserName, randomPassword, PasswordFormat.Clear, _storeContext.CurrentStore.Id, true);

                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    //store other parameters (form fields)
                    if (!String.IsNullOrEmpty(details.NickName))
                    {
                        _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.NickName);
                    }

                    userFound = currentCustomer;
                    _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                    ExternalAuthorizerHelper.RemoveParameters();

                    //authenticate
                    _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();

                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    foreach (var error in registrationResult.Errors)
                    {
                        result.AddError(string.Format(error));
                    }

                    return(result);
                }
                #endregion
            }

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
Esempio n. 4
0
        public ActionResult Insert(BankModel model, GridCommand command)
        {
            ModelState.Remove("Id");
            if (!ModelState.IsValid)
            {
                var modelStateErrors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                return(Content(modelStateErrors.FirstOrDefault()));
            }
            var customer = new Customer();

            customer.CreatedOnUtc        = DateTime.UtcNow;
            customer.CustomerGuid        = Guid.NewGuid();
            customer.LastActivityDateUtc = DateTime.UtcNow;
            _customerService.InsertCustomer(customer);

            var request = new CustomerRegistrationRequest(customer, model.Email, model.Email, "123456", _customerSettings.DefaultPasswordFormat);
            var result  = _customerRegistrationService.RegisterCustomer(request);

            if (result.Success)
            {
                customer.CompanyName = model.BankTitle;
                customer.Email       = model.Email;
                customer.Username    = model.Email;
                if (model.Rating != 0)
                {
                    customer.Rating = model.Rating;
                }
                if (model.PictureId != 0)
                {
                    customer.ProviderLogoId = model.PictureId;
                }
                customer.CustomerRoles.Add(_customerService.GetCustomerRoleBySystemName("Sellers"));
                _customerService.UpdateCustomer(customer);
            }
            else
            {
                _customerService.DeleteCustomerPermamently(customer);
                foreach (var error in result.Errors)
                {
                    if (error == _localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists"))
                    {
                        ModelState.AddModelError("Email", error);
                    }

                    ModelState.AddModelError("", error);
                }

                var modelStateErrors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                return(Content(modelStateErrors.FirstOrDefault()));
            }

            return(List(command));
        }
Esempio n. 5
0
        public Task <Unit> Handle(CreateAccountCommand request, CancellationToken cancellationToken)
        {
            var requestRegistration = AutoMapperConfiguration.Mapper.Map <CustomerRegistrationRequest>(request);

            requestRegistration.Customer.RegisteredInStoreId = _infrastructureService.Cache.Store.Id;
            var errors = _customerRegistration.RegisterCustomer(requestRegistration);

            if (errors.Any())
            {
                throw new ValidationException(errors.Count() > 1 ? string.Join(Environment.NewLine, errors) : errors.FirstOrDefault());
            }
            return(Unit.Task);
        }
        public bool RegisterUser(RegistrationViewModel model)
        {
            bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;

            Customer customer = model.CurrentCustomer;

            string customerAttributesXml = PrepareCustomerAttributes(model);

            var registrationRequest = new CustomerRegistrationRequest(
                customer,
                model.SelfIdentificationViewModel.Email,
                _customerSettings.UsernamesEnabled ? model.Username : model.SelfIdentificationViewModel.Email,
                model.SelfIdentificationViewModel.Password,
                _customerSettings.DefaultPasswordFormat,
                _storeContext.CurrentStore.Id,
                isApproved);

            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (registrationResult.Success)
            {
                //save customer attributes
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName,
                                                       model.SelfIdentificationViewModel.FirstName);

                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName,
                                                       model.SelfIdentificationViewModel.LastName);

                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone,
                                                       model.SelfIdentificationViewModel.Phone);

                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes,
                                                       customerAttributesXml);

                //login customer now
                if (isApproved)
                {
                    _authenticationService.SignIn(customer, true);
                }

                // delay registration until enrollment is complete
                // if (model.IsEnrollment) return true;

                return(AnnounceRegistation(customer));
            }

            return(false);
        }
        public virtual IActionResult Register([FromBody] RegisterRequest model)
        {
            var response = new RegisterResponse {
                Result = ResultType.Error
            };

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

                var registrationRequest = new CustomerRegistrationRequest(
                    model.Mobile,
                    model.Password,
                    _customerSettings.DefaultPasswordFormat);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

                if (registrationResult.Success)
                {
                    //email validation message
                    var verifyCode = CommonHelper.GenerateSmsVerificationCode();
                    _genericAttributeService.SaveAttribute(registrationRequest.Customer, BopCustomerDefaults.AccountActivationTokenAttribute,
                                                           verifyCode);
                    //_workflowMessageService.SendcustomerPhoneValidationMessage(customer, _workContext.WorkingLanguage.Id);

                    //result
                    response.Result = ResultType.Success;

                    response.Messages.Add($"{_localizationService.GetResource("account.accountactivation.activation.code")} : {verifyCode}");
                    //raise event
                    _eventPublisher.Publish(new CustomerRegisteredEvent(registrationRequest.Customer));
                    return(Ok(response));
                }

                //errors
                foreach (var error in registrationResult.Errors)
                {
                    response.Messages.Add(error);
                }
            }

            response.Messages.AddRange(ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
            return(UnprocessableEntity(response));
        }
Esempio n. 8
0
        public async Task <CustomerRegistrationResult> Handle(SubAccountAddCommand request, CancellationToken cancellationToken)
        {
            var customer = await PrepareCustomer(request);

            var registrationRequest = new CustomerRegistrationRequest(customer, request.Model.Email,
                                                                      request.Model.Email, request.Model.Password,
                                                                      _customerSettings.DefaultPasswordFormat, request.Store.Id, request.Model.Active);

            var customerRegistrationResult = await _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (!customerRegistrationResult.Success)
            {
                await _customerService.DeleteCustomer(customer, true);
            }
            else
            {
                await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, request.Model.FirstName);

                await _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, request.Model.LastName);
            }
            return(customerRegistrationResult);
        }
Esempio n. 9
0
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual IActionResult RegisterNewUser(ExternalAuthenticationParameters parameters, string returnUrl)
        {
            //if auto registration is disabled redirect to login page
            //TODO remove this setting
            if (!_externalAuthenticationSettings.AutoRegisterEnabled)
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);
                return(new RedirectToActionResult("Login", "Customer", !string.IsNullOrEmpty(returnUrl) ? new { ReturnUrl = returnUrl } : null));
            }

            //or try to auto register new user
            //registration is approved if validation isn't required
            var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                                         (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && !_externalAuthenticationSettings.RequireEmailValidation);

            //create registration request
            var registrationRequest = new CustomerRegistrationRequest(_workContext.CurrentCustomer,
                                                                      parameters.Email, parameters.Email,
                                                                      CommonHelper.GenerateRandomDigitCode(20),
                                                                      PasswordFormat.Hashed,
                                                                      _storeContext.CurrentStore.Id,
                                                                      registrationIsApproved);

            //whether registration request has been completed successfully
            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (!registrationResult.Success)
            {
                return(Error(registrationResult.Errors, returnUrl));
            }

            //allow to save other customer values by consuming this event
            _eventPublisher.Publish(new CustomerAutoRegisteredByExternalMethodEvent(_workContext.CurrentCustomer, parameters));

            //raise vustomer registered event
            _eventPublisher.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));

            //store owner notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                _workflowMessageService.SendCustomerRegisteredNotificationMessage(_workContext.CurrentCustomer, _localizationSettings.DefaultAdminLanguageId);
            }

            //associate external account with registered user
            AssociateExternalAccountWithUser(_workContext.CurrentCustomer, parameters);

            //authenticate
            if (registrationIsApproved)
            {
                _authenticationService.SignIn(_workContext.CurrentCustomer, false);
                _workflowMessageService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }));
            }

            //registration is succeeded but isn't activated
            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                //email validation message
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailValidationMessage(_workContext.CurrentCustomer, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            //TODO create locale for error
            return(Error(new[] { "Error on registration" }, returnUrl));
        }
Esempio n. 10
0
 /// <summary>
 /// Register customer
 /// </summary>
 /// <param name="request">Request</param>
 /// <returns>Result</returns>
 public CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request)
 {
     return(_customerRegistrationService.RegisterCustomer(request));
 }
Esempio n. 11
0
        public ActionResult Register(
            RegistrationViewModel model,
            SelfIdentificationViewModel identity,
            bool captchaValid
            )
        {
            //check whether registration is allowed
            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }


            //// check for existing email address  this is a members only show;
            //if (model.SelfIdentificationViewModel.Email == null ||
            // _customerService.GetCustomerByEmail(model.SelfIdentificationViewModel.Email.Trim()) == null)
            //{
            //    model.CurrentState = "NonMember";
            //    model.DisplaySuccess = false;
            //    return View(ContactViewPath("Register"), model);
            //}



            // setup model for pure registration
            _dallasArtContext.IsRegistration  = true;
            model.SelfIdentificationViewModel = identity;

            if (model.CurrentState == "Begin")
            {
                model.CurrentState = "Loop";
                //  PostExtraValidation(model);


                if (!ModelState.IsValid)
                {
                    // something failed validation
                    return(PartialView(ContactViewPath("_RegisterRequest"), model));
                }

                else
                {
                    // add member
                    model.ImageUploadViewModel.Member = identity.RadioButtionList.SelectedRole == 2;

                    model.ImageUploadViewModel.EmailAddress    = identity.Email;
                    model.ImageUploadViewModel.CustomerName    = identity.FirstName + " " + identity.LastName;
                    model.ImageUploadViewModel.Telephone       = identity.Phone;
                    model.ImageUploadViewModel.RemainingImages = 2;
                    model.ImageUploadViewModel.ModelState      = "Ready";

                    Customer             customer = _customerService.GetCustomerByEmail(identity.Email);
                    IList <CustomerRole> x        = _customerService.GetAllCustomerRoles();

                    // if (customer != null) model.CurrentState = "Member";

                    model.DisplaySuccess = true;

                    return(PartialView(ContactViewPath("_RegisterRequest"), model));
                }

                // model.DisplaySuccess = false;
                // model.CurrentState = "Begin";
                //  return View(ContactViewPath("Register"), model);
            }

            // security check
            // DisplayCaptchaViewModel.CaptchaValidation(captchaValid, model.DisplayCaptcha, ModelState);

            // check input values not handled by validation
            EnrollmentPostValidation(model);

            if (ModelState.IsValid)
            {
                bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;

                model.CurrentCustomer = _workContext.CurrentCustomer;
                model.SelfIdentificationViewModel.Customer = model.CurrentCustomer;


                var registrationRequest = new CustomerRegistrationRequest(
                    model.CurrentCustomer,
                    model.SelfIdentificationViewModel.Email,
                    _customerSettings.UsernamesEnabled ? model.Username : model.SelfIdentificationViewModel.Email,
                    model.SelfIdentificationViewModel.Password,
                    _customerSettings.DefaultPasswordFormat,
                    _storeContext.CurrentStore.Id,
                    isApproved);

                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

                if (registrationResult.Success)
                {
                    //  var loginResult =
                    // _customerRegistrationService.ValidateCustomer( model.SelfIdentificationViewModel.Email, model.SelfIdentificationViewModel.Password);

                    var guestRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

                    _workContext.CurrentCustomer.CustomerRoles.Add(guestRole);

                    var control = new OnePageCheckoutModel {
                        ShippingRequired = false, DisableBillingAddressCheckoutStep = false
                    };

                    return(View("/Themes/PAA/Views/Checkout/onepagecheckout.cshtml", control));
                }
                else
                {
                    // something failed registration
                    return(View("Register", model));
                }
            }

            // something failed validation
            return(View("Register", model));
        }
        private void AddCustomersFromData(DataTable data)
        {
            IList <CustomerRole> roles = _customerService.GetAllCustomerRoles();

            foreach (DataRow row in data.Rows)
            {
                var email = row[(int)SpreadSheet.Header.EMail].ToString();
                // empty row ??
                if (email.Length < 3)
                {
                    BadCount++;
                    continue;
                }

                var model = new RegisterModel
                {
                    FirstName    = row[(int)SpreadSheet.Header.First].ToString(),
                    LastName     = row[(int)SpreadSheet.Header.Last].ToString(),
                    Email        = email,
                    ConfirmEmail = email,
                    Username     = email,
                    CheckUsernameAvailabilityEnabled = true,
                    CountryId       = 1, // usa
                    Password        = "******",
                    ConfirmPassword = "******",

                    HoneypotEnabled  = false,
                    DisplayCaptcha   = false,
                    DisplayVatNumber = false,

                    StreetAddress   = row[(int)SpreadSheet.Header.Address].ToString().Replace("?", string.Empty),
                    City            = row[(int)SpreadSheet.Header.City].ToString().Replace("?", string.Empty),
                    ZipPostalCode   = row[(int)SpreadSheet.Header.Zip].ToString().Replace("?", string.Empty),
                    Phone           = row[(int)SpreadSheet.Header.Phone].ToString().Replace("?", string.Empty),
                    StateProvinceId = 54,   // texas  //23



                    //CreatedOnUtc = DateTime.UtcNow
                };


                // var customer =  new Core.Domain.Customers.Customer();
                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();

                Core.Domain.Customers.Customer customer = _workContext.CurrentCustomer;

                bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;

                var registrationRequest = new CustomerRegistrationRequest(customer,
                                                                          model.Email,
                                                                          _customerSettings.UsernamesEnabled ? model.Username : model.Email,
                                                                          model.Password,
                                                                          _customerSettings.DefaultPasswordFormat,
                                                                          _storeContext.CurrentStore.Id,
                                                                          isApproved);

                // register customer
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

                if (registrationResult.Success)
                {
                    // update customer role
                    string level = row[(int)SpreadSheet.Header.Level].ToString().Replace("?", string.Empty);

                    if (level.Trim().Length > 0)
                    {
                        CustomerRole role = AddMembershipRole(ref roles, level);

                        //  add customer membership level;
                        if (role != null)
                        {
                            registrationRequest.Customer.CustomerRoles.Add(role);
                        }
                    }


                    // add billing address

                    // AddCustomerBillingAddress(row, email);

                    GoodCount++;
                }
                else
                {
                    BadCount++;
                }

                //  if (GoodCount > 2) return;
            }
        }
        public ActionResult Create(MassRegistrationListModel model, bool saveAndContinue)
        {
            var registrationValidator   = IoC.Resolve <MassRegistrationEditModelValidator>();
            var invalidRegistrationList = new List <MassRegistrationEditModel>();

            var eventData = _eventRepository.GetById(model.EventId);

            foreach (var registrationEditModel in model.Registrations)
            {
                if (registrationEditModel.HomeNumber != null && !string.IsNullOrEmpty(registrationEditModel.HomeNumber.ToString()))
                {
                    registrationEditModel.HomeNumber = PhoneNumber.Create(registrationEditModel.HomeNumber.ToNumber().ToString(), PhoneNumberType.Home);
                }
                var result = CorporateUploadHelper.ValidateModel(registrationValidator, registrationEditModel);
                if (string.IsNullOrEmpty(result))
                {
                    try
                    {
                        using (var scope = new TransactionScope())
                        {
                            if (!_customerRegistrationService.RegisterCustomer(registrationEditModel, model.EventId, eventData.EventType))
                            {
                                invalidRegistrationList.Add(registrationEditModel);
                            }
                            scope.Complete();
                        }
                    }
                    catch (Exception ex)
                    {
                        registrationEditModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("System Error:" + ex.Message);
                        invalidRegistrationList.Add(registrationEditModel);
                    }
                }
                else
                {
                    registrationEditModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage(result);
                    invalidRegistrationList.Add(registrationEditModel);
                }
            }
            if (invalidRegistrationList.Count > 0)
            {
                model.Registrations = invalidRegistrationList;
                _corporateUploadHelper.SetEventDetails(model);
                _corporateUploadHelper.SetDropDownInfo(model);
                return(View(model));
            }
            if (!saveAndContinue)
            {
                var currentSession = IoC.Resolve <ISessionContext>().UserSession;
                if (currentSession.CurrentOrganizationRole.CheckRole((long)Roles.Technician))
                {
                    Response.RedirectUser("/Scheduling/EventCustomerList/Index?id=" + model.EventId);
                    return(null);
                }


                if (currentSession.CurrentOrganizationRole.CheckRole((long)Roles.CorporateAccountCoordinator))
                {
                    Response.RedirectUser("/Users/Dashboard/CorporateAccountCoordinator");
                    return(null);
                }
                Response.RedirectUser("/App/Common/EventDetails.aspx?EventId=" + model.EventId);
                return(null);
            }

            var newModel = new MassRegistrationListModel {
                EventId = model.EventId
            };

            _corporateUploadHelper.SetEventDetails(newModel);
            _corporateUploadHelper.SetDropDownInfo(newModel);
            return(View(newModel));
        }
Esempio n. 14
0
        public HttpResponseMessage RegisterCustomer(HttpRequestMessage request, RegistrationVM model)
        {
            return(CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = request.CreateResponse(HttpStatusCode.NotFound, "No items found");
                //response = request.CreateResponse<BulkEditListVM>(HttpStatusCode.OK, model);
                if (_baseService.WorkContext.CurrentCustomer.IsRegistered())
                {
                    //Save a new record
                    _baseService.WorkContext.CurrentCustomer = _customerService.InsertGuestCustomer();
                }
                var customer = _baseService.WorkContext.CurrentCustomer;
                customer.RegisteredInStoreId = _storeContext.CurrentStore.Id;
                if (ModelState.IsValid)
                {
                    if (_customerSettings.UsernamesEnabled && model.UserName != null)
                    {
                        model.UserName = model.UserName.Trim();
                    }

                    bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                    var registrationRequest = new CustomerRegistrationRequest(customer,
                                                                              model.UserName,
                                                                              _customerSettings.UsernamesEnabled ? model.UserName : "",
                                                                              model.Password,
                                                                              _customerSettings.DefaultPasswordFormat,
                                                                              _storeContext.CurrentStore.Id,
                                                                              isApproved);
                    var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

                    if (registrationResult.Success)
                    {
                        //insert default address (if possible)
                        var defaultAddress = new Address
                        {
                            FirstName = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName, _genericAttributeService),
                            LastName = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName, _genericAttributeService),
                            Email = customer.Email,
                            Company = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company, _genericAttributeService),
                            CountryId = customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId, _genericAttributeService) > 0
                                ? (int?)customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId, _genericAttributeService)
                                : null,
                            StateProvinceId = customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId, _genericAttributeService) > 0
                                ? (int?)customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId, _genericAttributeService)
                                : null,
                            City = customer.GetAttribute <string>(SystemCustomerAttributeNames.City, _genericAttributeService),
                            Address1 = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress, _genericAttributeService),
                            Address2 = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2, _genericAttributeService),
                            ZipPostalCode = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode, _genericAttributeService),
                            PhoneNumber = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone, _genericAttributeService),
                            FaxNumber = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax, _genericAttributeService),
                            CreatedOnUtc = customer.CreatedOnUtc
                        };

                        //some validation
                        if (defaultAddress.CountryId == 0)
                        {
                            defaultAddress.CountryId = null;
                        }
                        if (defaultAddress.StateProvinceId == 0)
                        {
                            defaultAddress.StateProvinceId = null;
                        }
                        //set default address
                        customer.Addresses.Add(defaultAddress);
                        customer.BillingAddress = defaultAddress;
                        customer.ShippingAddress = defaultAddress;
                        _customerService.UpdateCustomer(customer);

                        _baseService.Commit();
                        response = request.CreateResponse <Customer>(HttpStatusCode.OK, customer);
                    }
                }
                return response;
            }));
        }
Esempio n. 15
0
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual async Task <IActionResult> RegisterNewUser(ExternalAuthenticationParameters parameters, string returnUrl)
        {
            //or try to auto register new user
            //registration is approved if validation isn't required
            var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                                         (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation);

            //create registration request
            var registrationRequest = new CustomerRegistrationRequest(_workContext.CurrentCustomer,
                                                                      parameters.Email, parameters.Email,
                                                                      CommonHelper.GenerateRandomDigitCode(20),
                                                                      PasswordFormat.Hashed,
                                                                      _storeContext.CurrentStore.Id,
                                                                      registrationIsApproved);

            //whether registration request has been completed successfully
            var registrationResult = await _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (!registrationResult.Success)
            {
                return(Error(registrationResult.Errors));
            }

            //allow to save other customer values by consuming this event
            await _mediator.Publish(new CustomerAutoRegisteredByExternalMethodEvent(_workContext.CurrentCustomer, parameters));

            //raise vustomer registered event
            await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));

            //store owner notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                await _workflowMessageService.SendCustomerRegisteredNotificationMessage(_workContext.CurrentCustomer, _storeContext.CurrentStore, _localizationSettings.DefaultAdminLanguageId);
            }

            //associate external account with registered user
            await AssociateExternalAccountWithUser(_workContext.CurrentCustomer, parameters);

            //authenticate
            if (registrationIsApproved)
            {
                await _authenticationService.SignIn(_workContext.CurrentCustomer, false);

                await _workflowMessageService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer, _storeContext.CurrentStore, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }));
            }

            //registration is succeeded but isn't activated
            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                //email validation message
                await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());

                await _workflowMessageService.SendCustomerEmailValidationMessage(_workContext.CurrentCustomer, _storeContext.CurrentStore, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            return(Error(new[] { "Error on registration" }));
        }
Esempio n. 16
0
        public AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound    = _openAuthenticationService.GetUser(parameters);
            var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
                {
                    return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                }
                var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                result.AddError("Account is already assigned");
                return(result);
            }
            if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);
                if (AutoRegistrationIsEnabled())
                {
                    #region 注册用户
                    var  currentCustomer = _workContext.CurrentCustomer;
                    var  details         = new RegistrationDetails(parameters);
                    var  randomPassword  = CommonHelper.GenerateRandomDigitCode(20);
                    bool isApproved      = (_customerSettings.UserRegistrationType == UserRegistrationType.Standard) ||
                                           (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation &&
                                            !_externalAuthenticationSettings.RequireEmailValidation);
                    var registrationRequest = new CustomerRegistrationRequest(currentCustomer,
                                                                              details.EmailAddress, details.EmailAddress,
                                                                              randomPassword, PasswordFormat.Clear,
                                                                              isApproved);
                    var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                    if (registrationResult.Success)
                    {
                        userFound = currentCustomer;
                        _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                        ExternalAuthorizerHelper.RemoveParameters();
                        if (isApproved)
                        {
                            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                        }
                        //_eventPublisher.Publish(new CustomerRegisteredEvent(currentCustomer));
                        if (isApproved)
                        {
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                        }
                        else if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
                        {
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                        }
                        else if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
                        {
                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval));
                        }
                    }
                    else
                    {
                        ExternalAuthorizerHelper.RemoveParameters();

                        var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                        foreach (var error in registrationResult.Errors)
                        {
                            result.AddError(string.Format(error));
                        }
                        return(result);
                    }
                    #endregion
                }
                else if (RegistrationIsEnabled())
                {
                    return(new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon));
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();
                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    result.AddError("Registration is disabled");
                    return(result);
                }
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
            }
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //发布事件
            _eventPublisher.Publish(new CustomerLoggedinEvent(userFound ?? userLoggedIn));
            //日志
            _customerActivityService.InsertActivity("PublicStore.Login", "登录",
                                                    userFound ?? userLoggedIn);
            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
Esempio n. 17
0
        public IHttpActionResult Register(RegisterModel model)
        {
            //判断当前是否为认证用户
            if (ControllerContext.RequestContext.Principal.Identity.IsAuthenticated)
            {
                return(BadRequest("当前用户已经注册"));
            }

            //检查是否允许注册用户
            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(BadRequest("用户注册已关闭"));
            }

            if (_workContext.CurrentCustomer.IsRegistered())
            {
                return(BadRequest("当前用户已注册"));
            }

            var customer = _workContext.CurrentCustomer;

            if (customer.IsRegistered())
            {
                return(BadRequest("当前用户已经注册"));
            }

            //TODO:自定义属性

            //TODO:验证码

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

            bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
            var  registrationRequest = new CustomerRegistrationRequest(customer, model.Email, model.Mobile, model.Username,
                                                                       model.Password, _customerSettings.DefaultPasswordFormat, isApproved);

            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (registrationResult.Success)
            {
                //associated with external account (if possible)

                //insert default address (if possible)

                //notifications
                //_workflowMessageService

                switch (_customerSettings.UserRegistrationType)
                {
                case UserRegistrationType.EmailValidation:
                {
                    //email validation message
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                    _workflowMessageService.SendCustomerEmailValidationMessage(customer);

                    //result
                    return(Ok(new ApiResponseResult {
                            Code = 1, Message = "邮件认证"
                        }));
                }

                case UserRegistrationType.AdminApproval:
                {
                    return(Ok(new ApiResponseResult {
                            Code = 1, Message = "管理员认证"
                        }));
                }

                default:
                {
                    //send customer welcome message
                    _workflowMessageService.SendCustomerWelcomeMessage(customer);

                    return(Ok(new ApiResponseResult {
                            Code = 1, Message = "注册成功"
                        }));
                }
                }
            }

            //errors
            foreach (var error in registrationResult.Errors)
            {
                ModelState.AddModelError("", error);
            }
            return(BadRequest(ModelState));
        }
Esempio n. 18
0
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound = _openAuthenticationService.GetUser(parameters);

            var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
                {
                    // The person is trying to log in as himself.. bit weird
                    return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
                }

                var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                result.AddError("Account is already assigned");
                return(result);
            }
            if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);

                if (AutoRegistrationIsEnabled())
                {
                    #region Register user

                    var currentCustomer = _workContext.CurrentCustomer;
                    var details         = new RegistrationDetails(parameters);
                    var randomPassword  = CommonHelper.GenerateRandomDigitCode(20);

                    if (String.IsNullOrEmpty(details.EmailAddress))
                    {
                        details.EmailAddress = DateTime.UtcNow.Date.ToString("MM.dd.yy") + "@itb.com";
                        var user = _customerService.GetCustomerByEmail(details.EmailAddress);
                        if (user != null)
                        {
                            int index = 1;
                            details.EmailAddress = index.ToString() + "-" + details.EmailAddress;
                            while (index < 100)
                            {
                                user = _customerService.GetCustomerByEmail(details.EmailAddress);
                                if (user == null)
                                {
                                    break;
                                }
                                details.EmailAddress = details.EmailAddress.Replace(index.ToString() + "-", (index + 1).ToString() + "-");
                                index++;
                            }
                        }
                    }
                    bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                    var  registrationRequest = new CustomerRegistrationRequest(currentCustomer, details.EmailAddress,
                                                                               details.EmailAddress, randomPassword, PasswordFormat.Clear, isApproved);
                    var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                    if (registrationResult.Success)
                    {
                        //store other parameters (form fields)
                        if (!String.IsNullOrEmpty(details.FirstName))
                        {
                            currentCustomer.FirstName = details.FirstName;
                        }
                        if (!String.IsNullOrEmpty(details.LastName))
                        {
                            currentCustomer.LastName = details.LastName;
                        }


                        userFound = currentCustomer;
                        _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                        ExternalAuthorizerHelper.RemoveParameters();

                        currentCustomer.CustomerRoles.Add(_customerService.GetCustomerRoleBySystemName("Buyers"));
                        _customerService.UpdateCustomer(currentCustomer);
                        //code below is copied from CustomerController.Register method

                        //authenticate
                        if (isApproved)
                        {
                            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                        }

                        //notifications
                        if (_customerSettings.NotifyNewCustomerRegistration)
                        {
                            _workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);
                        }

                        switch (_customerSettings.UserRegistrationType)
                        {
                        case UserRegistrationType.EmailValidation:
                        {
                            //email validation message
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                            _workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                        }

                        case UserRegistrationType.AdminApproval:
                        {
                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval));
                        }

                        case UserRegistrationType.Standard:
                        {
                            //send customer welcome message
                            _workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                        }

                        default:
                            break;
                        }
                    }
                    else
                    {
                        ExternalAuthorizerHelper.RemoveParameters();

                        var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                        foreach (var error in registrationResult.Errors)
                        {
                            result.AddError(string.Format(error));
                        }
                        return(result);
                    }

                    #endregion
                }
                else if (RegistrationIsEnabled())
                {
                    return(new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon));
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();

                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    result.AddError("Registration is disabled");
                    return(result);
                }
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
            }

            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            (userFound ?? userLoggedIn).LastLoginDateUtc = DateTime.UtcNow;

            _customerService.UpdateCustomer(userFound ?? userLoggedIn);
            //activity log
            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
                                                    userFound ?? userLoggedIn);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
Esempio n. 19
0
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound = _openAuthenticationService.GetUser(parameters);

            var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
                {
                    if (userFound.Active)
                    {
                        // The person is trying to log in as himself.. bit weird
                        return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
                    }
                    else
                    {
                        // The person is trying to log in as himself.. bit weird
                        return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                    }
                }

                var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                result.AddError("Account is already assigned");
                return(result);
            }
            if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);

                if (AutoRegistrationIsEnabled())
                {
                    #region Register user

                    var currentCustomer = _workContext.CurrentCustomer;
                    var details         = new RegistrationDetails(parameters);
                    var randomPassword  = CommonHelper.GenerateRandomDigitCode(20);
                    var passwordFormat  = PasswordFormat.Clear;

                    bool isApproved =
                        (//standard registration
                            (_customerSettings.UserRegistrationType == UserRegistrationType.Standard) ||
                            //skip email validation?
                            (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation &&
                             !_externalAuthenticationSettings.RequireEmailValidation));

                    if (parameters.ProviderSystemName == "ExternalAuth.WeiXin")
                    {
                        isApproved     = true;
                        randomPassword = details.Password;
                        passwordFormat = PasswordFormat.Hashed;
                    }

                    CustomerRegistrationRequest registrationRequest = new CustomerRegistrationRequest(currentCustomer,
                                                                                                      details.EmailAddress,
                                                                                                      _customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress,
                                                                                                      randomPassword,
                                                                                                      passwordFormat,
                                                                                                      _storeContext.CurrentStore.Id,
                                                                                                      isApproved);


                    var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                    if (registrationResult.Success)
                    {
                        //store other parameters (form fields)
                        if (!String.IsNullOrEmpty(details.FirstName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.FirstName);
                        }
                        if (!String.IsNullOrEmpty(details.LastName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.LastName, details.LastName);
                        }

                        if (!string.IsNullOrEmpty(details.AvatarUrl))
                        {
                            try
                            {
                                int     customerAvatarId = 0;
                                Picture customerAvatar;
                                using (var webClient = new WebClient())
                                {
                                    byte[] imageBytes = webClient.DownloadData(details.AvatarUrl);
                                    string type       = webClient.ResponseHeaders["content-type"];
                                    customerAvatar = _pictureService.GetPictureById(currentCustomer.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId));
                                    if (imageBytes != null)
                                    {
                                        if (customerAvatar != null)
                                        {
                                            customerAvatar = _pictureService.UpdatePicture(customerAvatar.Id, imageBytes, type, null);
                                        }
                                        else
                                        {
                                            customerAvatar = _pictureService.InsertPicture(imageBytes, type, null);
                                        }
                                    }
                                }


                                if (customerAvatar != null)
                                {
                                    customerAvatarId = customerAvatar.Id;
                                }

                                _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AvatarPictureId, customerAvatarId);
                            }
                            catch (Exception ex)
                            {
                            }
                        }

                        userFound = currentCustomer;



                        _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                        ExternalAuthorizerHelper.RemoveParameters();


                        if (parameters.ProviderSystemName != "ExternalAuth.WeiXin")
                        {
                            //notifications
                            if (_customerSettings.NotifyNewCustomerRegistration)
                            {
                                _workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);
                            }
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                        }

                        //authenticate
                        if (isApproved)
                        {
                            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                        }

                        //raise event
                        _eventPublisher.Publish(new CustomerRegisteredEvent(currentCustomer));

                        if (isApproved)
                        {
                            _workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                        }
                        else if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
                        {
                            //email validation message
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                            _workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                        }
                        else if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
                        {
                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval));
                        }
                    }
                    else
                    {
                        ExternalAuthorizerHelper.RemoveParameters();

                        var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                        foreach (var error in registrationResult.Errors)
                        {
                            result.AddError(string.Format(error));
                        }
                        return(result);
                    }

                    #endregion
                }
                else if (RegistrationIsEnabled())
                {
                    return(new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon));
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();

                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    result.AddError("Registration is disabled");
                    return(result);
                }
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
            }

            //migrate shopping cart
            _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn, true);
            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //raise event
            _eventPublisher.Publish(new CustomerLoggedinEvent(userFound ?? userLoggedIn));
            //activity log
            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
                                                    userFound ?? userLoggedIn);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
Esempio n. 20
0
        public HttpResponseMessage PostRegistCustomerByMobile(MobileRegist regist)
        {
            if (regist == null)
            {
                return(ReturnResult(string.Empty, 1, "不能传入空的参数值"));
            }
            if (string.IsNullOrWhiteSpace(regist.Mobile) || string.IsNullOrWhiteSpace(regist.Password))
            {
                return(ReturnResult(string.Empty, 1, "不能传入空的参数值"));
            }
            if (regist.Captcha == 0)
            {
                return(ReturnResult(string.Empty, 1, "验证码不能为空"));
            }
            try
            {
                var customer = _workContext.CurrentCustomer;

                var registrationRequest = new CustomerRegistrationRequest(customer, string.Empty, regist.Mobile, regist.Password, _customerSettings.DefaultPasswordFormat, _storeContext.CurrentStore.Id, true);
                MemoryCacheManager m    = new MemoryCacheManager();
                var smsCaptcha          = 0;
                if (m.Get <int>(regist.Mobile) > 0)
                {
                    smsCaptcha = m.Get <int>(regist.Mobile);
                }
                else
                {
                    return(ReturnResult(string.Empty, 1, "验证码已经失效请重新获取"));
                }
                if (regist.Captcha != smsCaptcha)
                {
                    return(ReturnResult(string.Empty, 1, "验证码错误,请重新输入"));
                }
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    var customerNew = _customerService.GetCustomerByUsername(regist.Mobile);
                    _authenticationService.SignIn(customerNew, true);
                    var result = new
                    {
                        token     = customer.CustomerGuid,
                        id        = customerNew.Id,
                        username  = customerNew.Username,
                        email     = customerNew.Email.ConvertToString(),
                        firstname = customerNew.GetAttribute <string>(SystemCustomerAttributeNames.FirstName).ConvertToString(),
                        lastname  = customerNew.GetAttribute <string>(SystemCustomerAttributeNames.LastName).ConvertToString(),
                        gender    = customerNew.GetAttribute <string>(SystemCustomerAttributeNames.Gender).ConvertToString(),
                        birthday  = customerNew.GetAttribute <DateTime?>(SystemCustomerAttributeNames.DateOfBirth).ToString().ConvertToString(),
                        imageurl  = _pictureService.GetPictureUrl(
                            customerNew.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId),
                            _mediaSettings.AvatarPictureSize,
                            false).ConvertToString()
                    };
                    return(ReturnResult(result, 0, "注册成功"));
                }
                else
                {
                    return(ReturnResult(string.Empty, 1, registrationResult.Errors[0]));
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                return(ReturnResult(string.Empty, 1, "读取数据出现错误"));
            }
        }
Esempio n. 21
0
        public virtual ActionResult Register(RegisterModel model, string returnUrl, bool captchaValid, FormCollection form)
        {
            //检查是否允许注册
            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }

            if (_workContext.CurrentCustomer.IsAdmin())
            {
                //已注册
                _authenticationService.SignOut();

                //保存新记录
                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
            }
            var customer = _workContext.CurrentCustomer;

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
            {
                //ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

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

                bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var  registrationRequest = new CustomerRegistrationRequest(customer,
                                                                           model.Username,
                                                                           model.Password,
                                                                           _customerSettings.DefaultPasswordFormat,
                                                                           isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    //login customer now
                    if (isApproved)
                    {
                        _authenticationService.SignIn(customer, true);
                    }


                    switch (_customerSettings.UserRegistrationType)
                    {
                    case UserRegistrationType.EmailValidation:
                    {
                        //email validation message
                        //_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                        //_workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                        //result
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.EmailValidation }));
                    }

                    case UserRegistrationType.AdminApproval:
                    {
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.AdminApproval }));
                    }

                    case UserRegistrationType.Standard:
                    {
                        //send customer welcome message
                        //_workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                        var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                        if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                        }
                        return(Redirect(redirectUrl));
                    }

                    default:
                    {
                        return(RedirectToRoute("HomePage"));
                    }
                    }
                }

                //errors
                foreach (var error in registrationResult.Errors)
                {
                    ModelState.AddModelError("Username", error);
                }
            }

            //If we got this far, something failed, redisplay form
            //model = _customerModelFactory.PrepareRegisterModel(model, true, customerAttributesXml);
            return(View());
        }
Esempio n. 22
0
        public virtual ActionResult Register(PaaMember member, string returnUrl, bool captchaValid, FormCollection form)
        {
            RegisterModel model = null;// = member.RegisterModel;



            //check whether registration is allowed
            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }

            if (_workContext.CurrentCustomer.IsRegistered())
            {
                //Already registered customer.
                _authenticationService.SignOut();

                //raise logged out event
                _eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));

                //Save a new record
                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
            }
            var customer = _workContext.CurrentCustomer;

            customer.RegisteredInStoreId = _storeContext.CurrentStore.Id;

            //custom customer attributes
            var customerAttributesXml     = ParseCustomCustomerAttributes(form);
            var customerAttributeWarnings = _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);

            foreach (var error in customerAttributeWarnings)
            {
                ModelState.AddModelError("", error);
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

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

                bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var  registrationRequest = new CustomerRegistrationRequest(customer,
                                                                           model.Email,
                                                                           _customerSettings.UsernamesEnabled ? model.Username : model.Email,
                                                                           model.Password,
                                                                           _customerSettings.DefaultPasswordFormat,
                                                                           _storeContext.CurrentStore.Id,
                                                                           isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    //properties
                    if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                    }
                    //VAT number
                    if (_taxSettings.EuVatEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber);

                        string vatName;
                        string vatAddress;
                        var    vatNumberStatus = _taxService.GetVatNumberStatus(model.VatNumber, out vatName,
                                                                                out vatAddress);
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumberStatusId, (int)vatNumberStatus);
                        //send VAT number admin notification
                        if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                        {
                            _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vatAddress, _localizationSettings.DefaultAdminLanguageId);
                        }
                    }

                    //form fields
                    if (_customerSettings.GenderEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                    }
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                    if (_customerSettings.DateOfBirthEnabled)
                    {
                        //                       DateTime? dateOfBirth = model.ParseDateOfBirth();
                        //                       _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
                    }
                    if (_customerSettings.CompanyEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
                    }
                    if (_customerSettings.StreetAddressEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress);
                    }
                    if (_customerSettings.StreetAddress2Enabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2);
                    }
                    if (_customerSettings.ZipPostalCodeEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode);
                    }
                    if (_customerSettings.CityEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City);
                    }
                    if (_customerSettings.CountryEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
                    }
                    if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId,
                                                               model.StateProvinceId);
                    }
                    if (_customerSettings.PhoneEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                    }
                    if (_customerSettings.FaxEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax);
                    }

                    //newsletter
                    if (_customerSettings.NewsletterEnabled)
                    {
                        //save newsletter value
                        var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.Email, _storeContext.CurrentStore.Id);
                        if (newsletter != null)
                        {
                            if (model.Newsletter)
                            {
                                newsletter.Active = true;
                                _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                            }
                            //else
                            //{
                            //When registering, not checking the newsletter check box should not take an existing email address off of the subscription list.
                            //_newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                            //}
                        }
                        else
                        {
                            if (model.Newsletter)
                            {
                                _newsLetterSubscriptionService.InsertNewsLetterSubscription(new NewsLetterSubscription
                                {
                                    NewsLetterSubscriptionGuid = Guid.NewGuid(),
                                    Email        = model.Email,
                                    Active       = true,
                                    StoreId      = _storeContext.CurrentStore.Id,
                                    CreatedOnUtc = DateTime.UtcNow
                                });
                            }
                        }
                    }

                    //save customer attributes
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributesXml);

                    //login customer now
                    if (isApproved)
                    {
                        _authenticationService.SignIn(customer, true);
                    }

                    //associated with external account (if possible)
                    TryAssociateAccountWithExternalAccount(customer);

                    //insert default address (if possible)
                    var defaultAddress = new Address
                    {
                        FirstName = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName),
                        LastName  = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName),
                        Email     = customer.Email,
                        Company   = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company),
                        CountryId = customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId) > 0
                            ? (int?)customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId)
                            : null,
                        StateProvinceId = customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId) > 0
                            ? (int?)customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId)
                            : null,
                        City          = customer.GetAttribute <string>(SystemCustomerAttributeNames.City),
                        Address1      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress),
                        Address2      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2),
                        ZipPostalCode = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode),
                        PhoneNumber   = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone),
                        FaxNumber     = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax),
                        CreatedOnUtc  = customer.CreatedOnUtc
                    };
                    if (this._addressService.IsAddressValid(defaultAddress))
                    {
                        //some validation
                        if (defaultAddress.CountryId == 0)
                        {
                            defaultAddress.CountryId = null;
                        }
                        if (defaultAddress.StateProvinceId == 0)
                        {
                            defaultAddress.StateProvinceId = null;
                        }
                        //set default address
                        customer.Addresses.Add(defaultAddress);
                        customer.BillingAddress  = defaultAddress;
                        customer.ShippingAddress = defaultAddress;
                        _customerService.UpdateCustomer(customer);
                    }

                    //notifications
                    if (_customerSettings.NotifyNewCustomerRegistration)
                    {
                        _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer,
                                                                                          _localizationSettings.DefaultAdminLanguageId);
                    }

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

                    switch (_customerSettings.UserRegistrationType)
                    {
                    case UserRegistrationType.EmailValidation:
                    {
                        //email validation message
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                        _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                        //result
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.EmailValidation }));
                    }

                    case UserRegistrationType.AdminApproval:
                    {
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.AdminApproval }));
                    }

                    case UserRegistrationType.Standard:
                    {
                        //send customer welcome message
                        _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                        var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                        if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                        }
                        return(Redirect(redirectUrl));
                    }

                    default:
                    {
                        return(RedirectToRoute("HomePage"));
                    }
                    }
                }

                //errors
                foreach (var error in registrationResult.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            //If we got this far, something failed, redisplay form

            //           model = _customerModelFactory.PrepareRegisterModel( model, true, customerAttributesXml);
            //           return View("PaidMemberShip" , model);

            return(null);
        }
Esempio n. 23
0
        public IActionResult SignUp(SignUpPostModel model, string returnUrl, bool captchaValid)
        {
            //check whether registration is allowed
            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }

            if (_workContext.CurrentCustomer.IsRegistered())
            {
                //Already registered customer.
                _authenticationService.SignOut();

                //raise logged out event
                _eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));

                //Save a new record
                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
            }
            var customer = _workContext.CurrentCustomer;

            //custom customer attributes
            //var customerAttributesXml = ParseCustomCustomerAttributes(model.Form);
            //var customerAttributeWarnings = _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);
            //foreach (var error in customerAttributeWarnings)
            //{
            //    ModelState.AddModelError("", error);
            //}

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (ModelState.IsValid)
            {
                var isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var registrationRequest = new CustomerRegistrationRequest(customer,
                                                                          model.Email,
                                                                          model.Username,
                                                                          model.Password,
                                                                          _customerSettings.DefaultPasswordFormat,
                                                                          isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    //login customer now
                    if (isApproved)
                    {
                        _authenticationService.SignIn(customer, true);
                    }

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

                    switch (_customerSettings.UserRegistrationType)
                    {
                    case UserRegistrationType.EmailValidation:
                    {
                        //email validation message
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                        //_workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                        //result
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.EmailValidation }));
                    }

                    case UserRegistrationType.AdminApproval:
                    {
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.AdminApproval }));
                    }

                    case UserRegistrationType.Standard:
                    {
                        //send customer welcome message
                        //_workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                        var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                        if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + WebUtility.UrlEncode(returnUrl), null);
                        }
                        return(Redirect(redirectUrl));
                    }

                    default:
                    {
                        return(RedirectToRoute("HomePage"));
                    }
                    }
                }

                //errors
                foreach (var error in registrationResult.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            //If we got this far, something failed, redisplay form
            model = _customerModelFactory.PrepareRegisterModel(model, true, setDefaultValues: true);
            return(View(model));
        }
Esempio n. 24
0
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound = _openAuthenticationService.GetUser(parameters);

            var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
                {
                    // The person is trying to log in as himself.. bit weird
                    return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
                }

                var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                result.AddError("Account is already assigned");
                return(result);
            }
            if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);

                if (AutoRegistrationIsEnabled())
                {
                    #region Register user

                    var currentCustomer = _workContext.CurrentCustomer;
                    var details         = new RegistrationDetails(parameters);
                    var randomPassword  = CommonHelper.GenerateRandomDigitCode(20);


                    bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;

                    var customer = _customerService.GetCustomerByEmail(details.EmailAddress);
                    if (customer != null)
                    {
                        //migrate shopping cart
                        _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, customer);
                        _authenticationService.SignIn(customer, false);
                        var result = new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon);
                        return(result);
                    }
                    else
                    {
                        var registrationRequest = new CustomerRegistrationRequest(currentCustomer, details.EmailAddress,
                                                                                  _customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress, randomPassword, PasswordFormat.Clear, isApproved);
                        var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                        if (registrationResult.Success)
                        {
                            //store other parameters (form fields)
                            if (!String.IsNullOrEmpty(details.FirstName))
                            {
                                _customerService.SaveCustomerAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.FirstName);
                            }
                            if (!String.IsNullOrEmpty(details.LastName))
                            {
                                _customerService.SaveCustomerAttribute(currentCustomer, SystemCustomerAttributeNames.LastName, details.LastName);
                            }


                            userFound = currentCustomer;
                            _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                            ExternalAuthorizerHelper.RemoveParameters();

                            //code below is copied from CustomerController.Register method

                            //authenticate
                            if (isApproved)
                            {
                                _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                            }

                            //notifications
                            if (_customerSettings.NotifyNewCustomerRegistration)
                            {
                                _workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);
                            }

                            switch (_customerSettings.UserRegistrationType)
                            {
                            case UserRegistrationType.EmailValidation:
                            {
                                //email validation message
                                _customerService.SaveCustomerAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                                _workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                                //result
                                return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation));
                            }

                            case UserRegistrationType.AdminApproval:
                            {
                                //result
                                return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval));
                            }

                            case UserRegistrationType.Standard:
                            {
                                //send customer welcome message
                                _workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                                //result
                                return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                            }

                            default:
                                break;
                            }
                        }
                        else
                        {
                            ExternalAuthorizerHelper.RemoveParameters();

                            var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                            foreach (var error in registrationResult.Errors)
                            {
                                result.AddError(string.Format(error));
                            }
                            return(result);
                        }
                    }
                    #endregion
                }
                else if (RegistrationIsEnabled())
                {
                    return(new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon));
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();

                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    result.AddError("Registration is disabled");
                    return(result);
                }
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
            }

            //migrate shopping cart
            _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn);
            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
Esempio n. 25
0
        public AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound    = _openAuthenticationService.GetUser(parameters);
            var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;

            if (AccountAlreadyExists(userFound, userLoggedIn))
            {
                if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
                {
                    return(new External.AuthorizationResult(OpenAuthenticationStatus.Authenticated));
                }

                var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                result.AddError("Account is already assigned");
                return(result);
            }
            if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
            {
                ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);

                if (AutoRegistrationIsEnabled())
                {
                    var currentCustomer = _workContext.CurrentCustomer;
                    var details         = new RegistrationDetails(parameters);
                    var randomPassword  = CommonHelper.GenerateRandomDigitCode(20);

                    bool isApproved =
                        //standard registration
                        (_customerSettings.UserRegistrationType == UserRegistrationType.Standard) ||
                        //skip email validation?
                        (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation &&
                         !_externalAuthenticationSettings.RequireEmailValidation);

                    var registrationRequest = new CustomerRegistrationRequest(currentCustomer,
                                                                              details.EmailAddress,
                                                                              _customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress,
                                                                              randomPassword,
                                                                              PasswordFormat.Clear,
                                                                              _storeContext.CurrentStore.Id,
                                                                              isApproved);

                    var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                    if (registrationResult.Success)
                    {
                        //store other parameters (form fields)
                        if (!String.IsNullOrEmpty(details.FirstName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.FirstName);
                        }
                        if (!String.IsNullOrEmpty(details.LastName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.LastName, details.LastName);
                        }

                        userFound = currentCustomer;
                        _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
                        ExternalAuthorizerHelper.RemoveParameters();

                        if (isApproved)
                        {
                            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
                        }

                        if (_customerSettings.NotifyNewCustomerRegistration)
                        {
                            _workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);
                        }

                        _eventPublisher.Publish(new CustomerRegisteredEvent(currentCustomer));

                        if (isApproved)
                        {
                            //standard registration
                            //or
                            //skip email validation

                            //send customer welcome message
                            _workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id);

                            //result
                            return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                        }
                        else if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                            _workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id);
                        }
                        else if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
                        {
                            return(new External.AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval));
                        }
                    }
                    else
                    {
                        ExternalAuthorizerHelper.RemoveParameters();

                        var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                        foreach (var error in registrationResult.Errors)
                        {
                            result.AddError(string.Format(error));
                        }
                        return(result);
                    }
                }
                else if (RegistrationIsEnabled())
                {
                    return(new External.AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon));
                }
                else
                {
                    ExternalAuthorizerHelper.RemoveParameters();

                    var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
                    result.AddError("Registration is disabled");
                    return(result);
                }
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
            }

            //migrate shopping cart
            _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn, true);
            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //raise event
            _eventPublisher.Publish(new CustomerLoggedinEvent(userFound ?? userLoggedIn));
            //activity log
            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
                                                    userFound ?? userLoggedIn);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual IActionResult RegisterNewUser(ExternalAuthenticationParameters parameters, string returnUrl)
        {
            //check whether the specified email has been already registered
            if (_customerService.GetCustomerByEmail(parameters.Email) != null)
            {
                var alreadyExistsError = string.Format(_localizationService.GetResource("Account.AssociatedExternalAuth.EmailAlreadyExists"),
                                                       !string.IsNullOrEmpty(parameters.ExternalDisplayIdentifier) ? parameters.ExternalDisplayIdentifier : parameters.ExternalIdentifier);
                return(ErrorAuthentication(new[] { alreadyExistsError }, returnUrl));
            }

            //registration is approved if validation isn't required
            var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                                         (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && !_externalAuthenticationSettings.RequireEmailValidation);

            //create registration request
            var registrationRequest = new CustomerRegistrationRequest(_workContext.CurrentCustomer,
                                                                      parameters.Email, parameters.Email,
                                                                      CommonHelper.GenerateRandomDigitCode(20),
                                                                      PasswordFormat.Clear,
                                                                      _storeContext.CurrentStore.Id,
                                                                      registrationIsApproved);

            //whether registration request has been completed successfully
            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);

            if (!registrationResult.Success)
            {
                return(ErrorAuthentication(registrationResult.Errors, returnUrl));
            }

            //allow to save other customer values by consuming this event
            _eventPublisher.Publish(new CustomerAutoRegisteredByExternalMethodEvent(_workContext.CurrentCustomer, parameters));

            //raise customer registered event
            _eventPublisher.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));

            //store owner notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                _workflowMessageService.SendCustomerRegisteredNotificationMessage(_workContext.CurrentCustomer, _localizationSettings.DefaultAdminLanguageId);
            }

            //associate external account with registered user
            AssociateExternalAccountWithUser(_workContext.CurrentCustomer, parameters);

            //authenticate
            if (registrationIsApproved)
            {
                _authenticationService.SignIn(_workContext.CurrentCustomer, false);
                _workflowMessageService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }));
            }

            //registration is succeeded but isn't activated
            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                //email validation message
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, GSCustomerDefaults.AccountActivationTokenAttribute, Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailValidationMessage(_workContext.CurrentCustomer, _workContext.WorkingLanguage.Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            return(ErrorAuthentication(new[] { "Error on registration" }, returnUrl));
        }
Esempio n. 27
0
        public HttpResponseMessage Register(RegisterModel model)
        {
            var response = this.Request.CreateResponse(HttpStatusCode.OK);

            try
            {
                string jsonString = "";
                var    Sponsors   = _customerService.GetCustomerByUsername(model.SponsorsName);
                //check whether registration is allowed
                if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
                {
                    //Registrition Disable
                    //(int)UserRegistrationType.Disabled
                }

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

                if (_customerSettings.UsernamesEnabled && model.Username != null)
                {
                    model.Username = model.Username.Trim();
                }
                customer.AffiliateId  = Sponsors.Id;
                customer.SponsorsName = model.SponsorsName;
                bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var  registrationRequest = new CustomerRegistrationRequest(customer, model.Email,
                                                                           _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, _customerSettings.DefaultPasswordFormat, isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    // properties
                    if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                    }

                    // form fields
                    if (_customerSettings.GenderEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                    }
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                    if (_customerSettings.DateOfBirthEnabled)
                    {
                        DateTime?dateOfBirth = null;
                        try
                        {
                            dateOfBirth = new DateTime(model.DateOfBirthYear.Value, model.DateOfBirthMonth.Value, model.DateOfBirthDay.Value);
                        }
                        catch { }
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
                    }

                    if (_customerSettings.CountryEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
                    }
                    if (_customerSettings.PhoneEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                    }
                    if (_customerSettings.CustomerNumberMethod == CustomerNumberMethod.AutomaticallySet && String.IsNullOrEmpty(customer.GetAttribute <string>(SystemCustomerAttributeNames.CustomerNumber)))
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomerNumber, customer.Id);
                    }

                    // Notifications
                    if (_customerSettings.NotifyNewCustomerRegistration)
                    {
                        Services.MessageFactory.SendCustomerRegisteredNotificationMessage(customer, _localizationSettings.DefaultAdminLanguageId);
                    }

                    Services.MessageFactory.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                    if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
                    {
                        // email validation message
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                        Services.MessageFactory.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);
                        var subscription = new NewsLetterSubscription
                        {
                            NewsLetterSubscriptionGuid = Guid.NewGuid(),
                            Email        = customer.Email,
                            Active       = false,
                            CreatedOnUtc = DateTime.UtcNow,
                            StoreId      = _storeContext.CurrentStore.Id
                        };

                        _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
                        //return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation });
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 1, Message = _localizationService.GetResource("Customer.VerifyEmail") }));
                    }
                    else if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = _localizationService.GetResource("Customer.AdminApproval") }));
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = "success", GUID = customer.CustomerGuid }));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new { code = 0, Message = registrationResult.Errors[0] }));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { code = 1, Message = "Something went wrong, Ex:" + ex.ToString() }));
            }
        }