Exemplo n.º 1
0
        private void DummyLogActivityMethod()
        {
            //DocSection:LogRegisterActivity
            membershipActivityLogger.LogRegistration(userName);
            //EndDocSection:LogRegisterActivity

            //DocSection:LogSignInActivity
            membershipActivityLogger.LogLogin(userName);
            //EndDocSection:LogSignInActivity
        }
    /// <summary>
    /// Logs online marketing activities.
    /// </summary>
    private void LogOMActivity(UserInfo ui)
    {
        IMembershipActivityLogger logger = Service.Resolve <IMembershipActivityLogger>();

        logger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

        // Log login activity
        if (ui.Enabled)
        {
            // Log activity
            logger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
        }
    }
Exemplo n.º 3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = new User
            {
                UserName  = model.UserName,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Email     = model.UserName,
                Enabled   = true
            };

            var registerResult = new IdentityResult();

            try
            {
                registerResult = await UserManager.CreateAsync(user, model.Password);
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("AccountController", "Register", ex);
                ModelState.AddModelError(String.Empty, ResHelper.GetString("register_failuretext"));
            }

            if (registerResult.Succeeded)
            {
                mMembershipActivitiesLogger.LogRegistration(model.UserName);
                await SignInManager.SignInAsync(user, true, false);

                ContactManagementContext.UpdateUserLoginContact(model.UserName);

                mMembershipActivitiesLogger.LogLogin(model.UserName);

                return(RedirectToAction("Index", "Home"));
            }

            foreach (var error in registerResult.Errors)
            {
                ModelState.AddModelError(String.Empty, error);
            }

            return(View(model));
        }
Exemplo n.º 4
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = new ApplicationUser
            {
                UserName  = model.UserName,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Email     = model.UserName,
                FullName  = UserInfoProvider.GetFullName(model.FirstName, null, model.LastName),
                Enabled   = true
            };

            var registerResult = new IdentityResult();

            try
            {
                registerResult = await userManager.CreateAsync(user, model.Password);
            }
            catch (Exception ex)
            {
                eventLogService.LogException("AccountController", "Register", ex);
                ModelState.AddModelError(string.Empty, localizer["Your registration was not successful."]);
            }

            if (registerResult.Succeeded)
            {
                membershipActivitiesLogger.LogRegistration(model.UserName);

                var signInResult = await signInManager.PasswordSignInAsync(user, model.Password, true, false);

                if (signInResult.Succeeded)
                {
                    ContactManagementContext.UpdateUserLoginContact(model.UserName);

                    SendRegistrationSuccessfulEmail(user.Email);
                    membershipActivitiesLogger.LogLogin(model.UserName);

                    return(Redirect("/"));
                }

                if (signInResult.IsNotAllowed)
                {
                    if (user.WaitingForApproval)
                    {
                        SendWaitForApprovalEmail(user.Email);
                    }

                    return(RedirectToAction(nameof(RequireConfirmedAccount)));
                }
            }

            foreach (var error in registerResult.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return(View(model));
        }
    /// <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))
            {
                ShowError(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 another user with this user name (which is effectively 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))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)));
                return;
            }

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

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength));
                return;
            }

            if (!passStrength.IsValid())
            {
                ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                return;
            }

            if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH));
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError"));
                return;
            }

            #endregion


            #region "User properties"

            var userEmail = txtEmail.Text.Trim();

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = userEmail;
            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)
            var plainUserName = userEmail;
            ui.UserName = plainUserName;

            // Check if the given email can be used as user name
            if (!ValidationHelper.IsUserName(plainUserName))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName)));
                return;
            }

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

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
            ui.UserCampaign    = Service.Resolve <ICampaignService>().CampaignCode;

            ui.SiteIndependentPrivilegeLevel = 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 required
                requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval");
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overridden 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))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName))
            {
                ShowError(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))
            {
                ShowError(errorMessage);
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0))
            {
                ShowError(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)
                // New contact with user data is created in case it is not disabled by Data protection settings, otherwise an anonymous contact is created. Moreover an another
                // anonymous contact could be created during approval process when a new browser is used for approval step (when contact isn't in browser cookies).
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    Service.Resolve <IContactRelationAssigner>().Assign(ui.UserID, MembershipType.CMS_USER, contactId, new UserContactDataPropagationChecker());
                }

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;
                email.From        = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress");
                email.Subject     = emailSubject;

                try
                {
                    var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator));
                    EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                ShowError(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;
                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;
                    message.Subject     = GetString("RegistrationForm.EmailSubject");

                    try
                    {
                        MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui);
                        EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && Service.Resolve <IAnalyticsConsentProvider>().HasConsentForLogging() &&
                    !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress) &&
                    SystemContext.IsCMSRunningAsMainApplication)
                {
                    // 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)
            {
                IMembershipActivityLogger logger = Service.Resolve <IMembershipActivityLogger>();
                logger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                // Log login activity
                if (ui.Enabled)
                {
                    logger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                }
            }

            #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.StartsWith(".", StringComparison.Ordinal) ? "" : 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(UrlResolver.ResolveUrl(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("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath"))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(url));
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext"));
                    }
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = new User
            {
                UserName  = model.UserName,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Email     = model.UserName,
                FullName  = UserInfoProvider.GetFullName(model.FirstName, null, model.LastName),
                Enabled   = true
            };

            var registerResult = new IdentityResult();

            try
            {
                registerResult = await UserManager.CreateAsync(user, model.Password);
            }
            catch (Exception ex)
            {
                Service.Resolve <IEventLogService>().LogException("AccountController", "Register", ex);
                ModelState.AddModelError(String.Empty, ResHelper.GetString("register_failuretext"));
            }

            if (registerResult.Succeeded)
            {
                membershipActivitiesLogger.LogRegistration(model.UserName);
                var signInResult = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, true, false);

                if (signInResult == SignInStatus.Success)
                {
                    ContactManagementContext.UpdateUserLoginContact(model.UserName);

                    SendRegistrationSuccessfulEmail(user.Email);
                    membershipActivitiesLogger.LogLogin(model.UserName);

                    return(Redirect(Url.Kentico().PageUrl(ContentItemIdentifiers.HOME)));
                }

                if (signInResult == SignInStatus.LockedOut)
                {
                    if (user.WaitingForApproval)
                    {
                        SendWaitForApprovalEmail(user.Email);
                    }

                    return(RedirectToAction("RequireConfirmedAccount"));
                }
            }

            foreach (var error in registerResult.Errors)
            {
                ModelState.AddModelError(String.Empty, error);
            }

            return(View(model));
        }