/// <summary>
        /// Accociate external account with customer
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="parameters">Open authentication parameters</param>
        public virtual void AssociateExternalAccountWithUser(Customer customer, OpenAuthenticationParameters parameters)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            //find email
            string email = null;

            if (parameters.UserClaims != null)
            {
                foreach (var userClaim in parameters.UserClaims
                         .Where(x => x.Contact != null && !String.IsNullOrEmpty(x.Contact.Email)))
                {
                    //found
                    email = userClaim.Contact.Email;
                    break;
                }
            }

            var externalAuthenticationRecord = new ExternalAuthenticationRecord
            {
                CustomerId                = customer.Id,
                Email                     = email,
                ExternalIdentifier        = parameters.ExternalIdentifier,
                ExternalDisplayIdentifier = parameters.ExternalDisplayIdentifier,
                OAuthToken                = parameters.OAuthToken,
                OAuthAccessToken          = parameters.OAuthAccessToken,
                ProviderSystemName        = parameters.ProviderSystemName,
            };

            _externalAuthenticationRecordRepository.Insert(externalAuthenticationRecord);
        }
        public virtual void AssociateExternalAccountWithUser(Customer customer, OpenAuthenticationParameters parameters)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");

            //find email
            string email = null;
            if (parameters.UserClaims != null)
                foreach (var userClaim in parameters.UserClaims
                    .Where(x => x.Contact != null && !String.IsNullOrEmpty(x.Contact.Email)))
                    {
                        //found
                        email = userClaim.Contact.Email;
                        break;
                    }

            var externalAuthenticationRecord = new ExternalAuthenticationRecord()
            {
                CustomerId = customer.Id,
                Email = email,
                ExternalIdentifier = parameters.ExternalIdentifier,
                ExternalDisplayIdentifier = parameters.ExternalDisplayIdentifier,
                OAuthToken = parameters.OAuthToken,
                OAuthAccessToken = parameters.OAuthAccessToken,
                ProviderSystemName = parameters.ProviderSystemName,
            };

            _externalAuthenticationRecordRepository.Insert(externalAuthenticationRecord);
        }
        /// <summary>
        /// Remove the association
        /// </summary>
        /// <param name="parameters">Open authentication parameters</param>
        public virtual void RemoveAssociation(OpenAuthenticationParameters parameters)
        {
            var record = _externalAuthenticationRecordRepository.Table
                         .FirstOrDefault(o => o.ExternalIdentifier == parameters.ExternalIdentifier &&
                                         o.ProviderSystemName == parameters.ProviderSystemName);

            if (record != null)
            {
                _externalAuthenticationRecordRepository.Delete(record);
            }
        }
        /// <summary>
        /// Get the particular user with specified parameters
        /// </summary>
        /// <param name="parameters">Open authentication parameters</param>
        /// <returns>Customer</returns>
        public virtual Customer GetUser(OpenAuthenticationParameters parameters)
        {
            var record = _externalAuthenticationRecordRepository.Table
                         .FirstOrDefault(o => o.ExternalIdentifier == parameters.ExternalIdentifier &&
                                         o.ProviderSystemName == parameters.ProviderSystemName);

            if (record != null)
            {
                return(_customerService.GetCustomerById(record.CustomerId));
            }

            return(null);
        }
        /// <summary>
        /// ´æ´¢²ÎÊýÍù·µ
        /// </summary>
        /// <param name="parameters"></param>
        public static void StoreParametersForRoundTrip(OpenAuthenticationParameters parameters)
        {
            var session = GetSession();

            session["nop.externalauth.parameters"] = parameters;
        }
Example #6
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 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))
                            _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();

                        //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);
            }

            //migrate shopping cart
            _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn, true);
            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //activity log
            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"), 
                userFound ?? userLoggedIn);
            
            return new AuthorizationResult(OpenAuthenticationStatus.Authenticated);
        }
Example #7
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));
        }
        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));
        }
Example #9
0
 public static void StoreParametersForRoundTrip(OpenAuthenticationParameters parameters)
 {
     var session = GetSession();
     session["nop.externalauth.parameters"] = parameters;
 }
 /// <summary>
 /// Check that account exists
 /// </summary>
 /// <param name="parameters">Open authentication parameters</param>
 /// <returns>True if it exists; otherwise false</returns>
 public virtual bool AccountExists(OpenAuthenticationParameters parameters)
 {
     return(GetUser(parameters) != null);
 }
        public virtual Customer GetUser(OpenAuthenticationParameters parameters)
        {
            var record = _externalAuthenticationRecordRepository.Table
                .Where(o => o.ExternalIdentifier == parameters.ExternalIdentifier && o.ProviderSystemName == parameters.ProviderSystemName)
                .FirstOrDefault();

            if (record != null)
                return _customerService.GetCustomerById(record.CustomerId);

            return null;
        }
 public virtual bool AccountExists(OpenAuthenticationParameters parameters)
 {
     return GetUser(parameters) != null;
 }
        public virtual void RemoveAssociation(OpenAuthenticationParameters parameters)
        {
            var record = _externalAuthenticationRecordRepository.Table
                .Where(o => o.ExternalIdentifier == parameters.ExternalIdentifier && o.ProviderSystemName == parameters.ProviderSystemName)
                .FirstOrDefault();

            if (record != null)
                _externalAuthenticationRecordRepository.Delete(record);
        }
Example #14
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));
        }
Example #15
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 currentCustomer = _workContext.CurrentUser;
                    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 UserRegistrationRequest(currentCustomer,
                                                                          details.EmailAddress,
                                                                          _customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress,
                                                                          randomPassword,
                                                                          PasswordFormat.Clear,
                                                                          0, // _storeContext.CurrentStore.Id,
                                                                          isApproved);
                    var registrationResult = _customerRegistrationService.RegisterUser(registrationRequest);
                    if (registrationResult.Success)
                    {
                        //store other parameters (form fields)
                        if (!String.IsNullOrEmpty(details.FirstName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemUserAttributeNames.FirstName, details.FirstName);
                        }
                        if (!String.IsNullOrEmpty(details.LastName))
                        {
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemUserAttributeNames.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.NotifyNewUserRegistration)
                        //_workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);

                        //raise event
                        _eventPublisher.Publish(new UserRegisteredEvent(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)
                        {
                            //email validation message
                            _genericAttributeService.SaveAttribute(currentCustomer, SystemUserAttributeNames.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);
            }

            //authenticate
            _authenticationService.SignIn(userFound ?? userLoggedIn, false);
            //raise event
            _eventPublisher.Publish(new UserLoggedinEvent(userFound ?? userLoggedIn));
            //activity log
            _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
                                                    userFound ?? userLoggedIn);

            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }