Ejemplo n.º 1
0
        public ActionResult Register(AccountRegister model)
        {
            // TODO check if user already registered

            if (ModelState.IsValid)
            {
                User user = new User()
                {
                    Email      = model.Email,
                    Username   = model.Username,
                    Password   = model.Password,
                    IsActive   = true,
                    InsertedOn = DateTime.Now
                };


                var registrationResult = _userRegistrationService.RegisterUser(user);
                if (registrationResult.Success)
                {
                    _authenticationService.SignIn(user, true);
                    return(RedirectToAction("Index", "Home"));
                }

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

            return(View(model));
        }
Ejemplo n.º 2
0
        public virtual async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserRegistrationResult Result = _userRegistrationService.RegisterUser(model);


                if (Result.Success)
                {
                    //await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent: false);

                    //return RedirectToAction("Index", "Dashboard");
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(Result.NewlyRegistredUser);

                    var callbackUrl = Url.Action(
                        action: "RegistrationConfirmation",
                        controller: "Authentication",
                        values: new { userId = Result.NewlyRegistredUser.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(model.UserEmail, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    model.RegistrationConfirmationSent = true;
                }
                else
                {
                    foreach (var item in Result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, item);
                    }
                }
            }
            return(View(model));
        }
Ejemplo n.º 3
0
        public virtual IActionResult Register(RegisterModel model, string returnUrl)
        {
            if (_workContext.CurrentUser != null)
            {
                //Already registered user.
                _authenticationService.SignOut();

                //raise logged out event
                _eventPublisher.Publish(new UserLoggedOutEvent(_workContext.CurrentUser));
            }

            //Save a new record
            _workContext.CurrentUser = new User
            {
                CreatedOnUtc        = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow
            };

            var user = _workContext.CurrentUser;

            if (ModelState.IsValid)
            {
                var registrationRequest = new UserRegistrationRequest(user,
                                                                      model.Email,
                                                                      model.Password);
                var registrationResult = _userRegistrationService.RegisterUser(registrationRequest);
                if (registrationResult.Success)
                {
                    _genericAttributeService.SaveAttribute(user, AldanUserDefaults.FirstNameAttribute, model.FirstName);
                    _genericAttributeService.SaveAttribute(user, AldanUserDefaults.LastNameAttribute, model.LastName);

                    _authenticationService.SignIn(user, true);

                    _workflowMessageService.SendUserRegisteredNotificationMessage(user);

                    //raise event
                    _eventPublisher.Publish(new UserRegisteredEvent(user));

                    //send user welcome message
                    _workflowMessageService.SendUserWelcomeMessage(user);

                    var redirectUrl = Url.RouteUrl("RegisterResult",
                                                   new { returnUrl },
                                                   _webHelper.CurrentRequestProtocol);
                    return(Redirect(redirectUrl));
                }

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

            //If we got this far, something failed, redisplay form
            model = _userModelFactory.PrepareRegisterModel(model);
            return(View(model));
        }
Ejemplo n.º 4
0
        public ActionResult Register(RegisterModel model, string returnUrl, FormCollection form)
        {
            if (_workContext.CurrentUser.IsRegistered())
            {
                //Already registered customer.
                _authenticationService.SignOut();

                //Save a new record
                _workContext.CurrentUser = _userService.InsertGuestUser();
            }

            var user = _workContext.CurrentUser;

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

                var registrationRequest = new UserRegistrationRequest(user,
                                                                      model.Email,
                                                                      model.Email,
                                                                      model.Password,
                                                                      PasswordFormat.Hashed,
                                                                      true);
                var registrationResult = _userRegistrationService.RegisterUser(registrationRequest);
                if (registrationResult.Success)
                {
                    _genericAttributeService.SaveAttribute(user, SystemUserAttributeNames.Gender, model.Gender);
                    _genericAttributeService.SaveAttribute(user, SystemUserAttributeNames.FirstName, model.FirstName);
                    _genericAttributeService.SaveAttribute(user, SystemUserAttributeNames.LastName, model.LastName);

                    _authenticationService.SignIn(user, true);

                    // TODO регистрация через email
                    // стандартная регистрация
                    var redirectToResult = Url.RouteUrl("RegisterResult");
                    return(Redirect(redirectToResult));
                }

                // ошибки
                foreach (var error in registrationResult.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            PrepareUserRegisterModel(model);
            return(View(model));
        }
Ejemplo n.º 5
0
        public JsonResult Add(UserModel model)
        {
            UserRegistrationRequest request = new UserRegistrationRequest();

            TypeAdapter.Adapt(model, request);
            foreach (var roleId in model.SelectedRoles)
            {
                request.Roles.Add(new UserRole()
                {
                    Id = roleId
                });
            }
            var result = _userRegistrationService.RegisterUser(request);

            return(Json(result));
        }
Ejemplo n.º 6
0
        public virtual async Task <IActionResult> Register(RegisterViewModel model)
        {
            RedirectToActionResult RedirectNextPage = RedirectToAction("Register", "Home");

            if (ModelState.IsValid)
            {
                UserRegistrationResult Result = _userRegistrationService.RegisterUser(model);

                if (Result.Success)
                {
                    await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent : false);

                    RedirectNextPage = RedirectToUserPortalByRole(model.RoleDefault);
                }
            }
            return(RedirectNextPage);
        }
        public async Task <ActionResult> Create(User_Model model)
        {
            if (ModelState.IsValid)
            {
                var user = new User()
                {
                    UserGuid    = Guid.NewGuid(),
                    Username    = model.UserName,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    PhoneNumber = model.PhoneNumber,
                    Active      = model.Active,
                    //DepartmentId = model.Roles.Any(r => r.Name ==  "Administrators") ? 0 : model.Department.Id
                };

                foreach (var department in model.Departments)
                {
                    var d = _departmentService.GetByIdAsync(department.Id).Result;
                    user.Departments.Add(d);
                }

                foreach (var role in model.Roles)
                {
                    var userRole = _userService.GetUserRoleByIdAsync(role.Id);
                    user.UserRoles.Add(userRole);
                }

                var result = await _userRegistrationService.RegisterUser(new UserRegistrationRequest(user, model.Email, model.UserName, model.Password));

                if (!result.Success)
                {
                    return(Content(string.Join(", ", result.Errors)));
                }
                else
                {
                    return(Json(new{ status = "success" }));
                }
            }

            // If we got this far, something failed, redisplay form
            return(Json(new { Data = new[] { model } }));
            //return View(model);
        }
Ejemplo n.º 8
0
        public virtual IActionResult Register(RegisterModel model)
        {
            //check whether registration is allowed
            //var user = _workContext.CurrentUser;
            var user = new User()
            {
                Active           = true,
                Deleted          = false,
                LastActivityDate = DateTime.Now,
                CreatedOn        = DateTime.Now,
            };

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

                var isApproved          = _userSettings.UserRegistrationType == UserRegistrationType.Standard;
                var registrationRequest = new UserRegistrationRequest(user,
                                                                      model.Username,
                                                                      model.Email,
                                                                      model.Phone,
                                                                      model.Password,
                                                                      _userSettings.DefaultPasswordFormat,
                                                                      isApproved);
                var registrationResult = _userRegistrationService.RegisterUser(registrationRequest);
                if (registrationResult.Success)
                {
                    //login user now
                    //if (isApproved)
                    //    _authenticationService.SignIn(user, true);
                    var userModel = this._userModelFactory.PrepareUserModel(user);
                    return(Result(userModel));
                }
                return(Result(null, false, 9, registrationResult.Errors.FirstOrDefault()));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> PostRegister(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                UserRegistrationRequest request = new UserRegistrationRequest(model.FirstName, model.LastName, model.PhoneNumber,
                                                                              model.Email, model.BirthDate, model.Password, "InnoloftUser");

                var response = await _userRegistrationService.RegisterUser(request);

                if (response.Success)
                {
                    return(Ok(response));
                }
                foreach (var e in response.Errors)
                {
                    ModelState.AddModelError(string.Empty, e);
                }
            }

            return(BadRequest(ModelState));
        }
Ejemplo n.º 10
0
        public virtual async Task <IActionResult> RegisterAgent(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserRegistrationResult Result = _userRegistrationService.RegisterUser(model);


                if (Result.Success)
                {
                    await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent : false);

                    return(RedirectToAction("Index", "Dashboard"));
                }
                else
                {
                    foreach (var item in Result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, item);
                    }
                }
            }
            return(View());
        }
