Exemple #1
0
        /// <summary>
        /// Returns the <see cref="ActivityRegistration"/> for any activity type and activity type name.
        /// </summary>
        /// <param name="activityType">The target activity type.</param>
        /// <param name="activityTypeName">The target activity type name.</param>
        /// <returns>The <see cref="ActivityRegistration"/>.</returns>
        private static ActivityRegistration GetActivityInvokeInfo(Type activityType, string activityTypeName)
        {
            Covenant.Requires <ArgumentNullException>(activityType != null, nameof(activityType));
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(activityTypeName), nameof(activityTypeName));

            var info = new ActivityRegistration();

            // Locate the target method.  Note that the activity type name will be
            // formatted like:
            //
            //      CLIENT-ID::TYPE-NAME
            // or   CLIENT-ID::TYPE-NAME::METHOD-NAME

            var activityTypeNameParts = activityTypeName.Split(CadenceHelper.ActivityTypeMethodSeparator.ToCharArray(), 3);
            var activityMethodName    = (string)null;

            Covenant.Assert(activityTypeNameParts.Length >= 2);

            if (activityTypeNameParts.Length > 2)
            {
                activityMethodName = activityTypeNameParts[2];
            }

            if (string.IsNullOrEmpty(activityMethodName))
            {
                activityMethodName = null;
            }

            foreach (var method in activityType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
            {
                var activityMethodAttribute = method.GetCustomAttribute <ActivityMethodAttribute>();

                if (activityMethodAttribute == null)
                {
                    continue;
                }

                var name = activityMethodAttribute.Name;

                if (string.IsNullOrEmpty(name))
                {
                    name = null;
                }

                if (name == activityMethodName)
                {
                    info.ActivityMethod = method;
                    break;
                }
            }

            if (info.ActivityMethod == null)
            {
                throw new ArgumentException($"Activity type [{activityType.FullName}] does not have an entry point method tagged with [ActivityMethod(Name = \"{activityMethodName}\")].", nameof(activityType));
            }

            return(info);
        }
Exemple #2
0
        /// <summary>
        /// Constructs an activity instance suitable for executing a normal (non-local) activity.
        /// </summary>
        /// <param name="invokeInfo">The activity invocation information.</param>
        /// <param name="contextId">The activity context ID.</param>
        /// <returns>The constructed activity.</returns>
        private ActivityBase CreateNormalActivity(ActivityRegistration invokeInfo, long contextId)
        {
            var activity = (ActivityBase)ActivatorUtilities.CreateInstance(NeonHelper.ServiceContainer, invokeInfo.ActivityType);

            activity.IsLocal = false;
            activity.Initialize(this, invokeInfo.ActivityType, invokeInfo.ActivityMethod, this.Client.DataConverter, contextId);

            return(activity);
        }
Exemple #3
0
        /// <summary>
        /// Returns the <see cref="ActivityRegistration"/> for an activity type and type name.
        /// </summary>
        /// <param name="activityType">The target activity type.</param>
        /// <param name="activityTypeName">The target activity type name.</param>
        /// <returns>The <see cref="ActivityRegistration"/>.</returns>
        private ActivityRegistration GetActivityInvokeInfo(Type activityType, string activityTypeName)
        {
            Covenant.Requires <ArgumentNullException>(activityType != null, nameof(activityType));
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(activityTypeName), nameof(activityTypeName));

            var info = new ActivityRegistration();

            // Locate the target method.  Note that the activity type name will be
            // formatted like:
            //
            //      TYPE-NAME
            // or   TYPE-NAME::METHOD-NAME

            var activityMethodName = (string)null;
            var separatorPos       = activityTypeName.IndexOf("::");

            if (separatorPos != -1)
            {
                activityMethodName = activityTypeName.Substring(separatorPos + 2);

                if (string.IsNullOrEmpty(activityMethodName))
                {
                    activityMethodName = null;
                }
            }

            foreach (var method in activityType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
            {
                var activityMethodAttribute = method.GetCustomAttribute <ActivityMethodAttribute>();

                if (activityMethodAttribute == null)
                {
                    continue;
                }

                var name = activityMethodAttribute.Name;

                if (string.IsNullOrEmpty(name))
                {
                    name = null;
                }

                if (name == activityMethodName)
                {
                    info.ActivityMethod = method;
                    break;
                }
            }

            if (info.ActivityMethod == null)
            {
                throw new ArgumentException($"Activity type [{activityType.FullName}] does not have an entry point method tagged with [ActivityMethod(Name = \"{activityMethodName}\")].", nameof(activityType));
            }

            return(info);
        }
Exemple #4
0
        /// <summary>
        /// Constructs an activity instance suitable for executing a local activity.
        /// </summary>
        /// <param name="client">The associated client.</param>
        /// <param name="invokeInfo">The activity invocation information.</param>
        /// <param name="contextId">The activity context ID or <c>null</c> for local activities.</param>
        /// <returns>The constructed activity.</returns>
        private static ActivityBase Create(CadenceClient client, ActivityRegistration invokeInfo, long?contextId)
        {
            Covenant.Requires <ArgumentNullException>(client != null, nameof(client));

            var activity = (ActivityBase)(invokeInfo.ActivityConstructor.Invoke(noArgs));

            activity.Initialize(client, invokeInfo.ActivityType, invokeInfo.ActivityMethod, client.DataConverter, contextId);

            return(activity);
        }
Exemple #5
0
        /// <summary>
        /// Constructs an activity instance suitable for executing a normal activity.
        /// </summary>
        /// <param name="client">The associated client.</param>
        /// <param name="invokeInfo">The activity invocation information.</param>
        /// <param name="contextId">The activity context ID.</param>
        /// <returns>The constructed activity.</returns>
        private static ActivityBase CreateNormal(CadenceClient client, ActivityRegistration invokeInfo, long contextId)
        {
            Covenant.Requires <ArgumentNullException>(client != null, nameof(client));

            var activity = (ActivityBase)ActivatorUtilities.CreateInstance(NeonHelper.ServiceContainer, invokeInfo.ActivityType);

            activity.IsLocal = false;
            activity.Initialize(client, invokeInfo.ActivityType, invokeInfo.ActivityMethod, client.DataConverter, contextId);

            return(activity);
        }
    /// <summary>
    /// Log user activity.
    /// </summary>
    private void LogActivity()
    {
        // Create new activity for registered user
        Activity activity = new ActivityRegistration(RegisteredUser, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);

        if (activity.Data != null)
        {
            // Get contact for registered user
            int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(RegisteredUser);

            // Log contact data
            activity.Data.ContactID = contactId;
            activity.CheckViewMode  = false;
            activity.Log();
        }
    }
Exemple #7
0
    /// <summary>
    /// Logs online marketing activities.
    /// </summary>
    private void LogOMActivity(UserInfo ui)
    {
        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);

        if (activity.Data != null)
        {
            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
            activity.Log();
        }

        // Log login activity
        if (ui.Enabled)
        {
            // Log activity
            int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
            Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
            activityLogin.Log();
        }
    }
    /// <summary>
    /// Registers new user.
    /// </summary>
    /// <param name="facebookUserId">The user's Facebook ID</param>
    /// <param name="facebookAccessToken">The user's access token retrieved from Facebook</param>
    private void RegisterNewUser(string facebookUserId, string facebookAccessToken)
    {
        // Check whether additional user info page is set
        string currentSiteName = SiteContext.CurrentSiteName;

        // Register new user
        string   error = null;
        UserInfo ui    = AuthenticationHelper.AuthenticateFacebookConnectUser(facebookUserId, currentSiteName, false, true, ref error);

        // If user was found or successfuly created
        if (ui != null)
        {
            // Send registration e-mails
            // E-mail confirmation is not required as user already provided confirmation by successful login using Facebook connect
            AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

            // Notify administrator
            if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
            {
                AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
            }

            // Log user registration into the web analytics and track conversion if set
            AnalyticsHelper.TrackUserRegistration(currentSiteName, ui, TrackConversionName, ConversionValue);

            Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
            if (activity.Data != null)
            {
                activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                activity.Log();
            }

            MapFacebookUserProfile(FacebookUserProfileMappingTriggerEnum.Registration, ui, facebookUserId, facebookAccessToken);

            // Signs in created user and redirects her to the return URL
            SignInUser(ui, facebookUserId, facebookAccessToken);
        }

        lblError.Text    = error;
        lblError.Visible = true;
    }
Exemple #9
0
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error    = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);

        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = RequestContext.CurrentURL;

        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "token");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.ns");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.mode");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.return_to");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.claimed_id");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.identity");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.assoc_handle");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.realm");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.response_nonce");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.signed");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.op_endpoint");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.pape.auth_level.nist");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.sig");

        // Get OpenID response status
        switch (openIDhelper.CheckStatus())
        {
        // User is authenticated
        case CMSOpenIDHelper.RESPONSE_AUTHENTICATED:
            // Claimed ID not found  = save new user
            if (OpenIDUserInfoProvider.GetUserInfoByOpenID(openIDhelper.ClaimedIdentifier) == null)
            {
                // Check whether additional user info page is set
                string additionalInfoPage = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSRequiredOpenIDPage").Trim();

                // No page set, user can be created
                if (String.IsNullOrEmpty(additionalInfoPage))
                {
                    // Register new user
                    UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

                    // If user was found or successfuly created
                    if (ui != null)
                    {
                        // Load values submited by OpenID provider
                        // Load date of birth
                        if (openIDhelper.BirthDate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = openIDhelper.BirthDate;
                        }
                        // Load default country
                        if (openIDhelper.Culture != null)
                        {
                            ui.PreferredCultureCode = openIDhelper.Culture.Name;
                        }
                        // Load e-mail
                        if (!String.IsNullOrEmpty(openIDhelper.Email))
                        {
                            ui.Email = openIDhelper.Email;
                        }
                        // Nick name
                        if (!String.IsNullOrEmpty(openIDhelper.Nickname))
                        {
                            ui.UserSettings.UserNickName = openIDhelper.Nickname;
                        }
                        // User gender
                        if (openIDhelper.UserGender != null)
                        {
                            ui.UserSettings.UserGender = (int)openIDhelper.UserGender;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // If user is enabled
                        if (ui.Enabled)
                        {
                            // Create autentification cookie
                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openidlogin" });
                            // Log activity
                            Activity activityLogin = new ActivityUserLogin(ModuleCommands.OnlineMarketingGetUserLoginContactID(ui), ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                            activityLogin.Log();
                        }

                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using OpenID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        // Notify administrator
                        if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }
                    }

                    // Redirect when authentication was succesfull
                    if (String.IsNullOrEmpty(error))
                    {
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error otherwise
                    else
                    {
                        lblError.Text    = error;
                        lblError.Visible = true;
                    }
                }
                // Additional information page is set
                else
                {
                    // Store user object in session for additional use
                    StoreResponseInSession();

                    // Redirect to additional info page
                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        // Add return URL to parameter
                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                    }
                    URLHelper.Redirect(targetURL);
                }
            }
            // Claimed OpenID is in DB
            else
            {
                // Login existing user
                UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

                if ((ui != null) && (ui.Enabled))
                {
                    // Create autentification cookie
                    AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openilogin" });

                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();

                    // Redirect user
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                    }
                    else
                    {
                        URLHelper.Redirect(currentUrl);
                    }
                }
                // Display error which occured during authentication process
                else if (!String.IsNullOrEmpty(error))
                {
                    lblError.Text    = error;
                    lblError.Visible = true;
                }
                // Otherwise is user disabled
                else
                {
                    lblError.Text    = GetString("membership.userdisabled");
                    lblError.Visible = true;
                }
            }
            break;

        // Authentication was canceled
        case CMSOpenIDHelper.RESPONSE_CANCELED:
            lblError.Text    = GetString("openid.logincanceled");
            lblError.Visible = true;
            break;

        // Authentication failed
        case CMSOpenIDHelper.RESPONSE_FAILED:
            lblError.Text    = GetString("openid.loginfailed");
            lblError.Visible = true;
            break;
        }
    }
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(linkedInHelper.MemberId))
        {
            string currentSiteName = SiteContext.CurrentSiteName;

            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.linkedin.fillcorrectusername"))
                                                 .IsEmail(txtEmail.Text, GetString("mem.linkedin.fillvalidemail")).Result;

            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (String.IsNullOrEmpty(errorMessage)))
            {
                if (String.IsNullOrEmpty(password))
                {
                    errorMessage = GetString("mem.linkedin.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if ((String.IsNullOrEmpty(errorMessage)) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), currentSiteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if ((String.IsNullOrEmpty(errorMessage)) && UserInfoProvider.NameIsReserved(currentSiteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (String.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = DisplayMessage;
                    ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, currentSiteName, true, false, ref error);
                    DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = txtUserNameNew.Text.Trim();
                        ui.Email = txtEmail.Text;

                        if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                        }

                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Send registration e-mails
                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, password, true, SendWelcomeEmail);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(currentSiteName, ui, TrackConversionName, ConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text = errorMessage;
                plcError.Visible = true;
            }
        }
    }
    /// <summary>
    /// Logs online marketing activities.
    /// </summary>
    private void LogOMActivity(UserInfo ui)
    {
        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
        if (activity.Data != null)
        {
            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
            activity.Log();
        }

        // Log login activity
        if (ui.Enabled)
        {
            // Log activity
            int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
            Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
            activityLogin.Log();
        }
    }
    /// <summary>
    /// Registers new user.
    /// </summary>
    /// <param name="facebookUserId">The user's Facebook ID</param>
    /// <param name="facebookAccessToken">The user's access token retrieved from Facebook</param>
    private void RegisterNewUser(string facebookUserId, string facebookAccessToken)
    {
        // Check whether additional user info page is set
        string currentSiteName = SiteContext.CurrentSiteName;

        // Register new user
        string error = null;
        UserInfo ui = AuthenticationHelper.AuthenticateFacebookConnectUser(facebookUserId, currentSiteName, false, true, ref error);

        // If user was found or successfuly created
        if (ui != null)
        {
            // Send registration e-mails
            // E-mail confirmation is not required as user already provided confirmation by successful login using Facebook connect
            AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

            // Notify administrator
            if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
            {
                AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
            }

            // Log user registration into the web analytics and track conversion if set
            AnalyticsHelper.TrackUserRegistration(currentSiteName, ui, TrackConversionName, ConversionValue);

            Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
            if (activity.Data != null)
            {
                activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                activity.Log();
            }

            MapFacebookUserProfile(FacebookUserProfileMappingTriggerEnum.Registration, ui, facebookUserId, facebookAccessToken);

            // Signs in created user and redirects her to the return URL
            SignInUser(ui, facebookUserId, facebookAccessToken);
        }

        lblError.Text = error;
        lblError.Visible = true;
    }
