示例#1
0
    /// <summary>
    /// Registers new user.
    /// </summary>
    /// <param name="facebookUserId">The user's Facebook ID</param>
    /// <param name="facebookAccessToken">The user's access token retrieved from Facebook</param>
    private void RegisterNewUser(string facebookUserId, string facebookAccessToken)
    {
        // Check whether additional user info page is set
        string currentSiteName = SiteContext.CurrentSiteName;

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

        // If user was found or successfully created
        if (ui != null)
        {
            MapFacebookUserProfile(FacebookUserProfileMappingTriggerEnum.Registration, ui, facebookUserId, facebookAccessToken);

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

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

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

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

        lblError.Text    = error;
        lblError.Visible = true;
    }
示例#2
0
    /// <summary>
    /// Helper method, sets authentication cookie and redirects to return URL or default page.
    /// </summary>
    /// <param name="ui">User info</param>
    private void SetAuthCookieAndRedirect(UserInfo ui)
    {
        // Create autentification cookie
        if (ui.Enabled)
        {
            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "linkedinlogin" });

            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

            string returnUrl = QueryHelper.GetString("returnurl", null);

            // Redirect to ReturnURL
            if (URLHelper.IsLocalUrl(returnUrl))
            {
                URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl));
            }
            // Redirect to default page
            else if (!String.IsNullOrEmpty(DefaultTargetUrl))
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(ResolveUrl(DefaultTargetUrl)));
            }
            // Otherwise refresh current page
            else
            {
                URLHelper.Redirect(RequestContext.CurrentURL);
            }
        }
    }
    /// <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)
        {
            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "liveidlogin" });

            // Log activity
            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

            // Redirect to default page
            if (!String.IsNullOrEmpty(DefaultTargetUrl))
            {
                URLHelper.Redirect(ResolveUrl(DefaultTargetUrl));
            }
            // If there is some return page redirect there
            else if ((liveUser != null) && !string.IsNullOrEmpty(liveUser.Context))
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(liveUser.Context));
            }
            // Refresh current page to update see user signed in
            else
            {
                string url = RequestContext.CurrentURL;
                URLHelper.Redirect(url);
            }
        }
    }
示例#4
0
    /// <summary>
    /// Logs online marketing activities.
    /// </summary>
    private void LogOMActivity(UserInfo ui)
    {
        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

        // Log login activity
        if (ui.Enabled)
        {
            // Log activity
            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
        }
    }
示例#5
0
    /// <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 authentication cookie
        AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, false, Session.Timeout, new[] { "liveidlogin" });

        MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

        // 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);
            }
        }
    }