Ejemplo n.º 11
0
        public virtual IActionResult Register(RegisterModel model, string returnUrl)
        {
            var form = model.Form;

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

            if (_workContext.CurrentUser.IsRegistered())
            {
                //Already registered user.
                _authenticationService.SignOut();

                //raise logged out event
                _eventPublisher.Publish(new UserLoggedOutEvent(_workContext.CurrentUser));

                //Save a new record
                _workContext.CurrentUser = _userService.InsertGuestUser();
            }
            var user = _workContext.CurrentUser;

            if (ModelState.IsValid)
            {
                // user.UserGuid = Guid.NewGuid();
                user.FirstName  = model.FirstName;
                user.LastName   = model.LastName;
                user.TitleId    = model.TitleId;
                user.AgencyId   = model.AgencyId;
                user.UserTypeId = (int)UserType.Researchers;
                user.Roles      = UserType.Researchers.ToString();
                var isApproved          = _userSettings.UserRegistrationType == UserRegistrationType.EmailValidation;
                var registrationRequest = new UserRegistrationRequest(user,
                                                                      model.Email,
                                                                      model.IDCard,
                                                                      model.Password,
                                                                      _userService.GetNextNumber(),
                                                                      model.Gender,
                                                                      _userSettings.DefaultPasswordFormat,
                                                                      isApproved);
                var registrationResult = _userRegistrationService.RegisterUser(registrationRequest);
                if (registrationResult.Success)
                {
                    //login user now
                    if (isApproved)
                    {
                        _authenticationService.SignIn(user, true);
                    }


                    //raise event
                    _eventPublisher.Publish(new UserRegisteredEvent(user));

                    switch (_userSettings.UserRegistrationType)
                    {
                    case UserRegistrationType.EmailValidation:
                    {
                        //email validation message
                        _genericAttributeService.SaveAttribute(user, ResearchUserDefaults.AccountActivationTokenAttribute, Guid.NewGuid().ToString());

                        _workflowMessageService.SendUserEmailValidationMessage(user, 0);
                        var scheduleTask = _scheduleTaskService.GetTaskById(1);
                        var task         = new Task(scheduleTask)
                        {
                            Enabled = true
                        };
                        task.Execute(true, false);
                        //result
                        return(RedirectToAction("RegisterResult", "User", new { resultId = (int)UserRegistrationType.EmailValidation }));
                        //return RedirectToRoute("RegisterResult",
                        //    new { resultId = (int)UserRegistrationType.EmailValidation });
                    }

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

                    case UserRegistrationType.Standard:
                    {
                        //send user welcome message
                        //chai
                        _workflowMessageService.SendUserWelcomeMessage(user, 0);

                        var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }, _webHelper.CurrentRequestProtocol);
                        if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl", returnUrl);
                        }
                        //return Redirect(redirectUrl);


                        return(RedirectToAction("Login", "User"));
                    }

                    default:
                    {
                        return(RedirectToAction("Login", "User"));
                        //return RedirectToRoute("HomePage");
                    }
                    }
                }

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

            //If we got this far, something failed, redisplay form
            model = _userModelFactory.PrepareRegisterModel(model);
            return(View(model));
        }