Exemple #14
0
        /// <summary>
        /// Registers an activity type.
        /// </summary>
        /// <param name="client">The associated client.</param>
        /// <param name="activityType">The activity type.</param>
        /// <param name="activityTypeName">The name used to identify the implementation.</param>
        /// <param name="domain">Specifies the target domain.</param>
        /// <returns><c>true</c> if the activity was already registered.</returns>
        /// <exception cref="InvalidOperationException">Thrown if a different activity class has already been registered for <paramref name="activityTypeName"/>.</exception>
        internal async static Task RegisterAsync(CadenceClient client, Type activityType, string activityTypeName, string domain)
        {
            Covenant.Requires <ArgumentNullException>(client != null, nameof(client));
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(domain), nameof(domain));
            CadenceHelper.ValidateActivityImplementation(activityType);

            var constructor = activityType.GetConstructor(Type.EmptyTypes);

            if (constructor == null)
            {
                throw new ArgumentException($"Activity type [{activityType.FullName}] does not have a default constructor.", nameof(activityType));
            }

            // We need to register each activity method that implements an activity interface method
            // with the same signature that that was tagged by [ActivityMethod].
            //
            // First, we'll create a dictionary that maps method signatures from any inherited
            // interfaces that are tagged by [ActivityMethod] to the attribute.

            var methodSignatureToAttribute = new Dictionary <string, ActivityMethodAttribute>();

            foreach (var interfaceType in activityType.GetInterfaces())
            {
                foreach (var method in interfaceType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    var activityMethodAttribute = method.GetCustomAttribute <ActivityMethodAttribute>();

                    if (activityMethodAttribute == null)
                    {
                        continue;
                    }

                    var signature = method.ToString();

                    if (methodSignatureToAttribute.ContainsKey(signature))
                    {
                        throw new NotSupportedException($"Activity type [{activityType.FullName}] cannot implement the [{signature}] method from two different interfaces.");
                    }

                    methodSignatureToAttribute.Add(signature, activityMethodAttribute);
                }
            }

            // Next, we need to register the activity methods that implement the
            // activity interface.

            foreach (var method in activityType.GetMethods())
            {
                if (!methodSignatureToAttribute.TryGetValue(method.ToString(), out var activityMethodAttribute))
                {
                    continue;
                }

                var activityTypeKey = GetActivityTypeKey(client, activityTypeName, activityMethodAttribute);

                lock (syncLock)
                {
                    if (nameToRegistration.TryGetValue(activityTypeKey, out var registration))
                    {
                        if (!object.ReferenceEquals(registration.ActivityType, registration.ActivityType))
                        {
                            throw new InvalidOperationException($"Conflicting activity type registration: Activity type [{activityType.FullName}] is already registered for activity type name [{activityTypeKey}].");
                        }
                    }
                    else
                    {
                        nameToRegistration[activityTypeKey] =
                            new ActivityRegistration()
                        {
                            ActivityType                 = activityType,
                            ActivityConstructor          = constructor,
                            ActivityMethod               = method,
                            ActivityMethodParamaterTypes = method.GetParameterTypes()
                        };
                    }
                }

                var reply = (ActivityRegisterReply)await client.CallProxyAsync(
                    new ActivityRegisterRequest()
                {
                    Name   = GetActivityTypeNameFromKey(activityTypeKey),
                    Domain = client.ResolveDomain(domain)
                });

                // $hack(jefflill):
                //
                // We're going to ignore any errors here to handle:
                //
                //      https://github.com/nforgeio/neonKUBE/issues/668

                // reply.ThrowOnError();
            }
        }
    /// <summary>
    /// Log user activity.
    /// </summary>
    private void LogActivity()
    {
        // Create new activity for registered user
        Activity activity = new ActivityRegistration(RegisteredUser, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
        if (activity.Data != null)
        {
            int contactId = QueryHelper.GetInteger("contactid", 0);
            if (contactId <= 0)
            {
                // Get contact for registered user
                contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(RegisteredUser);
            }

            // Log contact data
            activity.Data.ContactID = contactId;
            activity.CheckViewMode = false;
            activity.Log();
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required
            if (DisplayCaptcha)
            {
                // Verify captcha text
                if (!captchaElem.IsValid())
                {
                    // Display error message if captcha text is not valid
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                    return;
                }
                else
                {
                    // Generate new code and clear captcha textbox if cpatcha code is valid
                    captchaElem.GenerateNew();
                }
            }

            string userName   = String.Empty;
            string nickName   = String.Empty;
            string firstName  = String.Empty;
            string lastName   = String.Empty;
            string emailValue = String.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            EditingFormControl txtUserName = formUser.BasicForm.FieldEditingControls["UserName"] as EditingFormControl;
            if (txtUserName != null)
            {
                userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            }

            EditingFormControl txtEmail = formUser.BasicForm.FieldEditingControls["Email"] as EditingFormControl;
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName))
            {
                userName = emailValue;
                if (String.IsNullOrEmpty(emailValue))
                {
                    formUser.StopProcessing = true;
                    lblError.Visible        = true;
                    lblError.Text           = GetString("customregistrationform.usernameandemail");
                    return;
                }
                else
                {
                    formUser.BasicForm.Data.SetValue("UserName", userName);
                }
            }

            EditingFormControl txtNickName = formUser.BasicForm.FieldEditingControls["UserNickName"] as EditingFormControl;
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            EditingFormControl txtFirstName = formUser.BasicForm.FieldEditingControls["FirstName"] as EditingFormControl;
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            EditingFormControl txtLastName = formUser.BasicForm.FieldEditingControls["LastName"] as EditingFormControl;
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            // Test if "global" or "site" user exists.
            SiteInfo si     = CMSContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
            if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, userName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, nickName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                return;
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            // Check whether email is unique if it is required
            string checkSites = (String.IsNullOrEmpty(AssignToSites)) ? CMSContext.CurrentSiteName : AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(emailValue, checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Validate and save form with new user data
            if (!formUser.Save())
            {
                // Return if saving failed
                return;
            }

            // Get user info from form
            UserInfo ui = (UserInfo)formUser.Info;

            // Add user prefix if settings is on
            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
            }

            ui.PreferredCultureCode = "";
            ui.Enabled  = EnableUserAfterRegistration;
            ui.IsEditor = false;
            ui.IsGlobalAdministrator = false;
            ui.UserURLReferrer       = CMSContext.CurrentUser.URLReferrer;
            ui.UserCampaign          = CMSContext.Campaign;

            // Fill optionally full user name
            if (String.IsNullOrEmpty(ui.FullName))
            {
                ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
            }

            // Ensure nick name
            if (ui.UserNickName.Trim() == "")
            {
                ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
            }

            ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
            ui.UserSettings.UserLogActivities    = true;
            ui.UserSettings.UserShowSplashScreen = true;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval");
            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(StartingAliasPath);
            }

            // Get user password and save it in apropriate format after form save
            string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
            UserInfoProvider.SetPassword(ui, password);


            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            ContextResolver resolver = CMSContext.CurrentResolver;
            resolver.SourceData = data;

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool              error    = false;
            EventLogProvider  ev       = new EventLogProvider();
            EmailTemplateInfo template = null;

            // Prepare macro replacements
            string[,] replacements = new string[6, 2];
            replacements[0, 0]     = "confirmaddress";
            replacements[0, 1]     = (ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(ApprovalPage) + "?userguid=" + ui.UserGUID : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx") + "?userguid=" + ui.UserGUID;
            replacements[1, 0]     = "username";
            replacements[1, 1]     = userName;
            replacements[2, 0]     = "password";
            replacements[2, 1]     = password;
            replacements[3, 0]     = "Email";
            replacements[3, 1]     = emailValue;
            replacements[4, 0]     = "FirstName";
            replacements[4, 1]     = firstName;
            replacements[5, 0]     = "LastName";
            replacements[5, 1]     = lastName;

            // Set resolver
            resolver.SourceParameters = replacements;

            // Email message
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.EmailFormat = EmailFormatEnum.Default;
            emailMessage.Recipients  = ui.Email;

            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CMSContext.CurrentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CMSContext.CurrentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CMSContext.CurrentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                }
            }

            if (template != null)
            {
                emailMessage.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                // Enable macro encoding for body
                resolver.EncodeResolvedValues = true;
                emailMessage.Body             = resolver.ResolveMacros(template.TemplateText);
                // Disable macro encoding for plaintext body and subject
                resolver.EncodeResolvedValues = false;
                emailMessage.PlainTextBody    = resolver.ResolveMacros(template.TemplatePlainText);
                emailMessage.Subject          = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                emailMessage.CcRecipients  = template.TemplateCc;
                emailMessage.BccRecipients = template.TemplateBcc;

                try
                {
                    MetaFileInfoProvider.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(CMSContext.CurrentSiteName, emailMessage, true);
                }
                catch (Exception ex)
                {
                    ev.LogEvent("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName);
                }

                if (mEmailTemplate == null)
                {
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                //email template ok
                else
                {
                    replacements       = new string[4, 2];
                    replacements[0, 0] = "firstname";
                    replacements[0, 1] = ui.FirstName;
                    replacements[1, 0] = "lastname";
                    replacements[1, 1] = ui.LastName;
                    replacements[2, 0] = "email";
                    replacements[2, 1] = ui.Email;
                    replacements[3, 0] = "username";
                    replacements[3, 1] = userName;

                    // Set resolver
                    resolver.SourceParameters = replacements;
                    // Enable macro encoding for body
                    resolver.EncodeResolvedValues = true;

                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.EncodeResolvedValues = false;
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                        EmailSender.SendEmail(CMSContext.CurrentSiteName, message);
                    }
                    catch
                    {
                        ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID);
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                string siteName = CMSContext.CurrentSiteName;

                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress))
                {
                    HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(CMSContext.CurrentSiteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }

                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Site and roles addition and authentication"

            string[] roleList = AssignRoles.Split(';');
            string[] siteList;

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }
            else // If not set user current site
            {
                siteList = new string[] { CMSContext.CurrentSiteName };
            }

            foreach (string siteName in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String sn = roleName.StartsWithCSafe(".") ? "" : siteName;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, sn))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlRegForm.Visible = false;
                lblInfo.Visible    = true;
                lblInfo.Text       = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    CMSContext.AuthenticateUser(ui.UserName, true);
                }

                string returnUrl = QueryHelper.GetString("ReturnURL", "");
                if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash")))
                {
                    URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl));
                }
                else if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            Visible = false;
        }
        else
        {
            if (QueryHelper.GetInteger("logout", 0) > 0)
            {
                // Sign out from CMS
                CMSContext.LogoutUser();

                CMSContext.CurrentUser = null;
                Response.Cache.SetNoStore();
                URLHelper.Redirect(URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, "logout"));
                return;
            }

            string currentSiteName = CMSContext.CurrentSiteName;
            if (!String.IsNullOrEmpty(currentSiteName) && SettingsKeyProvider.GetBoolValue(currentSiteName + ".CMSEnableFacebookConnect"))
            {
                // Check Facebook Connect settings
                if (!FacebookConnectHelper.FacebookIsAvailable(currentSiteName))
                {
                    // Display warning message in "Design mode"
                    if (DisplayMessage())
                    {
                        return;
                    }

                    Visible = false;
                    return;
                }

                // Try to retrieve return URL from query
                string returnUrl = QueryHelper.GetString("returnurl", null);

                // Init Facebook Connect
                if (Page is ContentPage)
                {
                    // Adding XML namespace
                    ((ContentPage)Page).XmlNamespace = FacebookConnectHelper.GetFacebookXmlNamespace();
                }

                // Init FB connect
                string initscr = FacebookConnectHelper.GetFacebookInitScriptForSite(currentSiteName) + " " + FacebookConnectHelper.GetFacebookLoginHandlerScript();
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "FBConnectLogon" + ClientID, initscr);
                // Return URL
                string currentUrl       = URLHelper.AddParameterToUrl(URLHelper.CurrentURL, "logout", "1");
                string additionalScript = "window.location.href=" + ScriptHelper.GetString(URLHelper.GetAbsoluteUrl(currentUrl)) + "; return false;";
                // Logout script for FB connect
                string logoutScript = FacebookConnectHelper.GetFacebookLogoutScriptForSignOut(URLHelper.CurrentURL, FacebookConnectHelper.GetFacebookApiKey(currentSiteName), additionalScript);

                // Validate FB access token against FB server
                string facebookUserId       = null;
                bool   facebookCookiesValid = false;
                string confirmToken         = QueryHelper.GetString(CONFIRMATION_URLPARAMETER, null);
                if (!String.IsNullOrEmpty(confirmToken))
                {
                    facebookCookiesValid = FacebookConnectHelper.ValidateFBAccessToken(confirmToken, out facebookUserId);
                }

                // If user is already authenticated
                if (CMSContext.CurrentUser.IsAuthenticated())
                {
                    // Is user logged in using Facebook Connect?
                    if ((CMSContext.CurrentUser.UserSettings != null) && String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.UserFacebookID))
                    {
                        // no, user is not logged in by Facebook Connect
                        logoutScript = additionalScript;
                    }

                    // Hide Facebook Connect button
                    plcFBButton.Visible = false;

                    // If signout should be visible and user has FacebookID registered
                    if (ShowSignOut && !String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.UserFacebookID))
                    {
                        // If only text is set use text/button link
                        if (!String.IsNullOrEmpty(SignOutText))
                        {
                            // Button link
                            if (ShowAsButton)
                            {
                                btnSignOut.OnClientClick = logoutScript;
                                btnSignOut.Text          = SignOutText;
                                btnSignOut.Visible       = true;
                            }
                            // Text link
                            else
                            {
                                lnkSignOutLink.Text    = SignOutText;
                                lnkSignOutLink.Visible = true;
                                lnkSignOutLink.Attributes.Add("onclick", logoutScript);
                                lnkSignOutLink.Attributes.Add("style", "cursor:pointer;");
                            }
                        }
                        // Image link
                        else
                        {
                            string signOutImageUrl = SignOutImageURL;
                            // Use default image if none is specified
                            if (String.IsNullOrEmpty(signOutImageUrl))
                            {
                                signOutImageUrl = GetImageUrl("Others/FacebookConnect/signout.gif");
                            }
                            imgSignOut.ImageUrl        = ResolveUrl(signOutImageUrl);
                            imgSignOut.Visible         = true;
                            imgSignOut.AlternateText   = GetString("webparts_membership_signoutbutton.signout");
                            lnkSignOutImageBtn.Visible = true;
                            lnkSignOutImageBtn.Attributes.Add("onclick", logoutScript);
                            lnkSignOutImageBtn.Attributes.Add("style", "cursor:pointer;");
                        }
                    }
                    else
                    {
                        Visible = false;
                    }
                }
                // Sign In
                else
                {
                    if (facebookCookiesValid)
                    {
                        if (!String.IsNullOrEmpty(facebookUserId))
                        {
                            UserInfo ui = UserInfoProvider.GetUserInfoByFacebookConnectID(facebookUserId);
                            // Claimed Facebook ID is in DB
                            if (ui != null)
                            {
                                // Login existing user
                                if ((ui != null) && ui.Enabled)
                                {
                                    // Ban IP addresses which are blocked for login
                                    BannedIPInfoProvider.CheckIPandRedirect(currentSiteName, BanControlEnum.Login);

                                    // Create autentification cookie
                                    AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" });
                                    UserInfoProvider.SetPreferredCultures(ui);

                                    int      contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                    Activity activity  = new ActivityUserLogin(contactId, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                                    activity.Log();

                                    // Redirect user
                                    if (String.IsNullOrEmpty(returnUrl))
                                    {
                                        returnUrl = URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, CONFIRMATION_URLPARAMETER);
                                    }

                                    URLHelper.Redirect(returnUrl);
                                }
                                // Otherwise is user disabled
                                else
                                {
                                    lblError.Text    = GetString("membership.userdisabled");
                                    lblError.Visible = true;
                                }
                            }
                            // Claimed Facebook ID not found  = save new user
                            else
                            {
                                // Check whether additional user info page is set
                                string additionalInfoPage = SettingsKeyProvider.GetStringValue(currentSiteName + ".CMSRequiredFacebookPage").Trim();

                                // No page set, user can be created
                                if (String.IsNullOrEmpty(additionalInfoPage))
                                {
                                    // Register new user
                                    string error = null;
                                    ui = AuthenticationHelper.AuthenticateFacebookConnectUser(facebookUserId, currentSiteName, false, true, ref error);

                                    // If user was found or successfuly created
                                    if (ui != null)
                                    {
                                        // If user is enabled
                                        if (ui.Enabled)
                                        {
                                            // Create authentification cookie
                                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" });

                                            int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                            Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                                            activityLogin.Log();
                                        }

                                        // Send registration e-mails
                                        // E-mail confirmation is not required as user already provided confirmation by successful login using Facebook connect
                                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                                        // Notify administrator
                                        if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                                        {
                                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                                        }

                                        // Log registration into analytics
                                        AuthenticationHelper.TrackUserRegistration(TrackConversionName, ConversionValue, currentSiteName, ui);

                                        Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                                        if (activity.Data != null)
                                        {
                                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                            activity.Log();
                                        }
                                    }
                                    // Redirect when authentication was succesfull
                                    if (String.IsNullOrEmpty(error))
                                    {
                                        if (!String.IsNullOrEmpty(returnUrl))
                                        {
                                            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                                        }
                                        else
                                        {
                                            URLHelper.Redirect(URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, CONFIRMATION_URLPARAMETER));
                                        }
                                    }
                                    // Display error otherwise
                                    else
                                    {
                                        lblError.Text    = error;
                                        lblError.Visible = true;
                                    }
                                }
                                // Additional information page is set
                                else
                                {
                                    // Store user object in session for additional info page
                                    SessionHelper.SetValue(SESSION_NAME_USERDATA, facebookUserId);

                                    // Redirect to additional info page
                                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                                    if (!String.IsNullOrEmpty(returnUrl))
                                    {
                                        // Add return URL to parameter
                                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                                    }
                                    URLHelper.Redirect(targetURL);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                // Show warning message in "Design mode"
                Visible = DisplayMessage();
            }
        }
    }
Exemple #18
0
        public void Ensure_We_Can_Fluently_Register_An_Authorizer_For_An_Activity_Registration()
        {
            var registration = new ActivityRegistration().AuthorizedBy <AllowAnonymous>();

            Assert.That(registration.AuthorizerTypes.First().Key, Is.EqualTo(typeof(AllowAnonymous)));
        }
    /// <summary>
    /// Page Load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // If StopProcessing flag is set, do nothing
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

        Guid userGuid = QueryHelper.GetGuid("userguid", Guid.Empty);

        if (userGuid != Guid.Empty)
        {
            #region "Request validity"

            UserInfo ui = UserInfoProvider.GetUserInfoByGUID(userGuid);

            // ui was not found, probably late activation try
            if (ui == null)
            {
                lblInfo.Text = UserDeletedText;
                return;
            }

            // ui has been already activated
            if (ui.UserSettings.UserWaitingForApproval || ui.UserEnabled)
            {
                lblInfo.Text = UnsuccessfulApprovalText;
                return;
            }

            #endregion


            string siteName = null;
            bool   administrationApproval = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval");
            lblInfo.Text = SuccessfulApprovalText;

            // Admin approve is not required, enable ui
            if (!administrationApproval)
            {
                lblInfo.Text = (!String.IsNullOrEmpty(SuccessfulApprovalText)) ? SuccessfulApprovalText : GetString("mem.reg.SuccessfulApprovalText");

                // Enable ui
                ui.UserSettings.UserActivationDate = DateTime.Now;
                ui.Enabled = true;

                // ui is confirmed and enabled, could be logged into statistics
                siteName = CMSContext.CurrentSiteName;
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }
            // ui must wait for admin approval
            else
            {
                lblInfo.Text = (!String.IsNullOrEmpty(WaitingForApprovalText)) ? WaitingForApprovalText : ResHelper.GetString("mem.reg.SuccessfulApprovalWaitingForAdministratorApproval");

                // If user is already waiting for approval, dont send email again, just show info label
                if (ui.UserSettings.UserWaitingForApproval)
                {
                    return;
                }

                // Mark for admin approval
                ui.UserSettings.UserWaitingForApproval = true;
            }

            // Save changes
            UserInfoProvider.SetUserInfo(ui);

            Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
            if (activity.Data != null)
            {
                int contactId = QueryHelper.GetInteger("contactid", 0);
                if (contactId <= 0)
                {
                    contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                }

                activity.Data.ContactID = contactId;
                activity.CheckViewMode  = false;
                activity.Log();
            }

            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if ((!String.IsNullOrEmpty(AdministratorEmail)) && (administrationApproval || NotifyAdministrator))
            {
                EmailTemplateInfo template = null;

                if (administrationApproval)
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName);
                }
                else
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName);
                }

                EventLogProvider ev = new EventLogProvider();

                if (template == null)
                {
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                //email template ok
                else
                {
                    string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                    if (!String.IsNullOrEmpty(from))
                    {
                        // Prepare macro replacements
                        string[,] replacements = new string[4, 2];
                        replacements[0, 0]     = "firstname";
                        replacements[0, 1]     = ui.FirstName;
                        replacements[1, 0]     = "lastname";
                        replacements[1, 1]     = ui.LastName;
                        replacements[2, 0]     = "email";
                        replacements[2, 1]     = ui.Email;
                        replacements[3, 0]     = "username";
                        replacements[3, 1]     = ui.UserName;

                        // Set resolver
                        ContextResolver resolver = CMSContext.CurrentResolver;
                        resolver.SourceParameters     = replacements;
                        resolver.EncodeResolvedValues = true;



                        // Email message
                        EmailMessage email = new EmailMessage();
                        email.EmailFormat = EmailFormatEnum.Default;
                        email.Recipients  = AdministratorEmail;

                        // Get e-mail sender and subject from template, if used
                        email.From = from;

                        email.Body = resolver.ResolveMacros(template.TemplateText);

                        resolver.EncodeResolvedValues = false;
                        email.PlainTextBody           = resolver.ResolveMacros(template.TemplatePlainText);

                        string emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.EmailSubject"));
                        email.Subject = resolver.ResolveMacros(emailSubject);

                        email.CcRecipients  = template.TemplateCc;
                        email.BccRecipients = template.TemplateBcc;

                        try
                        {
                            MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                            // Send the e-mail immediately
                            EmailSender.SendEmail(CMSContext.CurrentSiteName, email, true);
                        }
                        catch
                        {
                            ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationApprovalEmail", CMSContext.CurrentSite.SiteID);
                        }
                    }
                    else
                    {
                        EventLogProvider eventLog = new EventLogProvider();
                        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "RegistrationApproval", "EmailSenderNotSpecified");
                    }
                }
            }

            #endregion
        }
        else
        {
            Visible = false;
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = SiteContext.CurrentSiteName;

            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text = GetString("banip.ipisbannedregistration");
                return;
            }

            #endregion

            #region "Check Email & password"

            string[] siteList = { siteName };

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }

            // Check whether user with same email does not exist
            UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch");
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength.ToString());
                return;
            }

            if (!passStrength.IsValid())
            {
                lblError.Visible = true;
                lblError.Text = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                return;
            }

            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            #endregion

            #region "Captcha"

            // Check if captcha is required and verifiy captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            #endregion

            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email = txtEmail.Text.Trim();
            ui.FirstName = txtFirstName.Text.Trim();
            ui.LastName = txtLastName.Text.Trim();
            ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName);
            ui.MiddleName = "";
            ui.UserMFRequired = chkUseMultiFactorAutentization.Checked;

            // User name as put by user (no site prefix included)
            String plainUserName = txtEmail.Text.Trim();
            ui.UserName = plainUserName;

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si);
            }

            ui.Enabled = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign = AnalyticsHelper.Campaign;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if ((requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")))
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            #endregion

            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName));
                return;
            }

            #endregion

            #region "License limitations"

            string errorMessage = String.Empty;
            UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                lblError.Visible = true;
                lblError.Text = errorMessage;
                return;
            }

            #endregion

            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);

            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(data);
            resolver.Settings.EncodeResolvedValues = true;

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required)
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, 0, contactId);
                }

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0] = "confirmaddress";
                replacements[0, 1] = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator);
                replacements[1, 0] = "username";
                replacements[1, 1] = plainUserName;
                replacements[2, 0] = "password";
                replacements[2, 1] = passStrength.Text;
                replacements[3, 0] = "Email";
                replacements[3, 1] = txtEmail.Text;
                replacements[4, 0] = "FirstName";
                replacements[4, 1] = txtFirstName.Text;
                replacements[5, 0] = "LastName";
                replacements[5, 1] = txtLastName.Text;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients = ui.Email;

                email.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress"));
                email.Body = resolver.ResolveMacros(template.TemplateText);

                resolver.Settings.EncodeResolvedValues = false;
                email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);
                email.Subject = resolver.ResolveMacros(emailSubject);

                email.CcRecipients = template.TemplateCc;
                email.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(siteName, email, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion

            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    string[,] replacements = new string[4, 2];
                    replacements[0, 0] = "firstname";
                    replacements[0, 1] = ui.FirstName;
                    replacements[1, 0] = "lastname";
                    replacements[1, 1] = ui.LastName;
                    replacements[2, 0] = "email";
                    replacements[2, 1] = ui.Email;
                    replacements[3, 0] = "username";
                    replacements[3, 1] = plainUserName;

                    // Set resolver
                    resolver.SetNamedSourceData(replacements);

                    EmailMessage message = new EmailMessage();

                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients = ToAddress;
                    message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText);

                    resolver.Settings.EncodeResolvedValues = false;
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);
                    message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));

                    message.CcRecipients = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion

            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion

            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {

                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion

            #region "Roles & authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWithCSafe(".") ? "" : sn;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))
                    {
                        URLHelper.Redirect(url);
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
                    }
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = SiteContext.CurrentSiteName;


            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            #endregion


            #region "Check Email & password"

            string[] siteList = { siteName };

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }

            // Check whether user with same email does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch");
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text    = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength.ToString());
                return;
            }

            if (!passStrength.IsValid())
            {
                lblError.Visible = true;
                lblError.Text    = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                return;
            }

            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verifiy captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            #endregion


            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = txtEmail.Text.Trim();
            ui.FirstName      = txtFirstName.Text.Trim();
            ui.LastName       = txtLastName.Text.Trim();
            ui.FullName       = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName);
            ui.MiddleName     = "";
            ui.UserMFRequired = chkUseMultiFactorAutentization.Checked;

            // User name as put by user (no site prefix included)
            String plainUserName = txtEmail.Text.Trim();
            ui.UserName = plainUserName;

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign    = Service <ICampaignService> .Entry().CampaignCode;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if ((requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")))
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            #endregion


            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName));
                return;
            }

            #endregion


            #region "License limitations"

            string errorMessage = String.Empty;
            UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                lblError.Visible = true;
                lblError.Text    = errorMessage;
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template     = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required)
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, 0, contactId);
                }

                var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, passStrength.Text, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator));

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;

                email.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress"));

                // Enable macro encoding for body
                resolver.Settings.EncodeResolvedValues = true;
                email.Body = resolver.ResolveMacros(template.TemplateText);

                // Disable macro encoding for plaintext body and subject
                email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);
                email.Subject       = resolver.ResolveMacros(emailSubject);

                email.CcRecipients  = template.TemplateCc;
                email.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(siteName, email, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;
                MacroResolver     resolver       = MembershipResolvers.GetRegistrationResolver(ui);
                if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"))
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    EmailMessage message = new EmailMessage();

                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;

                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;
                    message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText);

                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Roles & authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWithCSafe(".") ? "" : sn;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash", "aliaspath"))
                    {
                        URLHelper.Redirect(url);
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(UIHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext"));
                    }
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error    = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);

        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = RequestContext.CurrentURL;

        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "oauth_token");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "oauth_verifier");

        // Get LinkedIn response status
        switch (linkedInHelper.CheckStatus(RequireFirstName, RequireLastName, RequireBirthDate, null))
        {
        // User is authenticated
        case CMSOpenIDHelper.RESPONSE_AUTHENTICATED:
            // LinkedIn profile Id not found  = save new user
            if (UserInfoProvider.GetUserInfoByLinkedInID(linkedInHelper.MemberId) == null)
            {
                string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredLinkedInPage").Trim();

                // No page set, user can be created
                if (String.IsNullOrEmpty(additionalInfoPage))
                {
                    // Register new user
                    UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, true, true, ref error);

                    // If user was successfully created
                    if (ui != null)
                    {
                        if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // If user is enabled
                        if (ui.Enabled)
                        {
                            // Create authentication cookie
                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" });

                            Activity activityLogin = new ActivityUserLogin(ModuleCommands.OnlineMarketingGetUserLoginContactID(ui), ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                            activityLogin.Log();
                        }

                        // Notify administrator
                        if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using OpenID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }
                    }

                    // Redirect when authentication was successful
                    if (String.IsNullOrEmpty(error))
                    {
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error otherwise
                    else
                    {
                        lblError.Text    = error;
                        lblError.Visible = true;
                    }
                }
                // Additional information page is set
                else
                {
                    // Store user object in session for additional use
                    string response = (linkedInHelper.LinkedInResponse != null) ? linkedInHelper.LinkedInResponse.OuterXml : null;
                    SessionHelper.SetValue(SESSION_NAME_USERDATA, response);

                    // Redirect to additional info page
                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        // Add return URL to parameter
                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                    }
                    URLHelper.Redirect(targetURL);
                }
            }
            // LinkedIn profile id is in DB
            else
            {
                // Login existing user
                UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, false, true, ref error);

                if ((ui != null) && (ui.Enabled))
                {
                    // Create authentication cookie
                    AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" });

                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();

                    // Redirect user
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                    }
                    else
                    {
                        URLHelper.Redirect(currentUrl);
                    }
                }
                // Display error which occurred during authentication process
                else if (!String.IsNullOrEmpty(error))
                {
                    lblError.Text    = error;
                    lblError.Visible = true;
                }
                // Otherwise is user disabled
                else
                {
                    lblError.Text    = GetString("membership.userdisabled");
                    lblError.Visible = true;
                }
            }
            break;

        // No authentication, do nothing
        case LinkedInHelper.RESPONSE_NOTAUTHENTICATED:
            break;
        }
    }
Exemple #23
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with openID token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (response != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.openid.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.openid.fillvalidemail")).Result;
            string siteName = CMSContext.CurrentSiteName;
            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (errorMessage == String.Empty))
            {
                if (password == String.Empty)
                {
                    errorMessage = GetString("mem.liveid.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if (string.IsNullOrEmpty(errorMessage) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if (string.IsNullOrEmpty(errorMessage) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (string.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    string error = DisplayMessage;
                    // Register new user
                    ui             = AuthenticationHelper.AuthenticateOpenIDUser((string)response["ClaimedIdentifier"], ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, true, false, ref error);
                    DisplayMessage = error;

                    // If user successfully created
                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = ui.FullName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        // Load values submitted by OpenID provider
                        // Load date of birth
                        DateTime birthdate = (DateTime)response["BirthDate"];
                        if (birthdate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = birthdate;
                        }
                        // Load default country
                        var culture = (System.Globalization.CultureInfo)response["Culture"];
                        if (culture != null)
                        {
                            ui.PreferredCultureCode = culture.Name;
                        }
                        // Nick name
                        string nick = (string)response["Nickname"];
                        if (!String.IsNullOrEmpty(nick))
                        {
                            ui.UserSettings.UserNickName = nick;
                        }
                        // Full name
                        string full = (string)response["FullName"];
                        if (!String.IsNullOrEmpty(full))
                        {
                            ui.FullName = full;
                        }
                        // User gender
                        var gender = (int?)response["UserGender"];
                        if (gender != null)
                        {
                            ui.UserSettings.UserGender = (int)gender;
                        }
                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        // Set user
                        UserInfoProvider.SetUserInfo(ui);

                        // Clear used session
                        SessionHelper.Remove(SESSION_NAME_URL);
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, password, true, SendWelcomeEmail);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Log registration into analytics
                        AuthenticationHelper.TrackUserRegistration(TrackConversionName, ConversionValue, siteName, ui);

                        Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
    /// <summary>
    /// Page Load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // If StopProcessing flag is set, do nothing
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

        Guid userGuid = QueryHelper.GetGuid("userguid", Guid.Empty);

        if (userGuid != Guid.Empty)
        {
            #region "Request validity"

            UserInfo ui = UserInfoProvider.GetUserInfoByGUID(userGuid);

            // ui was not found, probably late activation try
            if (ui == null)
            {
                lblInfo.Text = UserDeletedText;
                return;
            }

            // ui has been already activated
            if (ui.UserSettings.UserWaitingForApproval || ui.UserEnabled)
            {
                lblInfo.Text = UnsuccessfulApprovalText;
                return;
            }

            #endregion

            string siteName = null;
            bool administrationApproval = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval");
            lblInfo.Text = SuccessfulApprovalText;

            // Admin approve is not required, enable ui
            if (!administrationApproval)
            {
                lblInfo.Text = (!String.IsNullOrEmpty(SuccessfulApprovalText)) ? SuccessfulApprovalText : GetString("mem.reg.SuccessfulApprovalText");

                // Enable ui
                ui.UserSettings.UserActivationDate = DateTime.Now;
                ui.Enabled = true;

                // ui is confirmed and enabled, could be logged into statistics
                siteName = CMSContext.CurrentSiteName;
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }
            // ui must wait for admin approval
            else
            {
                lblInfo.Text = (!String.IsNullOrEmpty(WaitingForApprovalText)) ? WaitingForApprovalText : ResHelper.GetString("mem.reg.SuccessfulApprovalWaitingForAdministratorApproval");

                // If user is already waiting for approval, dont send email again, just show info label
                if (ui.UserSettings.UserWaitingForApproval)
                {
                    return;
                }

                // Mark for admin approval
                ui.UserSettings.UserWaitingForApproval = true;
            }

            // Save changes
            UserInfoProvider.SetUserInfo(ui);

            Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
            if (activity.Data != null)
            {
                int contactId = QueryHelper.GetInteger("contactid", 0);
                if (contactId <= 0)
                {
                    contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                }

                activity.Data.ContactID = contactId;
                activity.CheckViewMode = false;
                activity.Log();
            }

            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if ((!String.IsNullOrEmpty(AdministratorEmail)) && (administrationApproval || NotifyAdministrator))
            {
                EmailTemplateInfo template = null;

                if (administrationApproval)
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName);
                }
                else
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName);
                }

                EventLogProvider ev = new EventLogProvider();

                if (template == null)
                {
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                //email template ok
                else
                {
                    string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                    if (!String.IsNullOrEmpty(from))
                    {

                        // Prepare macro replacements
                        string[,] replacements = new string[4, 2];
                        replacements[0, 0] = "firstname";
                        replacements[0, 1] = ui.FirstName;
                        replacements[1, 0] = "lastname";
                        replacements[1, 1] = ui.LastName;
                        replacements[2, 0] = "email";
                        replacements[2, 1] = ui.Email;
                        replacements[3, 0] = "username";
                        replacements[3, 1] = ui.UserName;

                        // Set resolver
                        ContextResolver resolver = CMSContext.CurrentResolver;
                        resolver.SourceParameters = replacements;
                        resolver.EncodeResolvedValues = true;

                        // Email message
                        EmailMessage email = new EmailMessage();
                        email.EmailFormat = EmailFormatEnum.Default;
                        email.Recipients = AdministratorEmail;

                        // Get e-mail sender and subject from template, if used
                        email.From = from;

                        email.Body = resolver.ResolveMacros(template.TemplateText);

                        resolver.EncodeResolvedValues = false;
                        email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                        string emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.EmailSubject"));
                        email.Subject = resolver.ResolveMacros(emailSubject);

                        email.CcRecipients = template.TemplateCc;
                        email.BccRecipients = template.TemplateBcc;

                        try
                        {
                            MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                            // Send the e-mail immediately
                            EmailSender.SendEmail(CMSContext.CurrentSiteName, email, true);
                        }
                        catch
                        {
                            ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationApprovalEmail", CMSContext.CurrentSite.SiteID);
                        }
                    }
                    else
                    {
                        EventLogProvider eventLog = new EventLogProvider();
                        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "RegistrationApproval", "EmailSenderNotSpecified");
                    }
                }
            }

            #endregion
        }
        else
        {
            Visible = false;
        }
    }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(linkedInHelper.MemberId))
        {
            string currentSiteName = CMSContext.CurrentSiteName;

            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.linkedin.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.linkedin.fillvalidemail")).Result;

            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (String.IsNullOrEmpty(errorMessage)))
            {
                if (String.IsNullOrEmpty(password))
                {
                    errorMessage = GetString("mem.linkedin.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if ((String.IsNullOrEmpty(errorMessage)) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), currentSiteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if ((String.IsNullOrEmpty(errorMessage)) && UserInfoProvider.NameIsReserved(currentSiteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (String.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = DisplayMessage;
                    ui             = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, currentSiteName, true, false, ref error);
                    DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                        }

                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Send registration e-mails
                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, password, true, SendWelcomeEmail);

                        // Log registration into analytics
                        AuthenticationHelper.TrackUserRegistration(TrackConversionName, ConversionValue, currentSiteName, ui);

                        Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
