using System; using System.Data; using System.Collections; using System.Text; using System.Web; using System.Web.UI; using CMS.CMSHelper; using CMS.GlobalHelper; using CMS.MembershipProvider; using CMS.PortalControls; using CMS.PortalEngine; using CMS.SettingsProvider; using CMS.SiteProvider; using CMS.DocumentEngine; using CMS.URLRewritingEngine; using CMS.WebAnalytics; public partial class CMSWebParts_Membership_Registration_LiveIDUsersRequiredData : CMSAbstractWebPart { #region "Private variables" private WindowsLiveLogin.User liveUser; private string mDefaultTargetUrl = String.Empty; #endregion #region "Public properties" /// /// Gets or sets the value that indicates whether email to user should be sent. /// public bool SendWelcomeEmail { get { return ValidationHelper.GetBoolean(GetValue("SendWelcomeEmail"), true); } set { SetValue("SendWelcomeEmail", value); } } /// /// Gets or sets registration approval page URL. /// public string ApprovalPage { get { return DataHelper.GetNotEmpty(GetValue("ApprovalPage"), ""); } set { SetValue("ApprovalPage", value); } } /// /// Gets or sets the sender email (from). /// public string FromAddress { get { return DataHelper.GetNotEmpty(GetValue("FromAddress"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress")); } set { SetValue("FromAddress", value); } } /// /// Gets or sets the recipient email (to). /// public string ToAddress { get { return DataHelper.GetNotEmpty(GetValue("ToAddress"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSAdminEmailAddress")); } set { SetValue("ToAddress", value); } } /// /// Gets or sets the value that indicates whether after successful registration is /// notification email sent to the administrator /// public bool NotifyAdministrator { get { return ValidationHelper.GetBoolean(GetValue("NotifyAdministrator"), false); } set { SetValue("NotifyAdministrator", value); } } /// /// Gets or sets the message which is displayed after successful registration. /// public string DisplayMessage { get { return ValidationHelper.GetString(GetValue("DisplayMessage"), ""); } set { SetValue("DisplayMessage", value); } } /// /// Gets or sets the value which enables abitity of new user to set password. /// public bool AllowFormsAuthentication { get { return ValidationHelper.GetBoolean(GetValue("AllowFormsAuthentication"), false); } set { SetValue("AllowFormsAuthentication", value); plcPasswordNew.Visible = value; } } /// /// Gets or sets the value which enables abitity join liveid with existing account. /// public bool AllowExistingUser { get { return ValidationHelper.GetBoolean(GetValue("AllowExistingUser"), true); } set { SetValue("AllowExistingUser", value); plcPasswordNew.Visible = value; } } /// /// Gets or sets the default target url (rediredction when the user is logged in). /// public string DefaultTargetUrl { get { return ValidationHelper.GetString(GetValue("DefaultTargetUrl"), mDefaultTargetUrl); } set { SetValue("DefaultTargetUrl", value); mDefaultTargetUrl = value; } } /// /// Gets or sets the value which determines the behaviour if no Live ID user. /// public bool HideForNoLiveID { get { return ValidationHelper.GetBoolean(GetValue("HideForNoLiveID"), false); } set { SetValue("HideForNoLiveID", value); } } #endregion #region "Conversion properties" /// /// Gets or sets the conversion track name used after successful registration. /// public string TrackConversionName { get { return ValidationHelper.GetString(GetValue("TrackConversionName"), SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSLiveIDConversionName")); } set { if ((value != null) && (value.Length > 400)) { value = value.Substring(0, 400); } SetValue("TrackConversionName", value); } } /// /// Gets or sets the conversion value used after successful registration. /// public double ConversionValue { get { return ValidationHelper.GetDoubleSystem(GetValue("ConversionValue"), 0); } set { SetValue("ConversionValue", value); } } #endregion #region "Methods" /// /// Content loaded event handler. /// public override void OnContentLoaded() { base.OnContentLoaded(); SetupControl(); } /// /// Initializes the control properties. /// protected void SetupControl() { if (StopProcessing) { // Do nothing } else { if (SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSEnableWindowsLiveID")) { plcPasswordNew.Visible = AllowFormsAuthentication; pnlExistingUser.Visible = AllowExistingUser; liveUser = SessionHelper.GetValue("windowsliveloginuser") as WindowsLiveLogin.User; // There is no windows live user object stored in session - hide all if ((liveUser == null) && HideForNoLiveID) { Visible = false; } // WAI validation lblPasswordNew.AssociatedControlClientID = passStrength.InputClientID; } else { // Error label is displayed in Design mode when Windows Live ID is disabled if (CMSContext.ViewMode == ViewModeEnum.Design) { StringBuilder parameter = new StringBuilder(); parameter.Append(GetString("header.sitemanager") + " -> "); parameter.Append(GetString("settingscategory.cmssettings") + " -> "); parameter.Append(GetString("settingscategory.cmsmembership") + " -> "); parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> "); parameter.Append(GetString("settingscategory.cmswindowsliveid")); if (CMSContext.CurrentUser.UserSiteManagerAdmin) { // Make it link for SiteManager Admin parameter.Insert(0, ""); parameter.Append(""); } lblError.Text = String.Format(GetString("mem.liveid.disabled"), parameter.ToString()); plcError.Visible = true; plcContent.Visible = false; } else { Visible = false; } } } } /// /// Handles btnOkExist click, joins existing user with liveid token. /// protected void btnOkExist_Click(object sender, EventArgs e) { // Live user must be retrieved from session if (liveUser != null) { if (txtUserName.Text != String.Empty) // && (txtPassword.Text != String.Empty)) { // Try to authenticate user UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUserName.Text, txtPassword.Text, CMSContext.CurrentSiteName); // Check banned IPs BannedIPInfoProvider.CheckIPandRedirect(CMSContext.CurrentSiteName, BanControlEnum.Login); if (ui != null) { // Add liveID token to user ui.UserSettings.WindowsLiveID = liveUser.Id; UserInfoProvider.SetUserInfo(ui); // Remove live user object from session, won't be needed Session.Remove("windowsliveloginuser"); // Set authentication cookie and redirect to page SetAuthCookieAndRedirect(ui); } else // Invalid credentials { lblError.Text = GetString("Login_FailureText"); plcError.Visible = true; } } else // User did not fill the form { lblError.Text = GetString("mem.liveid.fillloginform"); plcError.Visible = true; } } } /// /// Handles btnOkNew click, creates new user and joins it with liveid token. /// protected void btnOkNew_Click(object sender, EventArgs e) { if (liveUser != null) { // Validate entered values string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.liveid.fillcorrectusername")) .IsEmail(txtEmail.Text, GetString("mem.liveid.fillvalidemail")).Result; string password = passStrength.Text.Trim(); // 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); } } string siteName = CMSContext.CurrentSiteName; // Check whether email is unique if it is required if ((errorMessage == String.Empty) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0)) { errorMessage = GetString("UserInfo.EmailAlreadyExist"); } // Check reserved names if ((errorMessage == String.Empty) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim())) { errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim())); } if (errorMessage == String.Empty) { string userName = txtUserNameNew.Text.Trim(); // Check if user with given username already exists UserInfo ui = UserInfoProvider.GetUserInfo(userName); UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, CMSContext.CurrentSite)); // User with given username is already registered if ((ui != null) || (siteui != null)) { plcError.Visible = true; lblError.Text = GetString("mem.openid.usernameregistered"); } else { // Register new user string error = DisplayMessage; ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, false, ref error); DisplayMessage = error; if (ui != null) { // Set additional information ui.UserName = ui.UserNickName = ui.FullName = userName; // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, CMSContext.CurrentSite); } ui.Email = txtEmail.Text; // 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 Session.Remove("windowsliveloginuser"); // Send registration e-mails 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); } // Track 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); // Display error message if (!String.IsNullOrEmpty(DisplayMessage)) { lblInfo.Visible = true; lblInfo.Text = DisplayMessage; plcForm.Visible = false; } else { URLHelper.Redirect(ResolveUrl("~/Default.aspx")); } } } } else { lblError.Text = errorMessage; plcError.Visible = true; } } } /// /// Helper method, set authentication cookie and redirect to return URL or default page. /// /// User info private void SetAuthCookieAndRedirect(UserInfo ui) { // Create autentification cookie if (ui.Enabled) { AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "liveidlogin" }); // Log activity int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables); activityLogin.Log(); // Redirect to default page if (!String.IsNullOrEmpty(DefaultTargetUrl)) { URLHelper.Redirect(ResolveUrl(DefaultTargetUrl)); } // If there is some return page redirect there else if ((liveUser != null) && !string.IsNullOrEmpty(liveUser.Context)) { URLHelper.Redirect(liveUser.Context); } // Refresh current page to update see user signed in else { string url = URLRewriter.CurrentURL; URLHelper.Redirect(url); } } } #endregion }