public void Log(IEnumerable <Activity> activities) { if (activities == null) { throw new ArgumentNullException("activities"); } int num = 0; bool flag = false; using (IEnumerator <Activity> enumerator = activities.GetEnumerator()) { while (enumerator.MoveNext()) { Activity activity = enumerator.Current; flag = ActivityLogHelper.CatchNonFatalExceptions(delegate { this.Log(activity); }, null); if (flag) { break; } num++; } } if (flag) { ActivityFileLogger.activityPerfCounters.ActivityLogsFileWriteExceptions.Increment(); } ActivityFileLogger.activityPerfCounters.ActivityLogsFileWriteCount.IncrementBy((long)num); }
/// <summary> /// Helper method, set authentication cookie and redirect to return URL or default page. /// </summary> /// <param name="ui">User info</param> /// <param name="user">Windows live user</param> private void SetAuthCookieAndRedirect(UserInfo ui) { // Create autentification cookie UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, false, Session.Timeout, new string[] { "liveidlogin" }); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, (currentDoc != null ? currentDoc.NodeID : 0), siteName, CMSContext.Campaign, (currentDoc != null ? currentDoc.DocumentCulture : null)); } } // Redirect will be used on parent window if (WindowsLiveLogin.UseServerSideAuthorization) { // If there is some return url redirect there if (!String.IsNullOrEmpty(relativeURL)) { URLHelper.Redirect(ResolveUrl(relativeURL)); } else // Redirect to default page { URLHelper.Redirect(defaultPage); } } }
//[ValidateAntiForgeryToken] public async Task <bool> Create(ActivityLogViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.UserEMail); if (user != null) { var Registro = new ActivityLog(); Registro.Date = DateTime.Now; Registro.Ip = ActivityLogHelper.GetIPClient(); Registro.MacAddress = ActivityLogHelper.GetMacAdreessDeviceClient(); Registro.NameDevice = ActivityLogHelper.GetNameDeviceClient(); Registro.UserId = user.Id; Registro.UserEMail = user.Email; Registro.UserFullName = user.FullName; Registro.Controller = model.Controller; Registro.Action = model.Action; Registro.Description = model.Description; Registro.Status = model.Status; Registro.Type = model.Type; _context.Add(Registro); await _context.SaveChangesAsync(); return(true); } } return(false); }
/// <summary> /// Helper method, set authentication cookie and redirect to return URL or default page. /// </summary> /// <param name="ui">User info</param> /// <param name="user">Windows live user</param> private void SetAuthCookieAndRedirect(UserInfo ui) { // Create autentification cookie if (ui.Enabled) { UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogin" }); // Log activity string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, (currentDoc != null ? currentDoc.NodeID : 0), siteName, CMSContext.Campaign, (currentDoc != null ? currentDoc.DocumentCulture : null)); } } string returnUrl = QueryHelper.GetString("returnurl", null); // Redirect to ReturnURL if (!String.IsNullOrEmpty(returnUrl)) { URLHelper.Redirect(ResolveUrl(HttpUtility.UrlDecode(returnUrl))); } // Redirect to default page else if (!String.IsNullOrEmpty(this.DefaultTargetUrl)) { URLHelper.Redirect(ResolveUrl(this.DefaultTargetUrl)); } // Otherwise refresh current page else { URLHelper.Redirect(URLRewriter.CurrentURL); } } }
/// <summary> /// Logs analytics and/or activity event. /// </summary> /// <param name="file">File to be sent</param> protected void LogEvent(CMSOutputFile file) { if (IsLiveSite && (file != null) && (file.FileNode != null) && (file.FileNode.NodeClassName.ToLower() == "cms.file")) { // Check if request is multipart request and log event if not GetRange(100, HttpContext.Current); // GetRange() parses request header and sets 'IsMultipart' property if (!IsMultipart) { if (IsRangeRequest && (BrowserHelper.IsIE() || BrowserHelper.IsChrome())) { return; } } else { return; } if (file.Attachment == null) { return; } // Log analytics hit if (AnalyticsHelper.IsLoggingEnabled(CurrentSiteName, String.Empty) && AnalyticsHelper.TrackFileDownloadsEnabled(CurrentSiteName) && !AnalyticsHelper.IsFileExtensionExcluded(CurrentSiteName, file.Attachment.AttachmentExtension)) { HitLogProvider.LogHit(HitLogProvider.FILE_DOWNLOADS, CurrentSiteName, file.FileNode.DocumentCulture, file.FileNode.NodeAliasPath, file.FileNode.NodeID); } // Log download activity // Get current contact ID and check if activity logging is enabled int contactId = 0; bool loggingActivityEnabled = LoggingActivityEnabled(file, out contactId); if (loggingActivityEnabled && (contactId > 0)) { ActivityLogHelper.LogFileDownload(contactId, CurrentSiteName, file.FileNode.NodeID, file.FileNode.DocumentName, file.Attachment.AttachmentName, file.FileNode.DocumentCulture); } } }
public static ActivitySession Create(MailboxSession session) { Util.ThrowOnNullArgument(session, "session"); if (!ActivityLogHelper.IsActivityLoggingEnabled(false)) { return(null); } if (session.LogonType == LogonType.Delegated || session.LogonType == LogonType.DelegatedAdmin) { ExTraceGlobals.SessionTracer.TraceDebug(0L, "Skipping Activity Logging since session is from delegate."); return(null); } IActivityLogger activityLogger = ActivityLogger.Create(session); if (activityLogger == null) { ExTraceGlobals.SessionTracer.TraceDebug(0L, "Skipping Activity Logging since the activity logger couldn't be created"); return(null); } ActivitySession.ClientInfo clientInfo = ActivitySession.ExtractClientInfo(session); return(new ActivitySession(session, clientInfo, activityLogger)); }
/// <summary> /// Helper method, set authentication cookie and redirect to return URL or default page. /// </summary> /// <param name="ui">User info</param> private void SetAuthCookieAndRedirect(UserInfo ui) { // Create autentification cookie if (ui.Enabled) { UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "liveidlogin" }); // Log activity string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture); } } // Redirect to default page if (!String.IsNullOrEmpty(this.DefaultTargetUrl)) { URLHelper.Redirect(ResolveUrl(this.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); } } }
private void ReadInferenceSettings(MailboxSession mailboxSession, UserContext userContext, OwaUserConfiguration owaUserConfiguration) { owaUserConfiguration.ApplicationSettings.InferenceEnabled &= ActivityLogHelper.IsActivityLoggingEnabled(false); if (userContext.FeaturesManager.ClientServerSettings.FolderBasedClutter.Enabled) { InferenceSettingsType.ReadFolderBasedClutterSettings(mailboxSession, userContext.FeaturesManager.ConfigurationSnapshot, owaUserConfiguration); return; } bool featureSupportedState = InferenceSettingsType.GetFeatureSupportedState(mailboxSession, userContext); owaUserConfiguration.SegmentationSettings.PredictedActions = featureSupportedState; if (featureSupportedState) { InferenceSettingsType inferenceSettingsType = new InferenceSettingsType(); inferenceSettingsType.LoadAll(mailboxSession); if (inferenceSettingsType.TryMigrateUserOptionsValue(mailboxSession, owaUserConfiguration.UserOptions)) { ExTraceGlobals.CoreTracer.TraceDebug((long)this.GetHashCode(), "Migrated inference flags from Owa.Settings to Inference.Settings configuration in GetOwaUserConfiguration."); } owaUserConfiguration.UserOptions.ShowInferenceUiElements = inferenceSettingsType.IsClutterUIEnabled.GetValueOrDefault(false); } }
public void Log(IEnumerable <Activity> activities) { if (activities == null || !activities.Any <Activity>()) { throw new ArgumentException("activities enumerable cannot be null or empty"); } List <Activity> activitiesCache = (from activity in activities where activity != null select activity).ToList <Activity>(); ActivityLogger.activityPerfCounters.ActivityLogsActivityCount.IncrementBy((long)activitiesCache.Count); if (this.storeLogger != null) { bool flag = ActivityLogHelper.CatchNonFatalExceptions(delegate { this.storeLogger.Append(this.GetStoreEligibleActivities(activitiesCache)); }, null); if (flag) { ActivityLogger.activityPerfCounters.ActivityLogsStoreWriteExceptions.Increment(); } } ActivityFileLogger.Instance.Log(activitiesCache); }
/// <summary> /// Checks status of current user. /// </summary> protected void CheckStatus() { // Get current site name string siteName = CMSContext.CurrentSiteName; string error = null; // Check return URL string returnUrl = QueryHelper.GetString("returnurl", null); returnUrl = HttpUtility.UrlDecode(returnUrl); // Get current URL string currentUrl = URLHelper.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 = SettingsKeyProvider.GetStringValue(siteName + ".CMSRequiredLinkedInPage").Trim(); // No page set, user can be created if (String.IsNullOrEmpty(additionalInfoPage)) { // Register new user UserInfo ui = UserInfoProvider.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, true, true, ref error); // If user was successfuly 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 autentification cookie UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" }); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, (currentDoc != null ? currentDoc.NodeID : 0), siteName, CMSContext.Campaign, (currentDoc != null ? currentDoc.DocumentCulture : null)); } } } // Notify administrator if (this.NotifyAdministrator && !String.IsNullOrEmpty(this.FromAddress) && !String.IsNullOrEmpty(this.ToAddress)) { UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress); } // Send registration e-mails // E-mail confirmation is not required as user already provided confirmation by successful login using OpenID UserInfoProvider.SendRegistrationEmails(ui, null, null, false, false); // Log registration into analytics UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, siteName, ui); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) && ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId); TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture); } } // 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 SessionHelper.SetValue(SESSION_NAME_USERDATA, linkedInHelper.LinkedInResponse); // 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 = UserInfoProvider.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, false, true, ref error); if ((ui != null) && (ui.Enabled)) { // Create autentification cookie UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "linkedinlogin" }); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture); } } // 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; // No authentication, do nothing case LinkedInHelper.RESPONSE_NOTAUTHENTICATED: break; } }
/// <summary> /// Checks status of current user. /// </summary> protected void CheckStatus() { // Get current site name string siteName = CMSContext.CurrentSiteName; string error = null; // Check return URL string returnUrl = QueryHelper.GetString("returnurl", null); returnUrl = HttpUtility.UrlDecode(returnUrl); // Get current URL string currentUrl = URLHelper.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 = SettingsKeyProvider.GetStringValue(siteName + ".CMSRequiredOpenIDPage").Trim(); // No page set, user can be created if (String.IsNullOrEmpty(additionalInfoPage)) { // Register new user UserInfo ui = UserInfoProvider.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 UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openidlogin" }); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture); } } } // Send registration e-mails // E-mail confirmation is not required as user already provided confirmation by successful login using OpenID UserInfoProvider.SendRegistrationEmails(ui, null, null, false, false); // Notify administrator if (this.NotifyAdministrator && !String.IsNullOrEmpty(this.FromAddress) && !String.IsNullOrEmpty(this.ToAddress)) { UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress); } // Track user registration UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, siteName, ui); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId); TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture); } } // 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 SessionHelper.SetValue(SESSION_NAME_USERDATA, openIDhelper.GetResponseObject()); // 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 = UserInfoProvider.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error); if ((ui != null) && (ui.Enabled)) { // Create autentification cookie UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "openilogin" }); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, currentDoc.NodeID, siteName, CMSContext.Campaign, currentDoc.DocumentCulture); } } // 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 (this.plcAccount.Visible) { string siteName = CMSContext.CurrentSiteName; // Existing account if (radSignIn.Checked) { // Authenticate user UserInfo ui = UserInfoProvider.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, CMSContext.CurrentSiteName, false); if (ui == null) { lblError.Text = GetString("ShoppingCartCheckRegistration.LoginFailed"); lblError.Visible = true; return(false); } // Sign in customer with existing account CMSContext.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 this.ShoppingCartInfoObj.UserInfoObj = ui; // Save changes to database if (!this.ShoppingCartControl.IsInternalOrder) { ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCartInfoObj); } // Log "login" activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { this.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(this.ContactID); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { TreeNode currentDoc = CMSContext.CurrentDocument; int nodeId = (currentDoc != null ? currentDoc.NodeID : 0); string culture = (currentDoc != null ? currentDoc.DocumentCulture : null); ActivityLogProvider.LogLoginActivity(this.ContactID, ui, URLHelper.CurrentRelativePath, nodeId, siteName, ui.UserCampaign, culture); } } 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; // 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(this.ShoppingCartControl.AssignToSites)) ? CMSContext.CurrentSiteName : this.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 = 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 = CMSContext.CurrentUser.URLReferrer; ui.UserCampaign = CMSContext.Campaign; ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; int nodeId = 0; string culture = null; try { UserInfoProvider.SetPassword(ui, passStrength.Text); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(this.ShoppingCartControl.AssignToSites)) { siteList = this.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 (this.ShoppingCartControl.AssignToRoles != "") { AssignUserToRoles(ui.UserName, this.ShoppingCartControl.AssignToRoles, site); } } // Log registered user AnalyticsHelper.LogRegisteredUser(siteName, ui); // Log "user registered" activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui) && ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { TreeNode currentDoc = CMSContext.CurrentDocument; this.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, this.ContactID); nodeId = (currentDoc != null ? currentDoc.NodeID : 0); culture = (currentDoc != null ? currentDoc.DocumentCulture : null); ActivityLogProvider.LogRegistrationActivity(this.ContactID, ui, URLHelper.CurrentRelativePath, nodeId, siteName, ui.UserCampaign, culture); } } catch (Exception ex) { lblError.Visible = true; lblError.Text = ex.Message; return(false); } // Customer CustomerInfo ci = new CustomerInfo(); ci.CustomerFirstName = this.txtFirstName1.Text.Trim(); ci.CustomerLastName = this.txtLastName1.Text.Trim(); ci.CustomerEmail = this.txtEmail2.Text.Trim(); ci.CustomerCompany = ""; ci.CustomerOrganizationID = ""; ci.CustomerTaxRegistrationID = ""; if (chkCorporateBody.Checked) { ci.CustomerCompany = this.txtCompany1.Text.Trim(); if (mShowOrganizationIDField) { ci.CustomerOrganizationID = this.txtOrganizationID.Text.Trim(); } if (mShowTaxRegistrationIDField) { ci.CustomerTaxRegistrationID = this.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 = this.ShoppingCartControl.RegistrationTrackConversionName; ECommerceHelper.TrackRegistrationConversion(this.ShoppingCartInfoObj.SiteName, name); // Log "customer registration" activity and update profile if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui) && ActivitySettingsHelper.CustomerRegistrationEnabled(siteName)) { if (this.ContactID <= 0) { this.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ci, this.ContactID); this.ShoppingCartControl.TrackActivityCustomerRegistration(ci, ui, this.ContactID, siteName, URLHelper.CurrentRelativePath); } // Sign in if (ui.UserEnabled) { CMSContext.AuthenticateUser(ui.UserName, false); this.ShoppingCartInfoObj.UserInfoObj = ui; // Log "login" activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { this.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(this.ContactID); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { if (nodeId <= 0) { TreeNode currentDoc = CMSContext.CurrentDocument; nodeId = (currentDoc != null ? currentDoc.NodeID : 0); culture = (currentDoc != null ? currentDoc.DocumentCulture : null); } ActivityLogProvider.LogLoginActivity(this.ContactID, ui, URLHelper.CurrentRelativePath, nodeId, siteName, ui.UserCampaign, culture); } } } this.ShoppingCartInfoObj.ShoppingCartCustomerID = ci.CustomerID; // Send new registration notification email if (this.ShoppingCartControl.SendNewRegistrationNotificationToAddress != "") { SendRegistrationNotification(ui); } } // Anonymous customer else if (radAnonymous.Checked) { CustomerInfo ci = null; if (this.ShoppingCartInfoObj.ShoppingCartCustomerID > 0) { // Update existing customer account ci = CustomerInfoProvider.GetCustomerInfo(this.ShoppingCartInfoObj.ShoppingCartCustomerID); } if (ci == null) { // Create new customer account ci = new CustomerInfo(); } ci.CustomerFirstName = this.txtFirstName2.Text.Trim(); ci.CustomerLastName = this.txtLastName2.Text.Trim(); ci.CustomerEmail = this.txtEmail3.Text.Trim(); ci.CustomerCompany = ""; ci.CustomerOrganizationID = ""; ci.CustomerTaxRegistrationID = ""; ci.CustomerCompany = this.txtCompany2.Text.Trim(); if (mShowOrganizationIDField) { ci.CustomerOrganizationID = this.txtOrganizationID2.Text.Trim(); } if (mShowTaxRegistrationIDField) { ci.CustomerTaxRegistrationID = this.txtTaxRegistrationID2.Text.Trim(); } ci.CustomerEnabled = true; ci.CustomerCreated = DateTime.Now; ci.CustomerSiteID = CMSContext.CurrentSiteID; CustomerInfoProvider.SetCustomerInfo(ci); // Log "customer registration" activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) && ActivitySettingsHelper.CustomerRegistrationEnabled(siteName)) { this.ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID(); this.ShoppingCartControl.TrackActivityCustomerRegistration(ci, CMSContext.CurrentUser, this.ContactID, siteName, URLHelper.CurrentRelativePath); } // Assign customer to shoppingcart this.ShoppingCartInfoObj.ShoppingCartCustomerID = ci.CustomerID; } else { return(false); } } else { // Save the customer data bool newCustomer = false; CustomerInfo ci = CustomerInfoProvider.GetCustomerInfoByUserID(this.ShoppingCartControl.UserInfo.UserID); if (ci == null) { ci = new CustomerInfo(); ci.CustomerUserID = this.ShoppingCartControl.UserInfo.UserID; ci.CustomerSiteID = 0; ci.CustomerEnabled = true; newCustomer = true; } // Old email address string oldEmail = ci.CustomerEmail.ToLower(); ci.CustomerFirstName = this.txtEditFirst.Text.Trim(); ci.CustomerLastName = this.txtEditLast.Text.Trim(); ci.CustomerEmail = this.txtEditEmail.Text.Trim(); pnlCompanyAccount2.Visible = chkEditCorpBody.Checked; ci.CustomerCompany = ""; ci.CustomerOrganizationID = ""; ci.CustomerTaxRegistrationID = ""; if (chkEditCorpBody.Checked) { ci.CustomerCompany = this.txtEditCompany.Text.Trim(); if (mShowOrganizationIDField) { ci.CustomerOrganizationID = this.txtEditOrgID.Text.Trim(); } if (mShowTaxRegistrationIDField) { ci.CustomerTaxRegistrationID = this.txtEditTaxRegID.Text.Trim(); } } // Update customer data CustomerInfoProvider.SetCustomerInfo(ci); // Update corresponding user email when required if (oldEmail != ci.CustomerEmail.ToLower()) { UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID); if (user != null) { user.Email = ci.CustomerEmail; UserInfoProvider.SetUserInfo(user); } } // Log "customer registration" activity and update contact profile string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) && ActivitySettingsHelper.CustomerRegistrationEnabled(siteName)) { this.ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID(); ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ci, this.ContactID); if (newCustomer) { this.ShoppingCartControl.TrackActivityCustomerRegistration(ci, CMSContext.CurrentUser, this.ContactID, siteName, URLHelper.CurrentRelativePath); } } // Set the shopping cart customer ID this.ShoppingCartInfoObj.ShoppingCartCustomerID = ci.CustomerID; } try { if (!this.ShoppingCartControl.IsInternalOrder) { ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCartInfoObj); } return(true); } catch { return(false); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { this.Visible = false; } else { if (QueryHelper.GetInteger("logout", 0) > 0) { // Sign out from CMS FormsAuthentication.SignOut(); CMSContext.ClearShoppingCart(); 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; } this.Visible = false; return; } // Try to retrieve return URL from query string returnUrl = QueryHelper.GetString("returnurl", null); // Init Facebook Connect if (this.Page is ContentPage) { // Adding XML namespace ((ContentPage)this.Page).XmlNamespace = FacebookConnectHelper.GetFacebookXmlNamespace(); } // Init FB connect ltlScript.Text = FacebookConnectHelper.GetFacebookInitScriptForSite(currentSiteName); // 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); string facebookUserId = ""; bool facebookCookiesValid = FacebookConnectHelper.GetFacebookSessionInfo(currentSiteName, out facebookUserId) == FacebookValidationEnum.ValidSignature; // If user is already authenticated if (CMSContext.CurrentUser.IsAuthenticated()) { // Is user logged in using Facebook Connect? if (!facebookCookiesValid || ((CMSContext.CurrentUser.UserSettings != null) && (CMSContext.CurrentUser.UserSettings.UserFacebookID != facebookUserId))) { // 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 ((QueryHelper.GetInteger(CONFIRMATION_URLPARAMETER, 0) > 0) && 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 UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" }); UserInfoProvider.SetPreferredCultures(ui); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.UserLoginEnabled(currentSiteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, currDoc.NodeID, currentSiteName, CMSContext.Campaign, currDoc.DocumentCulture); } } // 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 = UserInfoProvider.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 UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" }); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.UserLoginEnabled(currentSiteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, currDoc.NodeID, currentSiteName, CMSContext.Campaign, currDoc.DocumentCulture); } } } // Send registration e-mails // E-mail confirmation is not required as user already provided confirmation by successful login using Facebook connect UserInfoProvider.SendRegistrationEmails(ui, null, null, false, false); // Notify administrator if (this.NotifyAdministrator && !String.IsNullOrEmpty(this.FromAddress) && !String.IsNullOrEmpty(this.ToAddress)) { UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress); } // Log registration into analytics UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, currentSiteName, ui); // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui) && ActivitySettingsHelper.UserRegistrationEnabled(currentSiteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId); TreeNode currDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, currDoc.NodeID, currentSiteName, CMSContext.Campaign, currDoc.DocumentCulture); } } // 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" this.Visible = DisplayMessage(); } } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.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 ((this.PasswordMinLength > 0) && (passStrength.Text.Length < this.PasswordMinLength)) { lblError.Visible = true; lblError.Text = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), this.PasswordMinLength.ToString()); return; } if (!passStrength.IsValid()) { lblError.Visible = true; lblError.Text = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName); return; } if (!ValidationHelper.IsEmail(txtEmail.Text.ToLower())) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"); return; } #endregion #region "Captcha" // Check if captcha is required if (this.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 = txtFirstName.Text.Trim() + " " + 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 = this.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(this.StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.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(this.AssignToSites)) ? siteName : this.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); #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 (this.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) { // Rretrieve 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] = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.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 ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; resolver.EncodeResolvedValues = true; // 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 && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.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; ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, this.FromAddress); message.Recipients = this.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 (this.TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.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) { if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { int contactId = 0; // Log registration activity if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } // Log login activity if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName)) { if (contactId <= 0) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } ActivityLogHelper.UpdateContactLastLogon(contactId); // Update last logon time if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } } } #endregion #region "Roles & authentication" string[] roleList = this.AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(this.AssignToSites)) { siteList = this.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.StartsWith(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (this.DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = this.DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } if (this.RedirectToURL != String.Empty) { URLHelper.Redirect(this.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.StartsWith("~") || url.StartsWith("/") || 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> /// Logged in handler. /// </summary> void loginElem_LoggedIn(object sender, EventArgs e) { // Set view mode to live site after login to prevent bar with "Close preview mode" CMSContext.ViewMode = CMS.PortalEngine.ViewModeEnum.LiveSite; // Ensure response cookie CookieHelper.EnsureResponseCookie(FormsAuthentication.FormsCookieName); // Set cookie expiration if (loginElem.RememberMeSet) { CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddYears(1), false); } else { // Extend the expiration of the authentication cookie if required if (!UserInfoProvider.UseSessionCookies && (HttpContext.Current != null) && (HttpContext.Current.Session != null)) { CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddMinutes(Session.Timeout), false); } } // Current username string userName = loginElem.UserName; // Get user name (test site prefix too) UserInfo ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, CMSContext.CurrentSite); // Check whether safe user name is required and if so get safe username if (RequestHelper.IsMixedAuthentication() && UserInfoProvider.UseSafeUserName) { // User stored with safe name userName = ValidationHelper.GetSafeUserName(this.loginElem.UserName, CMSContext.CurrentSiteName); // Find user by safe name ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, CMSContext.CurrentSite); if (ui != null) { // Authenticate user by site or global safe username CMSContext.AuthenticateUser(ui.UserName, this.loginElem.RememberMeSet); } } // Log activity (warning: CMSContext contains info of previous user) if (ui != null) { // If user name is site prefixed, authenticate user manually if (UserInfoProvider.IsSitePrefixedUser(ui.UserName)) { CMSContext.AuthenticateUser(ui.UserName, this.loginElem.RememberMeSet); } // Log activity string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && ActivitySettingsHelper.UserLoginEnabled(siteName)) { int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogHelper.UpdateContactLastLogon(contactId); if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { TreeNode currentDoc = CMSContext.CurrentDocument; ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, (currentDoc != null ? currentDoc.NodeID : 0), CMSContext.CurrentSiteName, CMSContext.Campaign, (currentDoc != null ? currentDoc.DocumentCulture : null)); } } } // Redirect user to the return url, or if is not defined redirect to the default target url string url = QueryHelper.GetString("ReturnURL", string.Empty); if (!string.IsNullOrEmpty(url)) { if (url.StartsWith("~") || url.StartsWith("/") || QueryHelper.ValidateHash("hash")) { URLHelper.Redirect(ResolveUrl(ValidationHelper.GetString(Request.QueryString["ReturnURL"], ""))); } else { URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext"))); } } else { if (DefaultTargetUrl != "") { URLHelper.Redirect(ResolveUrl(DefaultTargetUrl)); } else { URLHelper.Redirect(URLRewriter.CurrentURL); } } }
// Token: 0x06000136 RID: 310 RVA: 0x00007DAC File Offset: 0x00005FAC private static bool IsOutlookActivityProcessingNeeded(MapiEvent mapiEvent, MailboxData mailboxData) { return(ActivityLogHelper.IsActivityLoggingEnabled(false) && CommonConfiguration.Singleton.OutlookActivityProcessingEnabledInEba && mapiEvent.ObjectClass == "IPM.Activity" && mapiEvent.EventFlags.HasFlag(MapiEventFlags.FolderAssociated) && (mailboxData == null || mailboxData.MatchCachedDefaultFolderType(mapiEvent.ParentEntryId) == DefaultFolderType.Inbox) && mapiEvent.EventMask.HasFlag(MapiEventTypeFlags.ObjectCreated) && mapiEvent.ClientType != MapiEventClientTypes.EventBasedAssistants); }
protected override object InternalTryGetValue(PropertyBag.BasicPropertyStore propertyBag) { return(ActivityLogHelper.IsActivityLoggingEnabled(false)); }
/// <summary> /// OK click handler (Proceed registration). /// </summary> void btnRegister_Click(object sender, EventArgs e) { if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.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 (this.DisplayCaptcha) { // Verify captcha text if (!captchaElem.IsValid()) { // Display error message if catcha 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 duplicit 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 txtNickName = formUser.BasicForm.FieldEditingControls["UserNickName"] as EditingFormControl; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } EditingFormControl txtEmail = formUser.BasicForm.FieldEditingControls["Email"] as EditingFormControl; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.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(this.AssignToSites)) ? CMSContext.CurrentSiteName : this.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 = this.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)) { string fullName = ""; if (ui.FirstName.Trim() != "") { fullName += ui.FirstName; } if (ui.MiddleName.Trim() != "") { fullName += " " + ui.MiddleName; } if (ui.LastName.Trim() != "") { fullName += " " + ui.LastName; } ui.FullName = fullName; } // 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(this.StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.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); #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] = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.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 ContextResolver resolver = CMSContext.CurrentResolver; 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 (this.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 && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.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 = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; // Enable macro encoding for body resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, this.FromAddress); message.Recipients = this.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 (this.TrackConversionName != String.Empty) { string siteName = CMSContext.CurrentSiteName; if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.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) { string siteName = CMSContext.CurrentSiteName; if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { int contactId = 0; // Log registration activity if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } // Log login activity if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName)) { if (contactId <= 0) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } ActivityLogHelper.UpdateContactLastLogon(contactId); // Update last logon time if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } } } #endregion #region "Site and roles addition and authentication" string[] roleList = this.AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(this.AssignToSites)) { siteList = this.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.StartsWith(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, sn)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn); } } } } if (this.DisplayMessage.Trim() != String.Empty) { pnlRegForm.Visible = false; lblInfo.Visible = true; lblInfo.Text = this.DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } string returnUrl = QueryHelper.GetString("ReturnURL", ""); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWith("~") || returnUrl.StartsWith("/") || QueryHelper.ValidateHash("hash"))) { URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl)); } else if (this.RedirectToURL != String.Empty) { URLHelper.Redirect(this.RedirectToURL); } } #endregion lblError.Visible = false; } }