Exemple #27
0
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);
        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = RequestContext.CurrentURL;
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "token");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.ns");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.mode");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.return_to");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.claimed_id");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.identity");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.assoc_handle");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.realm");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.response_nonce");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.signed");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.op_endpoint");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.pape.auth_level.nist");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.sig");

        // Get OpenID response status
        switch (openIDhelper.CheckStatus())
        {
            // User is authenticated
            case CMSOpenIDHelper.RESPONSE_AUTHENTICATED:
                // Claimed ID not found  = save new user
                if (OpenIDUserInfoProvider.GetUserInfoByOpenID(openIDhelper.ClaimedIdentifier) == null)
                {
                    // Check whether additional user info page is set
                    string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredOpenIDPage").Trim();

                    // No page set, user can be created
                    if (String.IsNullOrEmpty(additionalInfoPage))
                    {
                        // Register new user
                        UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

                        // If user was found or successfuly created
                        if (ui != null)
                        {
                            // Load values submited by OpenID provider
                            // Load date of birth
                            if (openIDhelper.BirthDate != DateTime.MinValue)
                            {
                                ui.UserSettings.UserDateOfBirth = openIDhelper.BirthDate;
                            }
                            // Load default country
                            if (openIDhelper.Culture != null)
                            {
                                ui.PreferredCultureCode = openIDhelper.Culture.Name;
                            }
                            // Load e-mail
                            if (!String.IsNullOrEmpty(openIDhelper.Email))
                            {
                                ui.Email = openIDhelper.Email;
                            }
                            // Nick name
                            if (!String.IsNullOrEmpty(openIDhelper.Nickname))
                            {
                                ui.UserSettings.UserNickName = openIDhelper.Nickname;
                            }
                            // User gender
                            if (openIDhelper.UserGender != null)
                            {
                                ui.UserSettings.UserGender = (int)openIDhelper.UserGender;
                            }

                            UserInfoProvider.SetUserInfo(ui);

                            // If user is enabled
                            if (ui.Enabled)
                            {
                                // Create autentification cookie
                                AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openidlogin" });
                                // Log activity
                                Activity activityLogin = new ActivityUserLogin(ModuleCommands.OnlineMarketingGetUserLoginContactID(ui), ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                                activityLogin.Log();
                            }

                            // Send registration e-mails
                            // E-mail confirmation is not required as user already provided confirmation by successful login using OpenID
                            AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                            // Notify administrator
                            if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                            {
                                AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                            }

                            // Log user registration into the web analytics and track conversion if set
                            AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                            Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                            if (activity.Data != null)
                            {
                                activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                activity.Log();
                            }
                        }

                        // Redirect when authentication was succesfull
                        if (String.IsNullOrEmpty(error))
                        {
                            if (!String.IsNullOrEmpty(returnUrl))
                            {
                                URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                            }
                            else
                            {
                                URLHelper.Redirect(currentUrl);
                            }
                        }
                        // Display error otherwise
                        else
                        {
                            lblError.Text = error;
                            lblError.Visible = true;
                        }
                    }
                    // Additional information page is set
                    else
                    {
                        // Store user object in session for additional use
                        StoreResponseInSession();

                        // Redirect to additional info page
                        string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            // Add return URL to parameter
                            targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                        }
                        URLHelper.Redirect(targetURL);
                    }
                }
                // Claimed OpenID is in DB
                else
                {
                    // Login existing user
                    UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

                    if ((ui != null) && (ui.Enabled))
                    {
                        // Create autentification cookie
                        AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openilogin" });

                        // Log activity
                        int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        activityLogin.Log();

                        // Redirect user
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error which occured during authentication process
                    else if (!String.IsNullOrEmpty(error))
                    {
                        lblError.Text = error;
                        lblError.Visible = true;
                    }
                    // Otherwise is user disabled
                    else
                    {
                        lblError.Text = GetString("membership.userdisabled");
                        lblError.Visible = true;
                    }
                }
                break;

            // Authentication was canceled
            case CMSOpenIDHelper.RESPONSE_CANCELED:
                lblError.Text = GetString("openid.logincanceled");
                lblError.Visible = true;
                break;

            // Authentication failed
            case CMSOpenIDHelper.RESPONSE_FAILED:
                lblError.Text = GetString("openid.loginfailed");
                lblError.Visible = true;
                break;
        }
    }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = SiteContext.CurrentSiteName;

            // Existing account
            if (radSignIn.Checked)
            {
                // Authenticate user
                UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, SiteContext.CurrentSiteName, false);
                if (ui == null)
                {
                    lblError.Text    = GetString("ShoppingCartCheckRegistration.LoginFailed");
                    lblError.Visible = true;
                    return(false);
                }

                // Sign in customer with existing account
                AuthenticationHelper.AuthenticateUser(ui.UserName, false);

                // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
                ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

                // Assign current user to the current shopping cart
                ShoppingCart.User = ui;

                // Save changes to database
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                // Log "login" activity
                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();

                LoadStep(true);

                // Return false to get to Edit customer page
                return(false);
            }
            // New registration
            else if (radNewReg.Checked)
            {
                txtEmail2.Text             = txtEmail2.Text.Trim();
                pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

                string[] siteList = { siteName };

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }

                // Check if user exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
                if (ui != null)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                    return(false);
                }

                // Check all sites where user will be assigned
                if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return(false);
                }

                // Create new customer and user account and sign in
                // User
                ui           = new UserInfo();
                ui.UserName  = txtEmail2.Text.Trim();
                ui.Email     = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName  = txtLastName1.Text.Trim();
                ui.FullName  = ui.FirstName + " " + ui.LastName;
                ui.Enabled   = true;
                ui.UserIsGlobalAdministrator = false;
                ui.UserURLReferrer           = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign = AnalyticsHelper.Campaign;
                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

                try
                {
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    foreach (string site in siteList)
                    {
                        UserInfoProvider.AddUserToSite(ui.UserName, site);

                        // Add user to roles
                        if (ShoppingCartControl.AssignToRoles != "")
                        {
                            AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                        }
                    }

                    // Log registered user
                    AnalyticsHelper.LogRegisteredUser(siteName, ui);

                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text    = ex.Message;
                    return(false);
                }

                // Customer
                CustomerInfo ci = new CustomerInfo();
                ci.CustomerFirstName = txtFirstName1.Text.Trim();
                ci.CustomerLastName  = txtLastName1.Text.Trim();
                ci.CustomerEmail     = txtEmail2.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";
                if (chkCorporateBody.Checked)
                {
                    ci.CustomerCompany = txtCompany1.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                    }
                }

                ci.CustomerUserID  = ui.UserID;
                ci.CustomerSiteID  = 0;
                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Track successful registration conversion
                string name = ShoppingCartControl.RegistrationTrackConversionName;
                ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

                // Log "customer registration" activity and update profile
                var activityCustomerRegistration = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                if (activityCustomerRegistration.Data != null)
                {
                    if (ContactID <= 0)
                    {
                        activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    }
                    activityCustomerRegistration.Log();
                }

                // Sign in
                if (ui.UserEnabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, false);
                    ShoppingCart.User = ui;

                    ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activity.Log();
                }

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

                // Send new registration notification email
                if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
                {
                    SendRegistrationNotification(ui);
                }
            }
            // Anonymous customer
            else if (radAnonymous.Checked)
            {
                CustomerInfo ci = null;
                if (ShoppingCart.ShoppingCartCustomerID > 0)
                {
                    // Update existing customer account
                    ci = CustomerInfoProvider.GetCustomerInfo(ShoppingCart.ShoppingCartCustomerID);
                }
                if (ci == null)
                {
                    // Create new customer account
                    ci = new CustomerInfo();
                }

                ci.CustomerFirstName = txtFirstName2.Text.Trim();
                ci.CustomerLastName  = txtLastName2.Text.Trim();
                ci.CustomerEmail     = txtEmail3.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";

                if (chkCorporateBody2.Checked)
                {
                    ci.CustomerCompany = txtCompany2.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID2.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID2.Text.Trim();
                    }
                }

                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                ci.CustomerSiteID  = SiteContext.CurrentSiteID;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Log "customer registration" activity
                var activity = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID();
                    activity.Data.ContactID = ContactID;
                    activity.Log();
                }

                // Assign customer to shoppingcart
                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
            }
            else
            {
                return(false);
            }
        }
        else
        {
            // Save the customer data
            bool         newCustomer = false;
            CustomerInfo ci          = CustomerInfoProvider.GetCustomerInfoByUserID(ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID  = ShoppingCartControl.UserInfo.UserID;
                ci.CustomerSiteID  = 0;
                ci.CustomerEnabled = true;
                newCustomer        = true;
            }

            // Old email address
            string oldEmail = ci.CustomerEmail.ToLowerCSafe();

            ci.CustomerFirstName = txtEditFirst.Text.Trim();
            ci.CustomerLastName  = txtEditLast.Text.Trim();
            ci.CustomerEmail     = txtEditEmail.Text.Trim();

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkEditCorpBody.Checked)
            {
                ci.CustomerCompany = txtEditCompany.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtEditOrgID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtEditTaxRegID.Text.Trim();
                }
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Update corresponding user email when required
            if (oldEmail != ci.CustomerEmail.ToLowerCSafe())
            {
                UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID);
                if (user != null)
                {
                    user.Email = ci.CustomerEmail;
                    UserInfoProvider.SetUserInfo(user);
                }
            }

            // Log "customer registration" activity and update contact profile
            if (newCustomer)
            {
                var activity = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            // Set the shopping cart customer ID
            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }

        try
        {
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            ShoppingCart.InvalidateCalculations();
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Exemple #29
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;

        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName       = String.Empty;
            string nickName       = String.Empty;
            string firstName      = String.Empty;
            string lastName       = String.Empty;
            string emailValue     = String.Empty;
            string pwd            = string.Empty;
            string confPassword   = string.Empty;
            string educationLevel = String.Empty;
            string interestArea   = String.Empty;
            string industry       = String.Empty;
            string referralSource = string.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            //FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];
            //if (txtUserName != null)
            //{
            //    userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            //}

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
                userName   = emailValue;
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName) && String.IsNullOrEmpty(emailValue))
            {
                formUser.StopProcessing = true;
                lblError.Visible        = true;
                lblError.Text           = GetString("customregistrationform.usernameandemail");
                return;
            }
            else
            {
                formUser.Data.SetValue("UserName", userName);
            }

            //check if email is valid
            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            FormEngineUserControl txtPwd = formUser.FieldControls["UserPassword"];
            if (txtPwd != null)
            {
                pwd = ValidationHelper.GetString(txtPwd.Value, String.Empty);
            }

            FormEngineUserControl txtConfPassword = formUser.FieldControls["ReenterPassword"];
            if (txtConfPassword != null)
            {
                confPassword = ValidationHelper.GetString(txtConfPassword.Value, String.Empty);
            }

            if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(confPassword))
            {
                lblError.Visible = true;
                lblError.Text    = "please enter password with confirmation";
                return;
            }

            if (pwd != confPassword)
            {
                lblError.Visible = true;
                lblError.Text    = "Password doesn't match";
                return;
            }


            if (validateFields(formUser.FieldControls["UserPassword"].Value.ToString()))
            {
                // Test if "global" or "site" user exists.
                SiteInfo si     = SiteContext.CurrentSite;
                UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
                if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                    return;
                }

                // Check for reserved user names like administrator, sysadmin, ...
                if (UserInfoProvider.NameIsReserved(currentSiteName, userName))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                    return;
                }

                if (UserInfoProvider.NameIsReserved(currentSiteName, nickName))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                    return;
                }

                // Check limitations for site members
                if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                    return;
                }

                // Check whether email is unique if it is required
                if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return;
                }

                // Validate and save form with new user data
                if (!formUser.Save())
                {
                    // Return if saving failed
                    return;
                }

                // Get user info from form
                UserInfo ui = (UserInfo)formUser.Info;

                // Add user prefix if settings is on
                // Ensure site prefixes
                if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName))
                {
                    ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
                }

                ui.Enabled         = EnableUserAfterRegistration;
                ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign    = AnalyticsHelper.Campaign;

                ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

                // Fill optionally full user name
                if (String.IsNullOrEmpty(ui.FullName))
                {
                    ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
                }

                // Ensure nick name
                if (ui.UserNickName.Trim() == String.Empty)
                {
                    ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
                }

                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
                ui.UserSettings.UserLogActivities        = true;
                ui.UserSettings.UserShowIntroductionTile = true;

                // Check whether confirmation is required
                bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
                bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval");
                if (!requiresConfirmation)
                {
                    // If confirmation is not required check whether administration approval is reqiures
                    if (requiresAdminApprove)
                    {
                        ui.Enabled = false;
                        ui.UserSettings.UserWaitingForApproval = true;
                    }
                }
                else
                {
                    // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                    ui.Enabled = false;
                }

                // Set user's starting alias path
                if (!String.IsNullOrEmpty(StartingAliasPath))
                {
                    ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
                }

                // Get user password and save it in apropriate format after form save
                string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
                UserInfoProvider.SetPassword(ui, password);

                var customerToken = PersonifyRegistered(emailValue, password, firstName, lastName);
                if (string.IsNullOrEmpty(customerToken))
                {
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }
                else
                {
                    var    roles      = GetImsroles(customerToken);
                    string groupslist = "";
                    if (roles.Length > 0)
                    {
                        foreach (string s in roles)
                        {
                            if (s.Length > 0)
                            {
                                groupslist += s + ",";
                            }
                        }
                    }

                    //we need this mispelling.
                    groupslist += "peronifyUser" + ",";

                    new LoginUsertokentico().AddUserToRole(ui, groupslist, true, false);
                }


                // Prepare macro data source for email resolver
                UserInfo userForMail = ui.Clone();
                userForMail.SetValue("UserPassword", string.Empty);

                object[] data = new object[1];
                data[0] = userForMail;

                // Prepare resolver for notification and welcome emails
                MacroResolver resolver = MacroContext.CurrentResolver;
                resolver.SetAnonymousSourceData(data);

                #region "Welcome Emails (confirmation, waiting for approval)"

                bool error = false;
                EmailTemplateInfo template = null;

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = userName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = password;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = emailValue;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = firstName;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = lastName;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

                // Email message
                EmailMessage emailMessage = new EmailMessage();
                emailMessage.EmailFormat = EmailFormatEnum.Default;
                emailMessage.Recipients  = ui.Email;

                // Send welcome message with username and password, with confirmation link, user must confirm registration
                if (requiresConfirmation)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
                }
                // Send welcome message with username and password, with information that user must be approved by administrator
                else if (SendWelcomeEmail)
                {
                    if (requiresAdminApprove)
                    {
                        template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName);
                        emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                    }
                    // Send welcome message with username and password, user can logon directly
                    else
                    {
                        template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName);
                        emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                    }
                }

                if (template != null)
                {
                    emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress"));
                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;
                    emailMessage.Body = resolver.ResolveMacros(template.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    emailMessage.PlainTextBody             = resolver.ResolveMacros(template.TemplatePlainText);
                    emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                    emailMessage.CcRecipients  = template.TemplateCc;
                    emailMessage.BccRecipients = template.TemplateBcc;

                    try
                    {
                        EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        // Send the e-mail immediately
                        EmailSender.SendEmail(currentSiteName, emailMessage, true);
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                        error = true;
                    }
                }

                // If there was some error, user must be deleted
                if (error)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                    // Email was not send, user can't be approved - delete it
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }

                #endregion


                #region "Administrator notification email"

                // Notify administrator if enabled and email confirmation is not required
                if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                {
                    EmailTemplateInfo mEmailTemplate = null;

                    if (requiresAdminApprove)
                    {
                        mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName);
                    }
                    else
                    {
                        mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName);
                    }

                    if (mEmailTemplate == null)
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                    }
                    else
                    {
                        // E-mail template ok
                        replacements       = new string[4, 2];
                        replacements[0, 0] = "firstname";
                        replacements[0, 1] = ui.FirstName;
                        replacements[1, 0] = "lastname";
                        replacements[1, 1] = ui.LastName;
                        replacements[2, 0] = "email";
                        replacements[2, 1] = ui.Email;
                        replacements[3, 0] = "username";
                        replacements[3, 1] = userName;

                        // Set resolver
                        resolver.SetNamedSourceData(replacements);
                        // Enable macro encoding for body
                        resolver.Settings.EncodeResolvedValues = true;

                        EmailMessage message = new EmailMessage();
                        message.EmailFormat = EmailFormatEnum.Default;
                        message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                        message.Recipients  = ToAddress;
                        message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                        // Disable macro encoding for plaintext body and subject
                        resolver.Settings.EncodeResolvedValues = false;
                        message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                        message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                        message.CcRecipients  = mEmailTemplate.TemplateCc;
                        message.BccRecipients = mEmailTemplate.TemplateBcc;

                        try
                        {
                            // Attach template meta-files to e-mail
                            EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                            EmailSender.SendEmail(currentSiteName, message);
                        }
                        catch
                        {
                            EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                        }
                    }
                }

                #endregion


                #region "Web analytics"

                // Track successful registration conversion
                if (TrackConversionName != String.Empty)
                {
                    if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                    {
                        HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                    }
                }

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    AnalyticsHelper.LogRegisteredUser(currentSiteName, ui);
                }

                #endregion


                #region "On-line marketing - activity"

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }

                    // Log login activity
                    if (ui.Enabled)
                    {
                        // Log activity
                        int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        activityLogin.Log();
                    }
                }

                #endregion

                #region "Site and roles addition and authentication"

                string[] roleList = AssignRoles.Split(';');

                foreach (string siteName in siteList)
                {
                    // Add new user to the current site
                    UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                    foreach (string roleName in roleList)
                    {
                        if (!String.IsNullOrEmpty(roleName))
                        {
                            String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName;

                            // Add user to desired roles
                            if (RoleInfoProvider.RoleExists(roleName, sn))
                            {
                                UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                            }
                        }
                    }
                }
                if (ui.Enabled)
                {
                    if (this.AutoLoginAfterRegistration)
                    {
                        Session["UserName"]   = userName;
                        Session["Password"]   = password;
                        Session["RememberMe"] = true;
                        Session["RetryCount"] = null;

                        if (this.Request.QueryString["ReturnURL"] != null)
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        else if (!String.IsNullOrEmpty(this.RedirectToURL))
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        Response.Redirect("~/sso/ssohandler.aspx", true);
                    }
                    else if (!String.IsNullOrEmpty(this.LoginURL))
                    {
                        Response.Redirect(string.Format(this.LoginURL, userName), true);
                    }
                    else if (!String.IsNullOrEmpty(this.RedirectToURL))
                    {
                        Response.Redirect(this.RedirectToURL, true);
                    }
                }
                #endregion

                lblError.Visible = false;
            }
        }
    }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with openID token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (response != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.openid.fillcorrectusername"))
                .IsEmail(txtEmail.Text, GetString("mem.openid.fillvalidemail")).Result;
            string siteName = SiteContext.CurrentSiteName;
            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (errorMessage == String.Empty))
            {
                if (password == String.Empty)
                {
                    errorMessage = GetString("mem.liveid.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if (string.IsNullOrEmpty(errorMessage) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if (string.IsNullOrEmpty(errorMessage) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (string.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    string error = DisplayMessage;
                    // Register new user
                    ui = AuthenticationHelper.AuthenticateOpenIDUser((string)response["ClaimedIdentifier"], ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, true, false, ref error);
                    DisplayMessage = error;

                    // If user successfully created
                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = ui.FullName = txtUserNameNew.Text.Trim();
                        ui.Email = txtEmail.Text;

                        // Load values submitted by OpenID provider
                        // Load date of birth
                        DateTime birthdate = (DateTime)response["BirthDate"];
                        if (birthdate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = birthdate;
                        }
                        // Load default country
                        var culture = (System.Globalization.CultureInfo)response["Culture"];
                        if (culture != null)
                        {
                            ui.PreferredCultureCode = culture.Name;
                        }
                        // Nick name
                        string nick = (string)response["Nickname"];
                        if (!String.IsNullOrEmpty(nick))
                        {
                            ui.UserSettings.UserNickName = nick;
                        }
                        // Full name
                        string full = (string)response["FullName"];
                        if (!String.IsNullOrEmpty(full))
                        {
                            ui.FullName = full;
                        }
                        // User gender
                        var gender = (int?)response["UserGender"];
                        if (gender != null)
                        {
                            ui.UserSettings.UserGender = (int)gender;
                        }
                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        // Set user
                        UserInfoProvider.SetUserInfo(ui);

                        // Clear used session
                        SessionHelper.Remove(SESSION_NAME_URL);
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, password, true, SendWelcomeEmail);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text = errorMessage;
                plcError.Visible = true;
            }
        }
    }
Exemple #31
0
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);
        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = RequestContext.CurrentURL;
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "oauth_token");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "oauth_verifier");

        // Get LinkedIn response status
        switch (linkedInHelper.CheckStatus(RequireFirstName, RequireLastName, RequireBirthDate, null))
        {
            // User is authenticated
            case CMSOpenIDHelper.RESPONSE_AUTHENTICATED:
                // LinkedIn profile Id not found  = save new user
                if (UserInfoProvider.GetUserInfoByLinkedInID(linkedInHelper.MemberId) == null)
                {
                    string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredLinkedInPage").Trim();

                    // No page set, user can be created
                    if (String.IsNullOrEmpty(additionalInfoPage))
                    {
                        // Register new user
                        UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, true, true, ref error);

                        // If user was successfully created
                        if (ui != null)
                        {
                            if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                            {
                                ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                            }

                            UserInfoProvider.SetUserInfo(ui);

                            // If user is enabled
                            if (ui.Enabled)
                            {
                                // Create authentication cookie
                                AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" });

                                Activity activityLogin = new ActivityUserLogin(ModuleCommands.OnlineMarketingGetUserLoginContactID(ui), ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                                activityLogin.Log();
                            }

                            // Notify administrator
                            if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                            {
                                AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                            }

                            // Send registration e-mails
                            // E-mail confirmation is not required as user already provided confirmation by successful login using OpenID
                            AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                            // Log user registration into the web analytics and track conversion if set
                            AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                            Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                            if (activity.Data != null)
                            {
                                activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                activity.Log();
                            }
                        }

                        // Redirect when authentication was successful
                        if (String.IsNullOrEmpty(error))
                        {
                            if (!String.IsNullOrEmpty(returnUrl))
                            {
                                URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                            }
                            else
                            {
                                URLHelper.Redirect(currentUrl);
                            }
                        }
                        // Display error otherwise
                        else
                        {
                            lblError.Text = error;
                            lblError.Visible = true;
                        }
                    }
                    // Additional information page is set
                    else
                    {
                        // Store user object in session for additional use
                        string response = (linkedInHelper.LinkedInResponse != null) ? linkedInHelper.LinkedInResponse.OuterXml : null;
                        SessionHelper.SetValue(SESSION_NAME_USERDATA, response);

                        // Redirect to additional info page
                        string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            // Add return URL to parameter
                            targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                        }
                        URLHelper.Redirect(targetURL);
                    }
                }
                // LinkedIn profile id is in DB
                else
                {
                    // Login existing user
                    UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, false, true, ref error);

                    if ((ui != null) && (ui.Enabled))
                    {
                        // Create authentication cookie
                        AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" });

                        int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        activityLogin.Log();

                        // Redirect user
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error which occurred during authentication process
                    else if (!String.IsNullOrEmpty(error))
                    {
                        lblError.Text = error;
                        lblError.Visible = true;
                    }
                    // Otherwise is user disabled
                    else
                    {
                        lblError.Text = GetString("membership.userdisabled");
                        lblError.Visible = true;
                    }
                }
                break;

            // No authentication, do nothing
            case LinkedInHelper.RESPONSE_NOTAUTHENTICATED:
                break;
        }
    }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = SiteContext.CurrentSiteName;

            // Existing account
            if (radSignIn.Checked)
            {
                // Authenticate user
                UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, SiteContext.CurrentSiteName, false);
                if (ui == null)
                {
                    lblError.Text = GetString("ShoppingCartCheckRegistration.LoginFailed");
                    lblError.Visible = true;
                    return false;
                }

                // Sign in customer with existing account
                AuthenticationHelper.AuthenticateUser(ui.UserName, false);

                // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
                ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

                // Assign current user to the current shopping cart
                ShoppingCart.User = ui;

                // Save changes to database
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                // Log "login" activity
                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();

                LoadStep(true);

                // Return false to get to Edit customer page
                return false;
            }
            // New registration
            else if (radNewReg.Checked)
            {
                txtEmail2.Text = txtEmail2.Text.Trim();
                pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

                string[] siteList = { siteName };

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }

                // Check if user exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
                if (ui != null)
                {
                    lblError.Visible = true;
                    lblError.Text = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                    return false;
                }

                // Check all sites where user will be assigned
                if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text = GetString("UserInfo.EmailAlreadyExist");
                    return false;
                }

                // Create new customer and user account and sign in
                // User
                ui = new UserInfo();
                ui.UserName = txtEmail2.Text.Trim();
                ui.Email = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName = txtLastName1.Text.Trim();
                ui.FullName = ui.FirstName + " " + ui.LastName;
                ui.Enabled = true;
                ui.UserIsGlobalAdministrator = false;
                ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign = AnalyticsHelper.Campaign;
                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent;

                try
                {
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    foreach (string site in siteList)
                    {
                        UserInfoProvider.AddUserToSite(ui.UserName, site);

                        // Add user to roles
                        if (ShoppingCartControl.AssignToRoles != "")
                        {
                            AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                        }
                    }

                    // Log registered user
                    AnalyticsHelper.LogRegisteredUser(siteName, ui);

                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text = ex.Message;
                    return false;
                }

                // Customer
                CustomerInfo ci = new CustomerInfo();
                ci.CustomerFirstName = txtFirstName1.Text.Trim();
                ci.CustomerLastName = txtLastName1.Text.Trim();
                ci.CustomerEmail = txtEmail2.Text.Trim();

                ci.CustomerCompany = "";
                ci.CustomerOrganizationID = "";
                ci.CustomerTaxRegistrationID = "";
                if (chkCorporateBody.Checked)
                {
                    ci.CustomerCompany = txtCompany1.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                    }
                }

                ci.CustomerUserID = ui.UserID;
                ci.CustomerSiteID = 0;
                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Track successful registration conversion
                string name = ShoppingCartControl.RegistrationTrackConversionName;
                ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

                // Log "customer registration" activity and update profile
                var activityCustomerRegistration = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                if (activityCustomerRegistration.Data != null)
                {
                    if (ContactID <= 0)
                    {
                        activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    }
                    activityCustomerRegistration.Log();
                }

                // Sign in
                if (ui.UserEnabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, false);
                    ShoppingCart.User = ui;

                    ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activity.Log();
                }

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

                // Send new registration notification email
                if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
                {
                    SendRegistrationNotification(ui);
                }
            }
            // Anonymous customer
            else if (radAnonymous.Checked)
            {
                CustomerInfo ci = null;
                if (ShoppingCart.ShoppingCartCustomerID > 0)
                {
                    // Update existing customer account
                    ci = CustomerInfoProvider.GetCustomerInfo(ShoppingCart.ShoppingCartCustomerID);
                }
                if (ci == null)
                {
                    // Create new customer account
                    ci = new CustomerInfo();
                }

                ci.CustomerFirstName = txtFirstName2.Text.Trim();
                ci.CustomerLastName = txtLastName2.Text.Trim();
                ci.CustomerEmail = txtEmail3.Text.Trim();

                ci.CustomerCompany = "";
                ci.CustomerOrganizationID = "";
                ci.CustomerTaxRegistrationID = "";

                if (chkCorporateBody2.Checked)
                {
                    ci.CustomerCompany = txtCompany2.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID2.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID2.Text.Trim();
                    }
                }

                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                ci.CustomerSiteID = SiteContext.CurrentSiteID;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Log "customer registration" activity
                var activity = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID();
                    activity.Data.ContactID = ContactID;
                    activity.Log();
                }

                // Assign customer to shoppingcart
                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
            }
            else
            {
                return false;
            }
        }
        else
        {
            // Save the customer data
            bool newCustomer = false;
            CustomerInfo ci = CustomerInfoProvider.GetCustomerInfoByUserID(ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID = ShoppingCartControl.UserInfo.UserID;
                ci.CustomerSiteID = 0;
                ci.CustomerEnabled = true;
                newCustomer = true;
            }

            // Old email address
            string oldEmail = ci.CustomerEmail.ToLowerCSafe();

            ci.CustomerFirstName = txtEditFirst.Text.Trim();
            ci.CustomerLastName = txtEditLast.Text.Trim();
            ci.CustomerEmail = txtEditEmail.Text.Trim();

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

            ci.CustomerCompany = "";
            ci.CustomerOrganizationID = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkEditCorpBody.Checked)
            {
                ci.CustomerCompany = txtEditCompany.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtEditOrgID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtEditTaxRegID.Text.Trim();
                }
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Update corresponding user email when required
            if (oldEmail != ci.CustomerEmail.ToLowerCSafe())
            {
                UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID);
                if (user != null)
                {
                    user.Email = ci.CustomerEmail;
                    UserInfoProvider.SetUserInfo(user);
                }
            }

            // Log "customer registration" activity and update contact profile
            if (newCustomer)
            {
                var activity = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            // Set the shopping cart customer ID
            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }

        try
        {
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            ShoppingCart.InvalidateCalculations();
            return true;
        }
        catch
        {
            return false;
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = CMSContext.CurrentSiteName;


            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            #endregion


            #region "Check Email & password"

            // Check whether user with same email does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = CMSContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch");
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text    = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength.ToString());
                return;
            }

            if (!passStrength.IsValid())
            {
                lblError.Visible = true;
                lblError.Text    = AuthenticationHelper.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                return;
            }

            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required
            if (DisplayCaptcha)
            {
                // Verifiy captcha text
                if (!scCaptcha.IsValid())
                {
                    // Display error message if catcha text is not valid
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                    return;
                }
                else
                {
                    // Generate new captcha
                    scCaptcha.GenerateNew();
                }
            }

            #endregion


            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email      = txtEmail.Text.Trim();
            ui.FirstName  = txtFirstName.Text.Trim();
            ui.FullName   = UserInfoProvider.GetFullName(txtFirstName.Text.Trim(), String.Empty, txtLastName.Text.Trim());
            ui.LastName   = txtLastName.Text.Trim();
            ui.MiddleName = "";

            // User name as put by user (no site prefix included)
            String plainUserName = txtEmail.Text.Trim();
            ui.UserName = plainUserName;

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si);
            }

            ui.Enabled  = EnableUserAfterRegistration;
            ui.IsEditor = false;
            ui.IsGlobalAdministrator = false;
            ui.UserURLReferrer       = CMSContext.CurrentUser.URLReferrer;
            ui.UserCampaign          = CMSContext.Campaign;

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if ((requiresAdminApprove = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")))
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(StartingAliasPath);
            }

            #endregion


            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName));
                return;
            }

            #endregion


            #region "License limitations"

            // Check limitations for Global administrator
            if (ui.IsGlobalAdministrator)
            {
                if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedGlobal");
                    return;
                }
            }

            // Check limitations for editors
            if (ui.IsEditor)
            {
                if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Editors, VersionActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedEditor");
                    return;
                }
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            string checkSites = (String.IsNullOrEmpty(AssignToSites)) ? siteName : AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);


            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            ContextResolver resolver = CMSContext.CurrentResolver;
            resolver.SourceData           = data;
            resolver.EncodeResolvedValues = true;

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool              error    = false;
            EventLogProvider  ev       = new EventLogProvider();
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template     = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Retrieve contact ID for confirmation e-mail
                int contactId = 0;
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    // Check if loggin registration activity is enabled
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                    }
                }

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = (ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(ApprovalPage) : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx");
                replacements[0, 1]    += "?userguid=" + ui.UserGUID + (contactId > 0 ? "&contactid=" + contactId.ToString() : String.Empty);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = plainUserName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = passStrength.Text;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = txtEmail.Text;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = txtFirstName.Text;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = txtLastName.Text;

                // Set resolver
                resolver.SourceParameters = replacements;

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;

                email.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress"));
                email.Body = resolver.ResolveMacros(template.TemplateText);

                resolver.EncodeResolvedValues = false;
                email.PlainTextBody           = resolver.ResolveMacros(template.TemplatePlainText);
                email.Subject = resolver.ResolveMacros(emailSubject);

                email.CcRecipients  = template.TemplateCc;
                email.BccRecipients = template.TemplateBcc;

                try
                {
                    MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(siteName, email, true);
                }
                catch (Exception ex)
                {
                    ev.LogEvent("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                else
                {
                    string[,] replacements = new string[4, 2];
                    replacements[0, 0]     = "firstname";
                    replacements[0, 1]     = ui.FirstName;
                    replacements[1, 0]     = "lastname";
                    replacements[1, 1]     = ui.LastName;
                    replacements[2, 0]     = "email";
                    replacements[2, 1]     = ui.Email;
                    replacements[3, 0]     = "username";
                    replacements[3, 1]     = plainUserName;

                    // Set resolver
                    resolver.SourceParameters = replacements;

                    EmailMessage message = new EmailMessage();

                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);

                    resolver.EncodeResolvedValues = false;
                    message.PlainTextBody         = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);
                    message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID);
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Roles & authentication"

            string[] roleList = AssignRoles.Split(';');
            string[] siteList;

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }
            else // If not set user current site
            {
                siteList = new string[] { siteName };
            }

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWithCSafe(".") ? "" : sn;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    CMSContext.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))
                    {
                        URLHelper.Redirect(url);
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
                    }
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
    public override bool ProcessStep()
    {
        string siteName = SiteContext.CurrentSiteName;

        if (IsExistingAccount())
        {
            // Sign in customer with existing account

            // Authenticate user
            //UserInfo ui = UserInfoProvider.GetUserInfo(txtLogin.Text);

            UserInfo ui = AuthenticationHelper.AuthenticateUser(txtLogin.Text.Trim(), txtMotDePasse.Text, SiteContext.CurrentSiteName);

            if (ui == null)
            {
                // ShowError(ResHelper.GetString("ShoppingCartCheckRegistration.LoginFailed"));
                return(false);
            }

            // Set current user
            MembershipContext.AuthenticatedUser = new CurrentUserInfo(ui, true);
            UserInfoProvider.SetPreferredCultures(ui);

            // Sign in
            FormsAuthentication.SetAuthCookie(ui.UserName, false);

            // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
            ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

            // Assign current user to the current shopping cart
            ShoppingCart.User = ui;

            // Save changes to database // Already done in the end of this method
            if (!this.ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCartInfObj);
            }

            //Create a customer for the user if do not yet exist
            CustomerInfo ci = CustomerInfoProvider.GetCustomerInfoByUserID(this.ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID  = this.ShoppingCartControl.UserInfo.UserID;
                ci.CustomerEnabled = true;
            }

            // Old email address
            //string oldEmail = ci.CustomerEmail.ToLower(); ;

            ci.CustomerFirstName = ui.FirstName;
            ci.CustomerLastName  = ui.LastName;
            ci.CustomerEmail     = ui.Email;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Set the shopping cart customer ID
            this.ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }
        else if (IsNewAccount())
        {
            txtEmail2.Text             = txtEmail2.Text.Trim();
            pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

            // Check if user exists
            UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
            if (ui != null)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                return(false);
            }

            // Check all sites where user will be assigned
            string checkSites = (String.IsNullOrEmpty(ShoppingCartControl.AssignToSites)) ? SiteContext.CurrentSiteName : ShoppingCartControl.AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return(false);
            }

            // Create new customer and user account and sign in
            // User



            ui = new UserInfo();


            ui.UserName  = txtEmailRegistration.Text.Trim();
            ui.Email     = txtEmailRegistration.Text.Trim();
            ui.FirstName = txtFirstName.Text.Trim();
            ui.FullName  = UserInfoProvider.GetFullName(txtFirstName.Text.Trim(), String.Empty, txtLastName.Text.Trim());
            ui.LastName  = txtLastName.Text.Trim();
            ui.Enabled   = true;
            ui.UserIsGlobalAdministrator = false;
            ui.UserURLReferrer           = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign = AnalyticsHelper.Campaign;
            ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            try
            {
                UserInfoProvider.SetPassword(ui, txtMotDePasseRegistration.Text);

                string[] siteList;

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }
                else // If not set user current site
                {
                    siteList = new string[] { siteName };
                }

                foreach (string site in siteList)
                {
                    UserInfoProvider.AddUserToSite(ui.UserName, site);

                    // Add user to roles
                    if (ShoppingCartControl.AssignToRoles != "")
                    {
                        AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                    }
                }

                // Log registered user
                AnalyticsHelper.LogRegisteredUser(siteName, ui);

                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                return(false);
            }

            // Customer
            CustomerInfo ci = new CustomerInfo();
            ci.CustomerFirstName = txtFirstName.Text.Trim();
            ci.CustomerLastName  = txtLastName.Text.Trim();
            ci.CustomerEmail     = txtEmailRegistration.Text.Trim();

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkCorporateBody.Checked)
            {
                ci.CustomerCompany = txtCompany1.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                }
            }

            ci.CustomerUserID  = ui.UserID;
            ci.CustomerSiteID  = 0;
            ci.CustomerEnabled = true;
            ci.CustomerCreated = DateTime.Now;
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Track successful registration conversion
            string name = ShoppingCartControl.RegistrationTrackConversionName;
            ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

            // Log "customer registration" activity and update profile
            var activityCustomerRegistration = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
            if (activityCustomerRegistration.Data != null)
            {
                if (ContactID <= 0)
                {
                    activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                }
                activityCustomerRegistration.Log();
            }

            // Sign in
            if (ui.UserEnabled)
            {
                CMSContext.AuthenticateUser(ui.UserName, false);
                ShoppingCart.User = ui;

                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

            // Send new registration notification email
            if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
            {
                SendRegistrationNotification(ui);
            }
            /**aadrresse*/
            // Process billing address
            //------------------------
            int         CountryID  = ValidationHelper.GetInteger(ddlShippingCountry.SelectedValue, 0);
            AddressInfo ai         = null;
            bool        newAddress = true;
            ai = new AddressInfo();
            string mCustomerName = ci.CustomerFirstName + " " + ci.CustomerLastName;
            // newAddress.AddressName = mCustomerName + " , " + txtAdresse.Text + " - " + txtCodePostale.Text + " " + txtVille.Text;


            ai.AddressPersonalName = mCustomerName + " , " + txtAdresse.Text + " - " + txtCodePostale.Text + " " + txtVille.Text;
            ai.AddressLine1        = txtAdresse.Text.Trim();
            ai.AddressLine2        = txtAdresse.Text.Trim();
            ai.AddressCity         = txtVille.Text.Trim();
            ai.AddressZip          = txtCodePostale.Text.Trim();
            ai.AddressCountryID    = CountryID;


            if (newAddress)
            {
                ai.AddressIsBilling  = true;
                ai.AddressIsShipping = !chkShippingAddr.Checked;
                ai.AddressEnabled    = true;
            }
            ai.AddressCustomerID = ci.CustomerID;
            ai.AddressName       = AddressInfoProvider.GetAddressName(ai);

            // Save address and set it's ID to ShoppingCartInfoObj
            AddressInfoProvider.SetAddressInfo(ai);

            // Update current contact's address
            ModuleCommands.OnlineMarketingMapAddress(ai, ContactID);

            ShoppingCart.ShoppingCartBillingAddressID = ai.AddressID;

            // If shopping cart does not need shipping
            if (!ShippingOptionInfoProvider.IsShippingNeeded(ShoppingCart))
            {
                ShoppingCart.ShoppingCartShippingAddressID = 0;
            }
            // If shipping address is different from billing address
            else if (chkShippingAddr.Checked)
            {
                //// Check country presence
                //if (CountrySelector2.CountryID <= 0)
                //{
                //    lblError.Visible = true;
                //    lblError.Text = GetString("countryselector.selectedcountryerr");
                //    return false;
                //}

                //if (!CountrySelector2.StateSelectionIsValid)
                //{
                //    lblError.Visible = true;
                //    lblError.Text = GetString("countryselector.selectedstateerr");
                //    return false;
                //}

                //newAddress = false;
                //// Process shipping address
                ////-------------------------
                //ai = AddressInfoProvider.GetAddressInfo(Convert.ToInt32(drpShippingAddr.SelectedValue));
                //if (ai == null)
                //{
                //    ai = new AddressInfo();
                //    newAddress = true;
                //}

                ai.AddressPersonalName = txtadresseshipping.Text.Trim();
                ai.AddressLine1        = txtadresseshipping.Text.Trim();
                ai.AddressLine2        = txtadresseshipping.Text.Trim();
                ai.AddressCity         = txtvilleshipping.Text.Trim();
                ai.AddressZip          = txtcpshipping.Text.Trim();
                ai.AddressCountryID    = CountryID;

                if (newAddress)
                {
                    ai.AddressIsShipping = true;
                    ai.AddressEnabled    = true;
                    ai.AddressIsBilling  = false;
                    ai.AddressIsCompany  = false;
                    ai.AddressEnabled    = true;
                }
                ai.AddressCustomerID = ci.CustomerID;
                ai.AddressName       = AddressInfoProvider.GetAddressName(ai);

                // Save address and set it's ID to ShoppingCartInfoObj
                AddressInfoProvider.SetAddressInfo(ai);
                ShoppingCart.ShoppingCartShippingAddressID = ai.AddressID;
            }
            // Shipping address is the same as billing address
            else
            {
                ShoppingCart.ShoppingCartShippingAddressID = ShoppingCart.ShoppingCartBillingAddressID;
            }
            /**finadrress*/
            this.ShoppingCartControl.ButtonNextClickAction();
        }

        try
        {
            if (!this.ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCart);
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;
        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName = String.Empty;
            string nickName = String.Empty;
            string firstName = String.Empty;
            string lastName = String.Empty;
            string emailValue = String.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];
            if (txtUserName != null)
            {
                userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            }

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName))
            {
                userName = emailValue;
                if (String.IsNullOrEmpty(emailValue))
                {
                    formUser.StopProcessing = true;
                    lblError.Visible = true;
                    lblError.Text = GetString("customregistrationform.usernameandemail");
                    return;
                }
                else
                {
                    formUser.Data.SetValue("UserName", userName);
                }
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            // Test if "global" or "site" user exists.
            SiteInfo si = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
            if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(currentSiteName, userName))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(currentSiteName, nickName))
            {
                lblError.Visible = true;
                lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                return;
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Validate and save form with new user data
            if (!formUser.Save())
            {
                // Return if saving failed
                return;
            }

            // Get user info from form
            UserInfo ui = (UserInfo)formUser.Info;

            // Add user prefix if settings is on
            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
            }

            ui.Enabled = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign = AnalyticsHelper.Campaign;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            // Fill optionally full user name
            if (String.IsNullOrEmpty(ui.FullName))
            {
                ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
            }

            // Ensure nick name
            if (ui.UserNickName.Trim() == String.Empty)
            {
                ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
            }

            ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent;
            ui.UserSettings.UserLogActivities = true;
            ui.UserSettings.UserShowIntroductionTile = true;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval");
            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            // Get user password and save it in apropriate format after form save
            string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
            UserInfoProvider.SetPassword(ui, password);

            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(data);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            // Prepare macro replacements
            string[,] replacements = new string[6, 2];
            replacements[0, 0] = "confirmaddress";
            replacements[0, 1] = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
            replacements[1, 0] = "username";
            replacements[1, 1] = userName;
            replacements[2, 0] = "password";
            replacements[2, 1] = password;
            replacements[3, 0] = "Email";
            replacements[3, 1] = emailValue;
            replacements[4, 0] = "FirstName";
            replacements[4, 1] = firstName;
            replacements[5, 0] = "LastName";
            replacements[5, 1] = lastName;

            // Set resolver
            resolver.SetNamedSourceData(replacements);

            // Email message
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.EmailFormat = EmailFormatEnum.Default;
            emailMessage.Recipients = ui.Email;

            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                }
            }

            if (template != null)
            {
                emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(currentSiteName + ".CMSNoreplyEmailAddress"));
                // Enable macro encoding for body
                resolver.Settings.EncodeResolvedValues = true;
                emailMessage.Body = resolver.ResolveMacros(template.TemplateText);
                // Disable macro encoding for plaintext body and subject
                resolver.Settings.EncodeResolvedValues = false;
                emailMessage.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);
                emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                emailMessage.CcRecipients = template.TemplateCc;
                emailMessage.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(currentSiteName, emailMessage, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion

            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName);
                }

                if (mEmailTemplate == null)
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    // E-mail template ok
                    replacements = new string[4, 2];
                    replacements[0, 0] = "firstname";
                    replacements[0, 1] = ui.FirstName;
                    replacements[1, 0] = "lastname";
                    replacements[1, 1] = ui.LastName;
                    replacements[2, 0] = "email";
                    replacements[2, 1] = ui.Email;
                    replacements[3, 0] = "username";
                    replacements[3, 1] = userName;

                    // Set resolver
                    resolver.SetNamedSourceData(replacements);
                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;

                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients = ToAddress;
                    message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                    message.CcRecipients = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(currentSiteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion

            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                {
                    HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(currentSiteName, ui);
            }

            #endregion

            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }

                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion

            #region "Site and roles addition and authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string siteName in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, sn))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlRegForm.Visible = false;
                lblInfo.Visible = true;
                lblInfo.Text = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty);
                if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash")))
                {
                    URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl));
                }
                else if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }