Example #1
0
        public override async Task Invoke(IOwinContext context)
        {
            context.Request.CallCancelled.ThrowIfCancellationRequested();

            try
            {
                await Next.Invoke(context);

                if (context.Request.User.Identity.IsAuthenticated)
                {
                    string path = context.Request.Path.Value;

                    if (_options.ShouldExecuteForPathDeterminer(path))
                    {
                        CookieOptions CreateCookieOptions() => new CookieOptions
                        {
                            Domain   = _options.CookieDomain, // Needs to be the same value as the Auth cookie
                            Expires  = DateTime.UtcNow.Add(_options.CookieExpiration),
                            HttpOnly = true,
                            Secure   = _options.CookieSecure
                        };

                        // Check if the user is signing-in as part of this request
                        var claimsIdentity = (ClaimsIdentity)context.Request.User.Identity;

                        Claim claim = claimsIdentity.FindFirst(_options.IsSigningInClaimType);

                        if (claim != null && claim.ValueType == ClaimValueTypes.Boolean && bool.TryParse(claim.Value, out bool isSigningIn) && isSigningIn)
                        {
                            // Merge the marketing contact
                            _kenticoContactManager.Value.ContingentMerge(context, _options.KenticoSiteName, true, CreateCookieOptions);

                            if (_options.LogLoginActivity)
                            {
                                // Now that the contact data has been merged correctly, we can log an activity against the user
                                string kenticoUserName = _kenticoUserNameNormalizer.Normalize(context.Request.User.Identity.Name);
                                _membershipActivitiesLogger.LogLogin(kenticoUserName);
                            }

                            // Remove the claim now we no longer need it
                            claimsIdentity.RemoveClaim(claim);

                            // Calling SignIn to issue a new Auth cookie with updated claims
                            context.Authentication.SignIn(claimsIdentity);
                        }
                        else
                        {
                            // Merge the marketing contact
                            _kenticoContactManager.Value.ContingentMerge(context, _options.KenticoSiteName, false, CreateCookieOptions);
                        }
                    }
                }
            }
            catch (Exception exc) when(_log.WriteError(exc, new { Path = context.Request.Path.Value }))
            {
                throw;
            }
        }
Example #2
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var signInResult = SignInResult.Failed;

            try
            {
                signInResult = await signInManager.PasswordSignInAsync(model.UserName, model.Password, model.StaySignedIn, false);
            }
            catch (Exception ex)
            {
                eventLogService.LogException("AccountController", "Login", ex);
            }

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

                membershipActivitiesLogger.LogLogin(model.UserName);

                var decodedReturnUrl = WebUtility.UrlDecode(returnUrl);
                if (!string.IsNullOrEmpty(decodedReturnUrl) && Url.IsLocalUrl(decodedReturnUrl))
                {
                    return(View("RedirectAfterLogin", decodedReturnUrl));
                }

                return(Redirect("/"));
            }

            if (signInResult.IsNotAllowed)
            {
                ModelState.AddModelError(string.Empty, localizer["Your account requires activation before logging in."]);
            }
            else
            {
                ModelState.AddModelError(string.Empty, localizer["Your sign-in attempt was not successful. Please try again."].ToString());
            }

            return(View(model));
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var signInResult = SignInStatus.Failure;

            try
            {
                signInResult = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.StaySignedIn, false);
            }
            catch (Exception ex)
            {
                Service.Resolve <IEventLogService>().LogException("AccountController", "Login", ex);
            }

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

                membershipActivitiesLogger.LogLogin(model.UserName);

                var decodedReturnUrl = Server.UrlDecode(returnUrl);
                if (!string.IsNullOrEmpty(decodedReturnUrl) && Url.IsLocalUrl(decodedReturnUrl))
                {
                    return(Redirect(decodedReturnUrl));
                }

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

            if (signInResult == SignInStatus.LockedOut)
            {
                ModelState.AddModelError(String.Empty, ResHelper.GetString("DancingGoatMvc.RequireConfirmedAccount"));
            }
            else
            {
                ModelState.AddModelError(String.Empty, ResHelper.GetString("login_failuretext"));
            }

            return(View(model));
        }
Example #4
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);
        }
    }
Example #6
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var signInResult = SignInStatus.Failure;

            try
            {
                signInResult = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.StaySignedIn, false);
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("AccountController", "Login", ex);
            }

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

                mMembershipActivitiesLogger.LogLogin(model.UserName);

                var decodedReturnUrl = Server.UrlDecode(returnUrl);
                if (!string.IsNullOrEmpty(decodedReturnUrl) && Url.IsLocalUrl(decodedReturnUrl))
                {
                    return(Redirect(decodedReturnUrl));
                }

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

            ModelState.AddModelError(String.Empty, ResHelper.GetString("login_failuretext"));

            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;
        }
    }