示例#6
0
    /// <summary>
    /// Signs in given user.
    /// </summary>
    /// <param name="ui">User that will be signed in.</param>
    /// <param name="facebookUserId">The user's Facebook ID</param>
    /// <param name="facebookAccessToken">The user's access token retrieved from Facebook</param>
    /// <param name="mapFacebookProfile">Indicates whether the user's Facebook profile is mapped to user info or not</param>
    private void SignInUser(UserInfo ui, string facebookUserId, string facebookAccessToken, bool mapFacebookProfile = true)
    {
        // Login existing user
        if (ui.Enabled)
        {
            if (mapFacebookProfile)
            {
                MapFacebookUserProfile(FacebookUserProfileMappingTriggerEnum.Login, ui, facebookUserId, facebookAccessToken);
            }

            // Ban IP addresses which are blocked for login
            BannedIPInfoProvider.CheckIPandRedirect(SiteContext.CurrentSiteName, BanControlEnum.Login);

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

            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

            // Redirect user
            string returnUrl = QueryHelper.GetString("returnurl", null);
            if (URLHelper.IsLocalUrl(returnUrl))
            {
                URLHelper.Redirect(returnUrl);
            }
            else
            {
                string currentUrl = URLHelper.RemoveParameterFromUrl(RequestContext.CurrentURL, CONFIRMATION_URLPARAMETER);
                URLHelper.Redirect(ResolveUrl(currentUrl));
            }
        }
        else
        {
            // User is disabled
            lblError.Text    = GetString("membership.userdisabled");
            lblError.Visible = true;
        }
    }
        public LoginResult Login(LoginRequest loginRequest)
        {
            CookieHelper.EnsureResponseCookie(FormsAuthentication.FormsCookieName);
            if (loginRequest.KeepLoggedIn)
            {
                CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddYears(1), false);
            }
            else
            {
                // Extend the expiration of the authentication cookie if required
                if (!AuthenticationHelper.UseSessionCookies && (HttpContext.Current != null) && (HttpContext.Current.Session != null))
                {
                    CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout), false);
                }
            }

            var user = AuthenticationHelper.AuthenticateUser(loginRequest.LoginEmail, loginRequest.Password, SiteContext.CurrentSiteName);

            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(user.UserName, loginRequest.KeepLoggedIn);
                MembershipActivityLogger.LogLogin(user.UserName);
                return(new LoginResult
                {
                    LogonSuccess = true
                });
            }
            else
            {
                return(new LoginResult
                {
                    LogonSuccess = false,
                    ErrorPropertyName = "loginEmail",
                    ErrorMessage = ResHelper.GetString("Kadena.Logon.LogonFailed", LocalizationContext.CurrentCulture.CultureCode)
                });
            }
        }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = SiteContext.CurrentSiteName;

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

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

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

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

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

                // Log "login" activity
                MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

                LoadStep(true);

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

                string[] siteList = { siteName };

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

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

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

                // Create new customer and user account and sign in
                // User
                ui           = new UserInfo();
                ui.UserName  = txtEmail2.Text.Trim();
                ui.Email     = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName  = txtLastName1.Text.Trim();
                ui.FullName  = ui.FirstName + " " + ui.LastName;
                ui.Enabled   = true;
                ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;
                ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
                ui.UserCampaign    = Service <ICampaignService> .Entry().CampaignCode;

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

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

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

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

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

                    MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text    = ex.Message;
                    return(false);
                }

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

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

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

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

                CreateContactRelation(ci);

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

                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                }

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

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

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

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

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

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

                CreateContactRelation(ci);

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

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

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

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

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

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

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

            if (newCustomer)
            {
                CreateContactRelation(ci);
            }

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

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

            ShoppingCart.InvalidateCalculations();
            return(true);
        }
        catch
        {
            return(false);
        }
    }
示例#9
0
    /// <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 <ICampaignService> .Entry().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)
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId);
                }

                // 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) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

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

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                // Log login activity
                if (ui.Enabled)
                {
                    MembershipActivityLogger.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;
        }
    }
示例#10
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(mLinkedInProfile?.Id))
        {
            string currentSiteName = SiteContext.CurrentSiteName;

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

            string password = passStrength.Text;

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

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

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

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

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

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

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

                        var birthDate = mLinkedInProfile.BirthDate?.ToDateTime();

                        if (birthDate.HasValue && birthDate.Value != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = birthDate.Value;
                        }

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

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

                        UserInfoProvider.SetUserInfo(ui);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            string error = String.Empty;

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

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

                    // If user was found or successfully created
                    if ((ui != null) && (ui.Enabled))
                    {
                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

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

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

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

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

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
示例#12
0
 /// <summary>
 /// Log user activity.
 /// </summary>
 private void LogActivity()
 {
     // Create new activity for registered user
     MembershipActivityLogger.LogRegistration(RegisteredUser.UserName, DocumentContext.CurrentDocument, false);
 }
示例#13
0
    /// <summary>
    /// Logged in handler.
    /// </summary>
    private void Login1_LoggedIn(object sender, EventArgs e)
    {
        // Set view mode to live site after login to prevent bar with "Close preview mode"
        PortalContext.ViewMode = ViewModeEnum.LiveSite;

        // Ensure response cookie
        CookieHelper.EnsureResponseCookie(FormsAuthentication.FormsCookieName);

        // Set cookie expiration
        if (Login1.RememberMeSet)
        {
            CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddYears(1), false);
        }
        else
        {
            // Extend the expiration of the authentication cookie if required
            if (!AuthenticationHelper.UseSessionCookies && (HttpContext.Current != null) && (HttpContext.Current.Session != null))
            {
                CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddMinutes(Session.Timeout), false);
            }
        }

        // Current username
        string userName = Login1.UserName;

        // Get user name (test site prefix too)
        UserInfo ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, SiteContext.CurrentSite);

        // Check whether safe user name is required and if so get safe username
        if (RequestHelper.IsMixedAuthentication() && UserInfoProvider.UseSafeUserName)
        {
            // Get info on the authenticated user
            if (ui == null)
            {
                // User stored with safe name
                userName = ValidationHelper.GetSafeUserName(Login1.UserName, SiteContext.CurrentSiteName);

                // Find user by safe name
                ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, SiteContext.CurrentSite);
                if (ui != null)
                {
                    // Authenticate user by site or global safe username
                    AuthenticationHelper.AuthenticateUser(ui.UserName, Login1.RememberMeSet);
                }
            }
        }

        if (ui != null)
        {
            // If user name is site prefixed, authenticate user manually
            if (UserInfoProvider.IsSitePrefixedUser(ui.UserName))
            {
                AuthenticationHelper.AuthenticateUser(ui.UserName, Login1.RememberMeSet);
            }

            // Log activity
            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
        }

        // Redirect user to the return URL, or if is not defined redirect to the default target URL
        var    redirectUrl = RequestContext.CurrentURL;
        string url         = QueryHelper.GetString("ReturnURL", String.Empty);

        if (!String.IsNullOrEmpty(url) && URLHelper.IsLocalUrl(url))
        {
            redirectUrl = url;
        }
        else if (!String.IsNullOrEmpty(DefaultTargetUrl))
        {
            redirectUrl = ResolveUrl(DefaultTargetUrl);
        }

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

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

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

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

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

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

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

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

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

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

                        // Set user
                        UserInfoProvider.SetUserInfo(ui);

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

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

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

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

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

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

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

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

        returnUrl = HttpUtility.UrlDecode(returnUrl);

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

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

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

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

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

                        UserInfoProvider.SetUserInfo(ui);

                        // If user is enabled
                        if (ui.Enabled)
                        {
                            // Create autentification cookie
                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "openidlogin" });
                            // Log activity
                            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                        }

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

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

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                    }

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

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

                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        // Add return URL to parameter
                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                    }

                    URLHelper.Redirect(UrlResolver.ResolveUrl(targetURL));
                }
            }
            // Claimed OpenID is in DB
            else
            {
                // Login existing user
                UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

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

                    // Log activity
                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

                    // Redirect user
                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(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>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error    = null;

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

        returnUrl = HttpUtility.UrlDecode(returnUrl);

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

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

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

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

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

                        UserInfoProvider.SetUserInfo(ui);

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

                            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                        }

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

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

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                    }

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

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

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

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

                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

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

        // No authentication, do nothing
        case LinkedInHelper.RESPONSE_NOTAUTHENTICATED:
            break;
        }
    }
        protected async void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ClientCredential credential = new ClientCredential(Constants.AzureActiveDirectory.ClientId,
                                                                   Constants.AzureActiveDirectory.AppKey);


                var authContext =
                    new AuthenticationContext(string.Format(Constants.AzureActiveDirectory.Authority,
                                                            Constants.AzureActiveDirectory.TenantId));
                var code = ValidationHelper.GetString(HttpContext.Current.Request.QueryString["code"], string.Empty);
                AuthenticationResult result =
                    await
                    authContext.AcquireTokenByAuthorizationCodeAsync(code,
                                                                     new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential,
                                                                     string.Format(Constants.AzureActiveDirectory.GraphResourceUri, ""));

                var adClient = new ActiveDirectoryClient(
                    new Uri(string.Format(Constants.AzureActiveDirectory.GraphResourceUri, result.TenantId)),
                    async() => await GetAppTokenAsync(result.TenantId));
                var adUser =
                    (User)
                    await
                    adClient.Users.Where(x => x.UserPrincipalName.Equals(result.UserInfo.DisplayableId))
                    .Expand(x => x.MemberOf)
                    .ExecuteSingleAsync();

                var user =
                    UserInfoProvider.GetUsers()
                    .Where("AzureADUsername", QueryOperator.Equals, adUser.UserPrincipalName)
                    .FirstOrDefault();
                var groupsToAdd = adUser.MemberOf.OfType <Group>()
                                  .Select(x => x.DisplayName)
                                  .Where(x => Constants.AzureActiveDirectory.GroupsToSync.Contains(x));
                var groupsToRemove = Constants.AzureActiveDirectory.GroupsToSync
                                     .Where(x => !groupsToAdd.Contains(x));
                if (user == null)
                {
                    user           = new CMS.Membership.UserInfo();
                    user.UserName  = adUser.UserPrincipalName;
                    user.FirstName = adUser.GivenName;
                    user.LastName  = adUser.Surname;
                    user.FullName  = adUser.DisplayName;
                    user.Email     = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault());
                    user.SetValue("AzureADUsername", adUser.UserPrincipalName);
                    user.IsExternal = true;
                    user.Enabled    = true;
                    UserInfoProvider.SetUserInfo(user);
                    UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName);

                    foreach (var group in groupsToAdd)
                    {
                        UserInfoProvider.AddUserToRole(user.UserName,
                                                       RoleInfoProvider.GetRoles()
                                                       .OnSite(SiteContext.CurrentSiteID)
                                                       .Where("RoleDisplayName", QueryOperator.Equals, group)
                                                       .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName);
                    }
                }
                else
                {
                    user.FirstName  = adUser.GivenName;
                    user.LastName   = adUser.Surname;
                    user.FullName   = adUser.DisplayName;
                    user.Email      = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault());
                    user.IsExternal = true;
                    UserInfoProvider.SetUserInfo(user);
                    UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName);
                    foreach (var group in groupsToAdd)
                    {
                        UserInfoProvider.AddUserToRole(user.UserName,
                                                       RoleInfoProvider.GetRoles()
                                                       .OnSite(SiteContext.CurrentSiteID)
                                                       .Where("RoleDisplayName", QueryOperator.Equals, group)
                                                       .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName);
                    }

                    foreach (var group in groupsToRemove)
                    {
                        UserInfoProvider.RemoveUserFromRole(user.UserName,
                                                            RoleInfoProvider.GetRoles()
                                                            .OnSite(SiteContext.CurrentSiteID)
                                                            .Where("RoleDisplayName", QueryOperator.Equals, group)
                                                            .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName);
                    }
                }

                AuthenticationHelper.AuthenticateUser(user.UserName, false);
                MembershipActivityLogger.LogLogin(user.UserName, DocumentContext.CurrentDocument);
            }
            catch (Exception exception)
            {
                EventLogProvider.LogException("AzureActiveDirectory", "Login", exception);
            }

            var postLoginPage = DocumentHelper.GetDocuments()
                                .WhereEquals("NodeAliasPath", Constants.AzureActiveDirectory.PostLoginPage)
                                .FirstOrDefault(x => x.DocumentCulture.Equals(LocalizationContext.CurrentCulture.CultureCode,
                                                                              StringComparison.InvariantCultureIgnoreCase));
            var returnUrl = HttpContext.Current.Request.GetReturnUrl(postLoginPage.GetRelativeUrl());

            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
        }
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            try
            {
                ClientCredential credential = new ClientCredential(Constants.AzureActiveDirectory.ClientId,
                                                                   Constants.AzureActiveDirectory.ApplicationKey);


                var authContext =
                    new AuthenticationContext(string.Format(Constants.AzureActiveDirectory.AuthorityUrl,
                                                            Constants.AzureActiveDirectory.TenantId));
                var code = ValidationHelper.GetString(HttpContext.Current.Request.QueryString["code"], string.Empty);
                AuthenticationResult result =
                    await
                    authContext.AcquireTokenByAuthorizationCodeAsync(code,
                                                                     new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential,
                                                                     string.Format(Constants.AzureActiveDirectory.GraphUrl, ""));

                var adClient = new ActiveDirectoryClient(
                    new Uri(string.Format(Constants.AzureActiveDirectory.GraphUrl, result.TenantId)),
                    async() => await GetAppTokenAsync(result.TenantId));

                var adUser =
                    (User)
                    await
                    adClient.Users.Where(x => x.UserPrincipalName.Equals(result.UserInfo.DisplayableId))
                    .Expand(x => x.MemberOf)
                    .ExecuteSingleAsync();

                var user =
                    UserInfoProvider.GetUsers()
                    .Where("AzureADUsername", QueryOperator.Equals, adUser.UserPrincipalName)
                    .FirstOrDefault();
                var groupsToAdd = adUser.MemberOf.OfType <Group>()
                                  .Select(x => x.DisplayName)
                                  .Where(x => Constants.AzureActiveDirectory.GroupsToSync.Contains(x));
                var groupsToRemove = Constants.AzureActiveDirectory.GroupsToSync
                                     .Where(x => !groupsToAdd.Contains(x));

                // check if any of the Azure Active Directory groups are matching by name any Kentico roles
                // if not save an error message in ErrorLog and return
                bool isGroupMatchRole = false;
                foreach (var group in groupsToAdd)
                {
                    var roleInfo = RoleInfoProvider.GetRoles()
                                   .OnSite(SiteContext.CurrentSiteID)
                                   .Where("RoleDisplayName", QueryOperator.Equals, group).ToList <RoleInfo>();
                    if (roleInfo.Count > 0)
                    {
                        isGroupMatchRole = true;
                        break;
                    }
                }

                if (!isGroupMatchRole)
                {
                    var logerr = $"Attempted login on {DateTime.Now} by user {adUser.UserPrincipalName},[{adUser.DisplayName}] memberOf {groupsToAdd.ToList<string>().Join(",")}";

                    EventLogProvider.LogEvent(EventType.ERROR,
                                              "Login user through Azure Active Directory",
                                              "AZUREADLOGINFAILURE",
                                              eventDescription: logerr);
                    var returnUrlWithError = ValidationHelper.GetString(this.Context.Request.Params["state"], string.Empty);
                    URLHelper.Redirect(URLHelper.GetAbsoluteUrl($"{returnUrlWithError}?logonresult=Failed&firstname={adUser.DisplayName}&lastname={string.Empty}&lastlogoninfo={logerr}"));
                    return;
                }

                if (user == null)
                {
                    user           = new CMS.Membership.UserInfo();
                    user.UserName  = adUser.UserPrincipalName;
                    user.FirstName = adUser.GivenName;
                    user.LastName  = adUser.Surname;
                    user.FullName  = adUser.DisplayName;
                    user.Email     = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault());
                    user.SetValue("AzureADUsername", adUser.UserPrincipalName);
                    user.IsExternal = true;

                    //None		    0	User has no privilege level
                    //Editor		1	User is able to use administration interface
                    //Admin		    2	User can use all applications except the global applications and functionality
                    //GlobalAdmin	3	User can use all applications and functionality without any exceptions
                    user.SiteIndependentPrivilegeLevel = CMS.Base.UserPrivilegeLevelEnum.Editor;

                    user.Enabled = true;
                    UserInfoProvider.SetUserInfo(user);
                    UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName);

                    foreach (var group in groupsToAdd)
                    {
                        UserInfoProvider.AddUserToRole(user.UserName,
                                                       RoleInfoProvider.GetRoles()
                                                       .OnSite(SiteContext.CurrentSiteID)
                                                       .Where("RoleDisplayName", QueryOperator.Equals, group)
                                                       .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName);
                    }
                }
                else
                {
                    user.FirstName  = adUser.GivenName;
                    user.LastName   = adUser.Surname;
                    user.FullName   = adUser.DisplayName;
                    user.Email      = adUser.Mail.IfEmpty(adUser.OtherMails.FirstOrDefault());
                    user.IsExternal = true;
                    UserInfoProvider.SetUserInfo(user);
                    UserInfoProvider.AddUserToSite(user.UserName, SiteContext.CurrentSiteName);
                    foreach (var group in groupsToAdd)
                    {
                        UserInfoProvider.AddUserToRole(user.UserName,
                                                       RoleInfoProvider.GetRoles()
                                                       .OnSite(SiteContext.CurrentSiteID)
                                                       .Where("RoleDisplayName", QueryOperator.Equals, group)
                                                       .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName);
                    }

                    foreach (var group in groupsToRemove)
                    {
                        UserInfoProvider.RemoveUserFromRole(user.UserName,
                                                            RoleInfoProvider.GetRoles()
                                                            .OnSite(SiteContext.CurrentSiteID)
                                                            .Where("RoleDisplayName", QueryOperator.Equals, group)
                                                            .FirstOrDefault()?.RoleName ?? "", SiteContext.CurrentSiteName);
                    }
                }

                AuthenticationHelper.AuthenticateUser(user.UserName, false);
                MembershipActivityLogger.LogLogin(user.UserName, DocumentContext.CurrentDocument);

                var returnUrl = ValidationHelper.GetString(context.Request.Params["state"], string.Empty);
                URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
            }
            catch (Exception exception)
            {
                EventLogProvider.LogException("AzureActiveDirectory", "Login", exception);
            }
        }
示例#19
0
 /// <summary>
 /// Logs login activity for given user.
 /// </summary>
 /// <remarks>
 /// This method should be called whenever the user is authenticated to ensure logging of correct <see cref="ActivityInfo"/>.
 /// </remarks>
 /// <param name="userName">User name of the authenticated user</param>
 public void LogLoginActivity(string userName)
 {
     MembershipActivityLogger.LogLogin(userName);
 }
示例#20
0
 /// <summary>
 /// Logs user registration activity for given user.
 /// </summary>
 /// <remarks>
 /// This method should be called whenever the user is registered to ensure logging of correct <see cref="ActivityInfo"/>.
 /// </remarks>
 /// <param name="userName">User name of the registered user</param>
 public void LogRegisterActivity(string userName)
 {
     MembershipActivityLogger.LogRegistration(userName);
 }