コード例 #1
0
        public Customer GetUser(WeChatUserInfo userInfo)
        {
            var parameters = new OAuthAuthenticationParameters(Provider.SystemName)
            {
                ExternalIdentifier        = userInfo.openid,
                ExternalDisplayIdentifier = userInfo.unionid,
            };

            return(_openAuthenticationService.GetUser(parameters));
        }
コード例 #2
0
        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));
        }
コード例 #3
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));
        }
コード例 #4
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));
        }
コード例 #5
0
        private AuthorizeState VerifyCode(string returnUrl)
        {
            var state = _httpContext.Request.QueryString["state"];

            var errorState = new AuthorizeState(returnUrl, OpenAuthenticationStatus.Error);

            string appId, appSecret;

            if (state == (string)Session["nop.externalauth.weixin.authentication.native"])
            {
                Session.Remove(("nop.externalauth.weixin.authentication.native"));
                appId     = _weiXinExternalAuthSettings.AppId;
                appSecret = _weiXinExternalAuthSettings.AppSecret;
            }
            else if (state == (string)Session["nop.externalauth.weixin.authentication.web"])
            {
                Session.Remove(("nop.externalauth.weixin.authentication.web"));
                appId     = _weiXinExternalAuthSettings.WebAppId;
                appSecret = _weiXinExternalAuthSettings.WebAppSecret;
            }
            else
            {
                errorState.AddError("State not matching");
                return(errorState);
            }
            var authResult = WeiXinApplication.VerifyCode(_httpContext, GenerateLocalCallbackUri());

            if (authResult.IsSuccessful)
            {
                if (!authResult.ExtraData.ContainsKey("code"))
                {
                    throw new Exception("Authentication code does not contain id data");
                }
                var code = authResult.ExtraData["code"];

                authResult = WeiXinApplication.VerifyAuthentication(GenerateLocalCallbackUri(), code, appId, appSecret);

                if (authResult.IsSuccessful)
                {
                    if (!authResult.ExtraData.ContainsKey("id"))
                    {
                        throw new Exception("Authentication result does not contain id data");
                    }

                    if (!authResult.ExtraData.ContainsKey("accesstoken"))
                    {
                        throw new Exception("Authentication result does not contain accesstoken data");
                    }

                    var parameters = new OAuthAuthenticationParameters(Provider.SystemName)
                    {
                        ExternalIdentifier        = authResult.ProviderUserId,
                        OAuthToken                = authResult.ExtraData["accesstoken"],
                        OAuthAccessToken          = authResult.ExtraData["refreshtoken"],
                        ExternalDisplayIdentifier = returnUrl
                    };

                    if (_externalAuthenticationSettings.AutoRegisterEnabled)
                    {
                        ParseClaims(authResult, parameters, new RegisterModel());
                    }

                    var user = _openAuthenticationService.GetUser(parameters);

                    //Login User
                    if (user != null)
                    {
                        var result = _authorizer.Authorize(parameters);
                        return(new AuthorizeState(returnUrl, result));
                    } // Register User
                    else
                    {
                        SaveOAuthParametersToSession(parameters);
                        return(new AuthorizeState("/Plugins/ExternalAuthWeiXin/Register",
                                                  OpenAuthenticationStatus.AutoRegisteredEmailEnter));
                    }
                }
            }

            var error = authResult.Error != null ? authResult.Error.Message : "Unknown error";

            errorState.AddError(error);
            return(errorState);
        }
コード例 #6
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));
        }
コード例 #7
0
        public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
        {
            var userFound   = _openAuthenticationService.GetUser(parameters);
            var currentUser = _userContext.CurrentUser;

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

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

                #region Register user

                currentUser = _userContext.CurrentUser;
                var details        = new RegistrationDetails(parameters);
                var randomPassword = CommonHelper.GenerateRandomDigitCode(20);

                bool isApproved = true;

                var registrationRequest = new UserRegistrationRequest(currentUser,
                                                                      details.EmailAddress,
                                                                      details.UserName,
                                                                      randomPassword,
                                                                      isApproved);

                var registrationResult = _userService.RegisterUser(registrationRequest);
                if (registrationResult.Success)
                {
                    currentUser = registrationResult.User;
                    _openAuthenticationService.AssociateSocialAccountWithUser(currentUser, parameters);
                    SocialAuthorizerHelper.RemoveParameters();

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

                    if (isApproved)
                    {
                        //send user welcome message
                        _emailService.SendUserWelcomeMessage(currentUser);

                        //result
                        return(new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard));
                    }
                }
                else
                {
                    SocialAuthorizerHelper.RemoveParameters();

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

                #endregion
            }
            if (userFound == null)
            {
                _openAuthenticationService.AssociateSocialAccountWithUser(currentUser, parameters);
            }

            //authenticate
            _authenticationService.SignIn(userFound ?? currentUser, false);
            return(new AuthorizationResult(OpenAuthenticationStatus.Authenticated));
        }
コード例 #8
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));
        }
コード例 #9
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));
        }
コード例 #10
0
 /// <summary>
 /// Get the particular user with specified parameters
 /// </summary>
 /// <param name="parameters">Open authentication parameters</param>
 /// <returns>Customer</returns>
 public Customer GetUser(OpenAuthenticationParameters parameters)
 {
     return(_openAuthenticationService.GetUser(parameters));
 }