Ejemplo n.º 12
0
        //available even when navigation is not allowed
        //[PublicStoreAllowNavigation(true)]
        public virtual ActionResult Register(RegisterModel model, string returnUrl, bool captchaValid, FormCollection form)
        {
            //check whether registration is allowed
            if (_userSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }

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

                //raise logged out event
                _eventPublisher.Publish(new UserLoggedOutEvent(_workContext.CurrentUser));

                //Save a new record
                // _workContext.CurrentUser = _userService.InsertGuestCustomer();
            }
            var customer = _workContext.CurrentUser;
            //customer.RegisteredInStoreId = _storeContext.CurrentStore.Id;

            //custom customer attributes
            var customerAttributesXml     = ParseCustomUserAttributes(form);
            var customerAttributeWarnings = _userAttributeParser.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 (_userSettings.UsernamesEnabled && model.Username != null)
                {
                    model.Username = model.Username.Trim();
                }

                bool isApproved          = _userSettings.UserRegistrationType == UserRegistrationType.Standard;
                var  registrationRequest = new UserRegistrationRequest(customer,
                                                                       model.Email,
                                                                       _userSettings.UsernamesEnabled ? model.Username : model.Email,
                                                                       model.Password,
                                                                       _userSettings.DefaultPasswordFormat,
                                                                       0,
                                                                       isApproved);
                var registrationResult = _userRegistrationService.RegisterUser(registrationRequest);
                if (registrationResult.Success)
                {
                    //properties
                    if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemUserAttributeNames.TimeZoneId, model.TimeZoneId);
                    }

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


                    //save customer attributes
                    _genericAttributeService.SaveAttribute(customer, SystemUserAttributeNames.CustomUserAttributes, customerAttributesXml);

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



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

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

                    switch (_userSettings.UserRegistrationType)
                    {
                    case UserRegistrationType.EmailValidation:
                    {
                        //email validation message
                        _genericAttributeService.SaveAttribute(customer, SystemUserAttributeNames.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 = _userModelFactory.PrepareRegisterModel(model, true, customerAttributesXml);
            return(View(model));
        }
Ejemplo n.º 13
0
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound = _openAuthenticationService.GetUser(parameters);

            var userLoggedIn = _workContext.CurrentUser.IsRegistered() ? _workContext.CurrentUser : 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 currentUser    = _workContext.CurrentUser;
                    var details        = new RegistrationDetails(parameters);
                    var randomPassword = CommonHelper.GenerateRandomDigitCode(20);


                    bool isApproved          = _userSettings.UserRegistrationType == UserRegistrationType.Standard;
                    var  registrationRequest = new UserRegistrationRequest(currentUser, details.EmailAddress,
                                                                           _userSettings.UsernamesEnabled ? details.UserName : details.EmailAddress, randomPassword, PasswordFormat.Clear,
                                                                           details.FirstName, details.LastName, isApproved);
                    var registrationResult = _userRegistrationService.RegisterUser(registrationRequest);
                    if (registrationResult.Success)
                    {
                        //store other parameters (form fields)
                        if (!String.IsNullOrEmpty(details.FirstName))
                        {
                            _genericAttributeService.SaveAttribute(currentUser, SystemUserAttributeNames.FirstName, details.FirstName);
                        }
                        if (!String.IsNullOrEmpty(details.LastName))
                        {
                            _genericAttributeService.SaveAttribute(currentUser, SystemUserAttributeNames.LastName, details.LastName);
                        }


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

                        //code below is copied from UserController.Register method

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

                        //notifications
                        if (_userSettings.NotifyNewUserRegistration)
                        {
                            _workflowMessageService.SendUserRegisteredNotificationMessage(currentUser, _localizationSettings.DefaultAdminLanguageId);
                        }

                        switch (_userSettings.UserRegistrationType)
                        {
                        case UserRegistrationType.EmailValidation:
                        {
                            //email validation message
                            _genericAttributeService.SaveAttribute(currentUser, SystemUserAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                            _workflowMessageService.SendUserEmailValidationMessage(currentUser, _workContext.WorkingLanguage.Id);

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

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

                        case UserRegistrationType.Standard:
                        {
                            //send user welcome message
                            _workflowMessageService.SendUserWelcomeMessage(currentUser, _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.CurrentUser, userFound ?? userLoggedIn);
            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //activity log
            _userActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
                                                userFound ?? userLoggedIn);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
Ejemplo n.º 14
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)
        {
            //check whether the specified email has been already registered
            if (_userService.GetUserByEmail(parameters.Email) != null)
            {
                var alreadyExistsError = string.Format("A user with the specified email has been already registered. If this is your account, and you want to associate it with '{0}' external record, please login firstly.",
                                                       !string.IsNullOrEmpty(parameters.ExternalDisplayIdentifier) ? parameters.ExternalDisplayIdentifier : parameters.ExternalIdentifier);
                return(ErrorAuthentication(new[] { alreadyExistsError }, returnUrl));
            }

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

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

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

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

            //allow to save other user values by consuming this event
            _eventPublisher.Publish(new UserAutoRegisteredByExternalMethodEvent(_workContext.CurrentUser, parameters));

            //raise vustomer registered event
            _eventPublisher.Publish(new UserRegisteredEvent(_workContext.CurrentUser));

            //site owner notifications
            //if (_userSettings.NotifyNewUserRegistration)
            //_workflowMessageService.SendUserRegisteredNotificationMessage(_workContext.CurrentUser, _localizationSettings.DefaultAdminLanguageId);

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

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

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

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

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

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

            return(ErrorAuthentication(new[] { "Error on registration" }, returnUrl));
        }