Beispiel #1
0
        public static void SetCurrentSkinBaseUrl(SiteSettings siteSettings)
        {
            if (siteSettings == null)
            {
                return;
            }

            string currentSkin = siteSettings.Skin + "/";

            if (siteSettings.AllowUserSkins)
            {
                string skinCookieName = "CUserSkin" + siteSettings.SiteId.ToString();

                if (CookieHelper.CookieExists(skinCookieName))
                {
                    string cookieValue = CookieHelper.GetCookieValue(skinCookieName);
                    if (cookieValue.Length > 0)
                    {
                        currentSkin = cookieValue + "/";
                    }
                }
            }

            string skinFolder = WebUtils.GetSiteRoot() + "/Data/Sites/"
                                + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture) + "/skins/";

            siteSettings.SkinBaseUrl = skinFolder + currentSkin;
        }
Beispiel #2
0
 private void ProcessSkinCookie()
 {
     //toggle
     if (SiteUtils.IsMobileDevice())
     {
         if (CookieHelper.CookieExists(SiteUtils.MobileUseFullViewCookieName))
         {
             CookieHelper.ExpireCookie(SiteUtils.MobileUseFullViewCookieName);
         }
         else
         {
             CookieHelper.SetCookie(SiteUtils.MobileUseFullViewCookieName, "y");
         }
     }
     else
     {
         if (CookieHelper.CookieExists(SiteUtils.NonMobileUseMobileViewCookieName))
         {
             CookieHelper.ExpireCookie(SiteUtils.NonMobileUseMobileViewCookieName);
         }
         else
         {
             CookieHelper.SetCookie(SiteUtils.NonMobileUseMobileViewCookieName, "y");
         }
     }
 }
Beispiel #3
0
        public PartialViewResult RemoveIngredient(Guid id)
        {
            HttpCookie cookie;
            ICollection <IngredientCreateViewModel> ingredients;

            if (CookieHelper.CookieExists(currentRecipeCookie, out cookie))
            {
                ingredients = CookieHelper.ReadCookie <ICollection <IngredientCreateViewModel> >(cookie, createdRecipeIngredients);

                if (ingredients == null)
                {
                    CookieHelper.DeleteCookie(currentRecipeCookie);
                }
                else
                {
                    IngredientCreateViewModel ingredient = ingredients.First(i => i.ProductId == id);
                    if (ingredient != null)
                    {
                        ingredients.Remove(ingredient);
                        CookieHelper.UpdateCookie <ICollection <IngredientCreateViewModel> >(cookie, createdRecipeIngredients, ingredients);
                    }
                }
            }
            else
            {
                ingredients = new List <IngredientCreateViewModel>();
            }

            return(PartialView("_CreatedRecipeIngredients", ingredients));
        }
Beispiel #4
0
        private void ShowResult()
        {
            //LoadPoll();
            poll = new Poll(ModuleId);

            if (currentUser != null)
            {
                userHasVoted = poll.UserHasVoted(currentUser);
            }
            else
            {
                userHasVoted = CookieHelper.CookieExists(poll.PollGuid.ToString());
            }

            if (userHasVoted)
            {
                lblVotingStatus.Text = PollResources.AlreadyVotedMessage;
            }

            rblOptions.Visible     = false;
            dlResults.Visible      = true;
            btnBackToVote.Visible  = !userHasVoted;
            btnShowResults.Visible = false;

            lblMessage.Text = PollResources.PollTotalVotesLabel + poll.TotalVotes;
            //IDataReader reader = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            List <PollOption> pollOptions = PollOption.GetOptionsByPollGuid(poll.PollGuid);

            dlResults.DataSource = pollOptions;
            dlResults.DataBind();
            //reader.Close();

            //rptResults.DataSource = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            //rptResults.DataBind();
        }
        private String GetUserPagePath(String path)
        {
            String result = path;

            if (CookieHelper.CookieExists(userPageCookie))
            {
                result = CookieHelper.GetCookieValue(userPageCookie);
            }


            return(result);
        }
Beispiel #6
0
        private void PopulateControls()
        {
            lblSkinGuid.Text = siteSettings.SkinVersion.ToString();

            if (CookieHelper.CookieExists(cssCacheCookieName))
            {
                btnCssCacheToggle.Text = DevTools.EnableCssCaching;
            }
            else
            {
                btnCssCacheToggle.Text = DevTools.DisableCssCaching;
            }
        }
Beispiel #7
0
        private void SetupLegacyNewsComments()
        {
            pnlFeedback.Visible       = true;
            fldEnterComments.Visible  = CommentsAreOpen();
            pnlCommentsClosed.Visible = !fldEnterComments.Visible;

            if ((!config.UseCaptcha) || (!fldEnterComments.Visible) || (Request.IsAuthenticated))
            {
                pnlAntiSpam.Visible = false;
                captcha.Visible     = false;
                captcha.Enabled     = false;
            }

            divCommentUrl.Visible = config.AllowWebSiteUrlForComments;

            if ((config.RequireAuthenticationForComments) && (!Request.IsAuthenticated))
            {
                pnlNewComment.Visible = false;
                pnlCommentsRequireAuthentication.Visible = true;
            }

            if (!IsPostBack)
            {
                txtCommentTitle.Text = "re: " + news.Title;

                if (Request.IsAuthenticated)
                {
                    SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
                    this.txtName.Text = currentUser.Name;
                    txtURL.Text       = currentUser.WebSiteUrl;
                }
                else
                {
                    if (CookieHelper.CookieExists("newsUser"))
                    {
                        this.txtName.Text = CookieHelper.GetCookieValue("newsUser");
                    }
                    if (CookieHelper.CookieExists("newsUrl"))
                    {
                        this.txtURL.Text = CookieHelper.GetCookieValue("newsUrl");
                    }
                }
            }

            using (IDataReader dataReader = News.GetNewsComments(news.NewsID))
            {
                dlComments.DataSource = dataReader;
                dlComments.DataBind();
            }
        }
Beispiel #8
0
        private bool HasNoCacheCookie()
        {
            SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();

            if (siteSettings != null)
            {
                string cookieName = SiteUtils.GetCssCacheCookieName(siteSettings);
                if (CookieHelper.CookieExists(cookieName))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #9
0
        public PartialViewResult AddIngredient(Guid id)
        {
            HttpCookie cookie;
            var        product = ProductManager.FindById(id);
            IngredientCreateViewModel ingredient = new IngredientCreateViewModel
            {
                ProductId        = id,
                Quantity         = 0,
                ProductName      = product.Name,
                BaseProtein      = product.Protein,
                BaseCarbohydrate = product.Carbohydrate,
                BaseFat          = product.Fat
            };
            ICollection <IngredientCreateViewModel> ingredients;

            if (CookieHelper.CookieExists(currentRecipeCookie, out cookie))
            {
                ingredients = CookieHelper.ReadCookie <ICollection <IngredientCreateViewModel> >(cookie, createdRecipeIngredients);

                if (ingredients == null)
                {
                    CookieHelper.DeleteCookie(currentRecipeCookie);
                    ingredients = new List <IngredientCreateViewModel> {
                        ingredient
                    };
                    CookieHelper.CreateCookie <ICollection <IngredientCreateViewModel> >(
                        currentRecipeCookie, createdRecipeIngredients, ingredients, new TimeSpan(0, 30, 0));
                }
                else
                {
                    if (!ingredients.Any(i => i.ProductId == id))
                    {
                        ingredients.Add(ingredient);
                        CookieHelper.UpdateCookie <ICollection <IngredientCreateViewModel> >(cookie, createdRecipeIngredients, ingredients);
                    }
                }
            }
            else
            {
                ingredients = new List <IngredientCreateViewModel> {
                    ingredient
                };
                CookieHelper.CreateCookie <ICollection <IngredientCreateViewModel> >(
                    currentRecipeCookie, createdRecipeIngredients, ingredients, new TimeSpan(0, 30, 0));
            }

            return(PartialView("_CreatedRecipeIngredients", ingredients));
        }
Beispiel #10
0
        protected String GetCssClass(String pagePath)
        {
            String userPageCookieValue = String.Empty;

            if (CookieHelper.CookieExists(userPageCookie))
            {
                userPageCookieValue = CookieHelper.GetCookieValue(userPageCookie);
            }

            if (userPageCookieValue == pagePath)
            {
                return("userpagemenu-Selected");
            }

            return("userpagemenu");
        }
Beispiel #11
0
        void btnCssCacheToggle_Click(object sender, EventArgs e)
        {
            if (CookieHelper.CookieExists(cssCacheCookieName))
            {
                HttpCookie cssCookie = new HttpCookie(cssCacheCookieName, string.Empty);
                cssCookie.Expires = DateTime.Now.AddMinutes(-10);
                cssCookie.Path    = "/";
                Response.Cookies.Add(cssCookie);
            }
            else
            {
                CookieHelper.SetPersistentCookie(cssCacheCookieName, "true");
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }
        void btnCreateUser_Click(object sender, EventArgs e)
        {
            Page.Validate("profile");
            if (Page.IsValid)
            {
                //PopulateRequiredProfileControls();
                string openID = CookieHelper.GetSecureCookieValue(openidCookieName);
                string email  = txtEmail.Text;

                if (
                    (CookieHelper.CookieExists(openIdEmailCookieName)) &&
                    (email.Length == 0)
                    )
                {
                    email = CookieHelper.GetSecureCookieValue(openIdEmailCookieName);
                }

                if (openID.Length == 0)
                {
                    return;
                }

                string loginName
                    = openID.Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("/", string.Empty);

                string name = loginName;
                if (CookieHelper.CookieExists(openIdFullNameCookieName))
                {
                    name = CookieHelper.GetSecureCookieValue(openIdFullNameCookieName);
                }

                if (SiteUser.EmailExistsInDB(siteSettings.SiteId, email))
                {
                    lblError.Text = Resource.RegisterDuplicateEmailMessage;
                }
                else
                {
                    CreateUser(openID, email, SecurityHelper.RemoveMarkup(loginName), SecurityHelper.RemoveMarkup(name));
                }
            }
        }
        private string GetRedirectPath()
        {
            string redirectPath = string.Empty;

            if (CookieHelper.CookieExists(returnUrlCookieName))
            {
                redirectPath = CookieHelper.GetCookieValue(returnUrlCookieName);
            }
            if (String.IsNullOrEmpty(redirectPath) ||
                redirectPath.Contains("AccessDenied") ||
                redirectPath.Contains("Login") ||
                redirectPath.Contains("SignIn") ||
                redirectPath.Contains("ConfirmRegistration.aspx") ||
                redirectPath.Contains("Register")
                )
            {
                return(SiteUtils.GetNavigationSiteRoot());
            }

            return(redirectPath);
        }
Beispiel #14
0
 public void UpdateIngredientAlias(Guid productId, string alias)
 {
     if (CookieHelper.CookieExists(currentRecipeCookie))
     {
         ICollection <IngredientCreateViewModel> ingredients;
         if (CookieHelper.TryReadCookie <ICollection <IngredientCreateViewModel> >(
                 currentRecipeCookie, createdRecipeIngredients, out ingredients))
         {
             foreach (var ingr in ingredients)
             {
                 if (ingr.ProductId == productId)
                 {
                     ingr.Alias = alias;
                     break;
                 }
             }
             CookieHelper.UpdateCookie <ICollection <IngredientCreateViewModel> >(
                 currentRecipeCookie, createdRecipeIngredients, ingredients);
         }
     }
 }
Beispiel #15
0
        private bool TryUpdateCreatedQuantity(Guid productId, int quantity, out ICollection <IngredientCreateViewModel> ingredients)
        {
            HttpCookie recipeCookie;

            if (CookieHelper.CookieExists(currentRecipeCookie, out recipeCookie))
            {
                ingredients = CookieHelper.ReadCookie <ICollection <IngredientCreateViewModel> >(
                    recipeCookie, createdRecipeIngredients);
                if (ingredients == null)
                {
                    // Ciasteczko jest uszkodzone.
                    CookieHelper.DeleteCookie(currentRecipeCookie);
                    return(false);
                }
                IngredientCreateViewModel ing = ingredients.First(i => i.ProductId == productId);
                if (ing != null)
                {
                    ing.Quantity = quantity;
                }
                else
                {
                    var product = ProductManager.FindById(productId);
                    if (product != null)
                    {
                        ingredients.Add(new IngredientCreateViewModel {
                            ProductId = productId, ProductName = product.Name, Quantity = quantity
                        });
                    }
                    else
                    {
                        return(false);
                    }
                }
                CookieHelper.UpdateCookie <ICollection <IngredientCreateViewModel> >(recipeCookie, createdRecipeIngredients, ingredients);
                return(true);
            }
            ingredients = null;
            return(false);
        }
        /// <summary>
        /// required implementation
        /// </summary>
        /// <param name="username">a username</param>
        /// <returns>a list of roles</returns>
        public override string[] GetRolesForUser(string userName)
        {
            if (HttpContext.Current != null)
            {
                SiteSettings siteSettings   = CacheHelper.GetCurrentSiteSettings();
                string       roleCookieName = SiteUtils.GetRoleCookieName(siteSettings);

                if ((HttpContext.Current.Request.IsAuthenticated) &&
                    (HttpContext.Current.User.Identity.Name == userName) &&
                    (siteSettings != null)
                    )
                {
                    if (
                        (CookieHelper.CookieExists(roleCookieName)) &&
                        (CookieHelper.GetCookieValue(roleCookieName).Length > 0)
                        )
                    {
                        return(GetRolesFromCookie());
                    }
                    else
                    {
                        return(GetRolesAndSetCookie());
                    }
                }
                else
                {
                    // not current user or not authenticated


                    if ((siteSettings != null) && (userName != null) && (userName.Length > 0))
                    {
                        return(SiteUser.GetRoles(siteSettings, userName));
                    }
                }
            }

            return(new string[0]);
        }
Beispiel #17
0
        private void EnsureUserPage()
        {
            // check if the user has a page cookie, if so nothing to do
            // the personalization provider will populate
            if (CookieHelper.CookieExists(userPageCookie))
            {
                return;
            }
            else
            {
                //prevent a redirect loop if the user agent isn't taking cookies
                if (Request.Params["c"] != null)
                {
                    return;
                }
            }

            // else

            if (currentUser != null)
            {
                String userPageIDString = UserPage.GetDefaultPagePath(
                    currentUser.UserGuid,
                    siteSettings,
                    Resource.MyPageDefaultUserPageName,
                    defaultUserPageCookie);

                CookieHelper.SetPersistentCookie(userPageCookie, userPageIDString);
            }
            else
            {
                // unauthenticated user with no cookie
                // set the default cookie
                CookieHelper.SetPersistentCookie(userPageCookie, defaultUserPageCookie);
            }

            Response.Redirect(SiteRoot + "/MyPage.aspx?c=t", true);
        }
        public ActionResult Index()
        {
            this.Session["Answer"]    = rng.Next(1, 101);
            this.Session["GuessList"] = new List <int>();
            Guess guess = new Guess
            {
                Answer = (int)this.Session["Answer"],
            };
            HighScore highScore;

            var requestCookie = Request.Cookies["GuessingGame"];

            if (!CookieHelper.CookieExists(requestCookie))
            {
                highScore = new HighScore();
                var responseCookie = Response.Cookies["GuessingGame"];
                CookieHelper.WriteCookie(responseCookie, "HighScore", highScore, DateTime.Now.AddYears(1));
            }
            else
            {
                try
                {
                    highScore = CookieHelper.ReadCookie <HighScore>(requestCookie, "HighScore");
                    if (highScore == null)
                    {
                        throw (new Exception("Trash data in cookie"));
                    }
                }
                catch
                {
                    highScore = new HighScore();
                    var responseCookie = Response.Cookies["GuessingGame"];
                    CookieHelper.WriteCookie(responseCookie, "HighScore", highScore, DateTime.Now.AddYears(1));
                }
            }
            return(View(new GuessAndHighScore(highScore, guess)));
        }
        private void SignInUser(SiteUser user)
        {
            if (
                (siteSettings.UseSecureRegistration) &&
                (user.RegisterConfirmGuid != Guid.Empty)
                )
            {
                Notification.SendRegistrationConfirmationLink(
                    SiteUtils.GetSmtpSettings(),
                    ResourceHelper.GetMessageTemplate("RegisterConfirmEmailMessage.config"),
                    siteSettings.DefaultEmailFromAddress,
                    user.Email,
                    siteSettings.SiteName,
                    SiteRoot + "/ConfirmRegistration.aspx?ticket=" +
                    user.RegisterConfirmGuid.ToString());


                log.Info("User " + user.Name + " tried to login but email address is not confirmed.");

                lblError.Text = Resource.RegistrationRequiresEmailConfirmationMessage;

                return;
            }

            if (user.IsLockedOut)
            {
                log.Info("User " + user.Name + " tried to login but account is locked.");

                lblError.Text = Resource.LoginAccountLockedMessage;

                return;
            }


            if (siteSettings.UseEmailForLogin)
            {
                FormsAuthentication.SetAuthCookie(
                    user.Email, true);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(
                    user.LoginName, true);
            }

            if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites)
            {
                string cookieName = "siteguid" + siteSettings.SiteGuid;
                CookieHelper.SetCookie(cookieName, user.UserGuid.ToString(), true);
            }

            user.UpdateLastLoginTime();

            // track user ip address
            UserLocation userLocation = new UserLocation(user.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Request.UserHostName;
            userLocation.Save();

            UserSignInEventArgs u = new UserSignInEventArgs(user);

            OnUserSignIn(u);

            if (CookieHelper.CookieExists(returnUrlCookieName))
            {
                returnUrl = CookieHelper.GetCookieValue(returnUrlCookieName);
                CookieHelper.ExpireCookie(returnUrlCookieName);
            }

            if (returnUrl.Length > 0)
            {
                WebUtils.SetupRedirect(this, returnUrl);
                return;
            }

            WebUtils.SetupRedirect(this, SiteRoot);
            return;
        }
        void application_AuthenticateRequest(object sender, EventArgs e)
        {
            //if (debugLog) log.Debug("AuthHandlerHttpModule Application_AuthenticateRequest");

            if (sender == null)
            {
                return;
            }

            HttpApplication app = (HttpApplication)sender;

            if (app.Request == null)
            {
                return;
            }
            if (!app.Request.IsAuthenticated)
            {
                return;
            }

            if (WebUtils.IsRequestForStaticFile(app.Request.Path))
            {
                return;
            }
            if (app.Request.Path.ContainsCaseInsensitive(".ashx"))
            {
                return;
            }
            if (app.Request.Path.ContainsCaseInsensitive(".axd"))
            {
                return;
            }
            if (app.Request.Path.ContainsCaseInsensitive("setup/default.aspx"))
            {
                return;
            }


            //if (debugLog) log.Debug("IsAuthenticated == true");
            SiteSettings siteSettings;

            try
            {
                siteSettings = CacheHelper.GetCurrentSiteSettings();
            }
            catch (System.Data.Common.DbException ex)
            {
                // can happen during upgrades
                log.Error(ex);
                return;
            }
            catch (InvalidOperationException ex)
            {
                log.Error(ex);
                return;
            }
            catch (Exception ex)
            {
                // hate to trap System.Exception but SqlCeException doe snot inherit from DbException as it should
                if (DatabaseHelper.DBPlatform() != "SqlCe")
                {
                    throw;
                }
                log.Error(ex);
                return;
            }
            bool useFolderForSiteDetection = WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites;

            // Added by Haluk Eryuksel - 2006-01-23
            // support for Windows authentication
            if (
                (app.User.Identity.AuthenticationType == "NTLM") ||
                (app.User.Identity.AuthenticationType == "Negotiate")
                // || ( Context.User.Identity.AuthenticationType == "Windows" )
                )
            {
                //Added by Benedict Chan - 2008-08-05
                //Added Cookie here so that we don't have to check the users in every page, also to authenticate under NTLM with "useFolderForSiteDetection == true"
                string cookieName = "siteguid" + siteSettings.SiteGuid;
                if (!CookieHelper.CookieExists(cookieName))
                {
                    bool existsInDB;
                    existsInDB = SiteUser.LoginExistsInDB(siteSettings.SiteId, app.Context.User.Identity.Name);

                    if (!existsInDB)
                    {
                        SiteUser u = new SiteUser(siteSettings);
                        u.Name      = app.Context.User.Identity.Name;
                        u.LoginName = app.Context.User.Identity.Name;
                        u.Email     = GuessEmailAddress(u.Name);
                        u.Password  = SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars);

                        mojoMembershipProvider m = Membership.Provider as mojoMembershipProvider;
                        if (m != null)
                        {
                            u.Password = m.EncodePassword(siteSettings, u, u.Password);
                        }

                        u.Save();
                        NewsletterHelper.ClaimExistingSubscriptions(u);

                        UserRegisteredEventArgs args = new UserRegisteredEventArgs(u);
                        OnUserRegistered(args);
                    }

                    SiteUser siteUser = new SiteUser(siteSettings, app.Context.User.Identity.Name);
                    CookieHelper.SetCookie(cookieName, siteUser.UserGuid.ToString(), true);

                    //Copied logic from SiteLogin.cs  Since we will skip them if we use NTLM
                    if (siteUser.UserId > -1 && siteSettings.AllowUserSkins && siteUser.Skin.Length > 0)
                    {
                        SiteUtils.SetSkinCookie(siteUser);
                    }

                    // track user ip address
                    try
                    {
                        UserLocation userLocation = new UserLocation(siteUser.UserGuid, SiteUtils.GetIP4Address());
                        userLocation.SiteGuid = siteSettings.SiteGuid;
                        userLocation.Hostname = app.Request.UserHostName;
                        userLocation.Save();
                        log.Info("Set UserLocation : " + app.Request.UserHostName + ":" + SiteUtils.GetIP4Address());
                    }
                    catch (Exception ex)
                    {
                        log.Error(SiteUtils.GetIP4Address(), ex);
                    }
                }

                //End-Added by Benedict Chan
            }
            // End-Added by Haluk Eryuksel


            if ((useFolderForSiteDetection) && (!WebConfigSettings.UseRelatedSiteMode))
            {
                // replace GenericPrincipal with custom one
                //string roles = string.Empty;
                if (!(app.Context.User is mojoIdentity))
                {
                    app.Context.User = new mojoPrincipal(app.Context.User);
                }
            }
        }
Beispiel #21
0
        private void SignInUser(SiteUser user, bool isNewUser)
        {
            if (
                (siteSettings.UseSecureRegistration) &&
                (user.RegisterConfirmGuid != Guid.Empty)
                )
            {
                Notification.SendRegistrationConfirmationLink(
                    SiteUtils.GetSmtpSettings(),
                    ResourceHelper.GetMessageTemplate("RegisterConfirmEmailMessage.config"),
                    siteSettings.DefaultEmailFromAddress,
                    siteSettings.DefaultFromEmailAlias,
                    user.Email,
                    siteSettings.SiteName,
                    SiteRoot + "/ConfirmRegistration.aspx?ticket=" +
                    user.RegisterConfirmGuid.ToString());


                log.Info("User " + user.Name + " tried to login but email address is not confirmed.");

                lblError.Text = Resource.RegistrationRequiresEmailConfirmationMessage;
                litInfoNeededMessage.Visible         = false;
                pnlRequiredProfileProperties.Visible = false;
                btnCreateUser.Visible = false;

                return;
            }

            if (user.IsLockedOut)
            {
                log.Info("User " + user.Name + " tried to login but account is locked.");

                lblError.Text = Resource.LoginAccountLockedMessage;

                return;
            }

            if ((siteSettings.RequireApprovalBeforeLogin) && (!user.ApprovedForLogin))
            {
                log.Info("User " + user.Name + " tried to login but account is not approved yet.");

                lblError.Text = Resource.LoginNotApprovedMessage;

                return;
            }


            if (siteSettings.UseEmailForLogin)
            {
                FormsAuthentication.SetAuthCookie(user.Email, true);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(user.LoginName, true);
            }

            if (WebConfigSettings.UseFolderBasedMultiTenants)
            {
                string cookieName = "siteguid" + siteSettings.SiteGuid;
                CookieHelper.SetCookie(cookieName, user.UserGuid.ToString(), true);
            }

            if (user.UserId > -1 && siteSettings.AllowUserSkins && user.Skin.Length > 0)
            {
                SiteUtils.SetSkinCookie(user);
            }

            user.UpdateLastLoginTime();

            // track user ip address
            UserLocation userLocation = new UserLocation(user.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Request.UserHostName;
            userLocation.Save();

            UserSignInEventArgs u = new UserSignInEventArgs(user);

            OnUserSignIn(u);

            if (CookieHelper.CookieExists(returnUrlCookieName))
            {
                returnUrl = CookieHelper.GetCookieValue(returnUrlCookieName);
                CookieHelper.ExpireCookie(returnUrlCookieName);
            }
            string requestedReturnUrl = SiteUtils.GetReturnUrlParam(Page, SiteRoot);

            returnUrl = requestedReturnUrl;

            if (isNewUser)
            {
                if (WebConfigSettings.PageToRedirectToAfterRegistration.Length > 0)
                {
                    returnUrl = SiteRoot + WebConfigSettings.PageToRedirectToAfterRegistration;
                }
            }

            if (String.IsNullOrEmpty(returnUrl) ||
                returnUrl.Contains("AccessDenied") ||
                returnUrl.Contains("Login") ||
                returnUrl.Contains("SignIn") ||
                returnUrl.Contains("ConfirmRegistration.aspx") ||
                returnUrl.Contains("OpenIdRpxHandler.aspx") ||
                returnUrl.Contains("RecoverPassword.aspx") ||
                returnUrl.Contains("Register")
                )
            {
                returnUrl = SiteRoot;
            }

            if (returnUrl.Length > 0)
            {
                if (SiteUtils.IsSecureRequest())
                {
                    if (returnUrl.StartsWith("http:"))
                    {
                        returnUrl = returnUrl.Replace("http:", "https:");
                    }
                }

                WebUtils.SetupRedirect(this, returnUrl);
                return;
            }

            if (SiteUtils.IsSecureRequest())
            {
                if (SiteRoot.StartsWith("http:"))
                {
                    WebUtils.SetupRedirect(this, SiteRoot.Replace("http:", "https:"));
                    return;
                }
            }


            WebUtils.SetupRedirect(this, SiteRoot);
            return;
        }
Beispiel #22
0
        /// <summary>
        /// required implementation
        /// </summary>
        /// <param name="username">a username</param>
        /// <returns>a list of roles</returns>
        public override string[] GetRolesForUser(string userName)
        {
            if (HttpContext.Current != null)
            {
                SiteSettings siteSettings   = CacheHelper.GetCurrentSiteSettings();
                string       roleCookieName = SiteUtils.GetRoleCookieName(siteSettings);

                if ((HttpContext.Current.Request.IsAuthenticated) &&
                    (HttpContext.Current.User.Identity.Name == userName) &&
                    (siteSettings != null)
                    )
                {
                    if (
                        (CookieHelper.CookieExists(roleCookieName)) &&
                        (CookieHelper.GetCookieValue(roleCookieName).Length > 0)
                        )
                    {
                        try
                        {
                            return(GetRolesFromCookie());

                            // the below errors are expected if the machine key has been changed and the user already has a role cookie
                            // apparently the update for http://weblogs.asp.net/scottgu/archive/2010/09/28/asp-net-security-update-now-available.aspx
                            // changed it from throwing a CryptographyException to an HttpException
                        }
                        catch (System.Security.Cryptography.CryptographicException)
                        {
                            return(GetRolesAndSetCookie());
                        }
                        catch (HttpException)
                        {
                            return(GetRolesAndSetCookie());
                        }
                        catch (NullReferenceException ex)
                        {
                            // https://www.mojoportal.com/Forums/Thread.aspx?thread=9515&mid=34&pageid=5&ItemID=2&pagenumber=1#post39505
                            // not sure what is null here but someone reported it happening using the Amazon silk browser
                            // which does some very weird things like caching everything on their own servers
                            // so their servers make the web request and the brwoser gets it from their server
                            // its like a strange proxy server
                            // then it happened on my own site after applying a windows update
                            log.Error("handled exception", ex);
                            return(GetRolesAndSetCookie());
                        }
                    }
                    else
                    {
                        return(GetRolesAndSetCookie());
                    }
                }
                else
                {
                    // not current user or not authenticated


                    if ((siteSettings != null) && (userName != null) && (userName.Length > 0))
                    {
                        return(SiteUser.GetRoles(siteSettings, userName));
                    }
                }
            }

            return(new string[0]);
        }
Beispiel #23
0
        void application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("AuthHandlerHttpModule Application_AuthenticateRequest");
            }

            if (sender == null)
            {
                return;
            }

            HttpApplication app = (HttpApplication)sender;

            if (
                (app.Request.Path.EndsWith(".gif", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".js", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".axd", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith("thumbnailservice.ashx", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.Contains("csshandler.ashx")) ||
                (app.Request.Path.EndsWith("/Data/", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.StartsWith("/Data/", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.Contains("GCheckoutNotificationHandler.ashx"))
                )
            {
                return;
            }



            if (app.Request.IsAuthenticated)
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("IsAuthenticated == true");
                }

                SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
                bool         useFolderForSiteDetection = WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites;

                // Added by Haluk Eryuksel - 2006-01-23
                // support for Windows authentication
                if (
                    (app.User.Identity.AuthenticationType == "NTLM") ||
                    (app.User.Identity.AuthenticationType == "Negotiate")
                    // || ( Context.User.Identity.AuthenticationType == "Windows" )
                    )
                {
                    //Added by Benedict Chan - 2008-08-05
                    //Added Cookie here so that we don't have to check the users in every page, also to authenticate under NTLM with "useFolderForSiteDetection == true"
                    string cookieName = "siteguid" + siteSettings.SiteGuid;
                    if (!CookieHelper.CookieExists(cookieName))
                    {
                        bool existsInDB;
                        existsInDB = SiteUser.LoginExistsInDB(siteSettings.SiteId, app.Context.User.Identity.Name);

                        if (!existsInDB)
                        {
                            SiteUser u = new SiteUser(siteSettings);
                            u.Name      = app.Context.User.Identity.Name;
                            u.LoginName = app.Context.User.Identity.Name;
                            u.Email     = "";
                            u.Password  = SiteUser.CreateRandomPassword(7);
                            u.Save();
                            NewsletterHelper.ClaimExistingSubscriptions(u);

                            UserRegisteredEventArgs args = new UserRegisteredEventArgs(u);
                            OnUserRegistered(args);
                        }

                        SiteUser siteUser = new SiteUser(siteSettings, app.Context.User.Identity.Name);
                        CookieHelper.SetCookie(cookieName, siteUser.UserGuid.ToString(), true);

                        //Copied logic from SiteLogin.cs  Since we will skip them if we use NTLM
                        if (siteUser.UserId > -1 && siteSettings.AllowUserSkins && siteUser.Skin.Length > 0)
                        {
                            SiteUtils.SetSkinCookie(siteUser);
                        }

                        // track user ip address
                        try
                        {
                            UserLocation userLocation = new UserLocation(siteUser.UserGuid, SiteUtils.GetIP4Address());
                            userLocation.SiteGuid = siteSettings.SiteGuid;
                            userLocation.Hostname = app.Request.UserHostName;
                            userLocation.Save();
                            log.Info("Set UserLocation : " + app.Request.UserHostName + ":" + SiteUtils.GetIP4Address());
                        }
                        catch (Exception ex)
                        {
                            log.Error(SiteUtils.GetIP4Address(), ex);
                        }
                    }

                    //End-Added by Benedict Chan
                }
                // End-Added by Haluk Eryuksel


                if ((useFolderForSiteDetection) && (!WebConfigSettings.UseRelatedSiteMode))
                {
                    // replace GenericPrincipal with custom one
                    //string roles = string.Empty;
                    if (!(app.Context.User is CIdentity))
                    {
                        app.Context.User = new CPrincipal(app.Context.User);
                    }
                }
            }
        }
Beispiel #24
0
        private void ShowVoting()
        {
            LoadPoll();

            lblMessage.Text        = String.Empty;
            rblOptions.Visible     = true;
            dlResults.Visible      = false;
            btnBackToVote.Visible  = false;
            btnShowResults.Visible = true;

            if (poll.PollGuid == Guid.Empty)
            {
                lblMessage.Text        = PollResources.PollNoActivePollLabel;
                btnShowResults.Visible = false;
                return;
            }

            if (!poll.IsActive && poll.ShowResultsWhenDeactivated)
            {
                lblMessage.Text = PollResources.PollDeactivatedLabel;
                userHasVoted    = true;
                ShowResult();
                return;
            }

            if (!poll.IsActive)
            {
                lblMessage.Text        = PollResources.PollNoActivePollLabel;
                lblQuestion.Text       = String.Empty;
                btnShowResults.Visible = false;
                return;
            }

            if (currentUser != null)
            {
                userHasVoted = poll.UserHasVoted(currentUser);
            }
            else
            {
                userHasVoted = CookieHelper.CookieExists(poll.PollGuid.ToString());
            }

            if (userHasVoted)
            {
                ShowResult();
                return;
            }

            if (!poll.AnonymousVoting && !Request.IsAuthenticated)
            {
                rblOptions.Enabled = false;
                lblMessage.Text    = PollResources.PollMustLoginToVoteLabel;
            }

            if (!userHasVoted && !poll.AllowViewingResultsBeforeVoting)
            {
                btnShowResults.Visible = false;
            }

            //IDataReader reader;
            List <PollOption> pollOptions = PollOption.GetOptionsByPollGuid(poll.PollGuid);

            if (poll.ShowOrderNumbers)
            {
                //reader = PollOption.GetOptionsByPollGuid(poll.PollGuid);
                DataTable table = new DataTable();
                table.Columns.Add("OptionGuid");
                table.Columns.Add("Answer");
                foreach (PollOption option in pollOptions)
                {
                    table.Rows.Add(
                        option.OptionGuid.ToString(),
                        option.Order.ToString(CultureInfo.InvariantCulture) + ". " + option.Answer);
                }
                //reader.Close();

                rblOptions.DataSource = table;
                rblOptions.DataBind();
            }
            else
            {
                //reader = PollOption.GetOptionsByPollGuid(poll.PollGuid);
                rblOptions.DataSource = pollOptions;
                rblOptions.DataBind();
                //reader.Close();
            }
        }
Beispiel #25
0
        private void LoadSettings()
        {
            ThePost = new Blog(ItemId);
            module  = new Module(ModuleId, BasePage.CurrentPage.PageId);

            siteSettings = CacheHelper.GetCurrentSiteSettings();

            if (
                (module.ModuleId == -1) ||
                (ThePost.ModuleId == -1) ||
                (ThePost.ModuleId != module.ModuleId) ||
                (siteSettings == null)
                )
            {
                // query string params have been manipulated
                this.pnlBlog.Visible = false;
                AllowComments        = false;
                parametersAreInvalid = true;
                return;
            }
            ShowAddThisButton           = siteSettings.AddThisDotComUsername.Length > 0;
            RegexRelativeImageUrlPatern = SiteUtils.GetRegexRelativeImageUrlPatern();

            moduleSettings = ModuleSettings.GetModuleSettings(ModuleId);

            GmapApiKey = SiteUtils.GetGmapApiKey();

            ShowCategories = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogShowCategoriesSetting", ShowCategories);

            BlogUseTagCloudForCategoriesSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogUseTagCloudForCategoriesSetting", BlogUseTagCloudForCategoriesSetting);

            ShowArchives = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogShowArchiveSetting", ShowArchives);

            NavigationOnRight = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogNavigationOnRightSetting", NavigationOnRight);

            ShowStatistics = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogShowStatisticsSetting", ShowStatistics);

            ShowFeedLinks = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogShowFeedLinksSetting", ShowFeedLinks);

            ShowAddFeedLinks = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogShowAddFeedLinksSetting", ShowAddFeedLinks);

            UseCommentSpamBlocker = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogUseCommentSpamBlocker", UseCommentSpamBlocker);

            RequireAuthenticationForComments = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "RequireAuthenticationForComments", RequireAuthenticationForComments);

            AllowComments = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogAllowComments", AllowComments);

            EnableContentRatingSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "EnableContentRatingSetting", EnableContentRatingSetting);

            EnableRatingCommentsSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "EnableRatingCommentsSetting", EnableRatingCommentsSetting);

            ShowPostAuthorSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "ShowPostAuthorSetting", ShowPostAuthorSetting);

            AllowWebSiteUrlForComments = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "AllowWebSiteUrlForComments", AllowWebSiteUrlForComments);

            HideDetailsFromUnauthencticated = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "HideDetailsFromUnauthencticated", HideDetailsFromUnauthencticated);

            ExcerptLength = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "BlogExcerptLengthSetting", ExcerptLength);

            if (moduleSettings.Contains("BlogExcerptSuffixSetting"))
            {
                ExcerptSuffix = moduleSettings["BlogExcerptSuffixSetting"].ToString();
            }

            if (moduleSettings.Contains("DisqusSiteShortName"))
            {
                DisqusSiteShortName = moduleSettings["DisqusSiteShortName"].ToString();
            }

            if (moduleSettings.Contains("CommentSystemSetting"))
            {
                CommentSystem = moduleSettings["CommentSystemSetting"].ToString();
            }

            if (moduleSettings.Contains("IntenseDebateAccountId"))
            {
                IntenseDebateAccountId = moduleSettings["IntenseDebateAccountId"].ToString();
            }

            CommentDateTimeFormat = DateFormat;
            if (moduleSettings.Contains("BlogDateTimeFormat"))
            {
                DateFormat = moduleSettings["BlogDateTimeFormat"].ToString().Trim();
                if (DateFormat.Length > 0)
                {
                    try
                    {
                        string d = DateTime.Now.ToString(DateFormat, CultureInfo.CurrentCulture);
                    }
                    catch (FormatException)
                    {
                        DateFormat = CultureInfo.CurrentCulture.DateTimeFormat.FullDateTimePattern;
                    }
                }
                else
                {
                    DateFormat = CultureInfo.CurrentCulture.DateTimeFormat.FullDateTimePattern;
                }
            }

            divCommentUrl.Visible = AllowWebSiteUrlForComments;

            ((CRating)Rating).Enabled       = EnableContentRatingSetting;
            ((CRating)Rating).AllowFeedback = EnableRatingCommentsSetting;
            ((CRating)Rating).ContentGuid   = ThePost.BlogGuid;

            if (moduleSettings.Contains("GoogleMapInitialMapTypeSetting"))
            {
                string gmType = moduleSettings["GoogleMapInitialMapTypeSetting"].ToString();
                try
                {
                    mapType = (MapType)Enum.Parse(typeof(MapType), gmType);
                }
                catch (ArgumentException) { }
            }

            GoogleMapHeightSetting = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "GoogleMapHeightSetting", GoogleMapHeightSetting);

            GoogleMapWidthSetting = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "GoogleMapWidthSetting", GoogleMapWidthSetting);

            GoogleMapInitialZoomSetting = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "GoogleMapInitialZoomSetting", GoogleMapInitialZoomSetting);


            GoogleMapEnableMapTypeSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableMapTypeSetting", false);

            GoogleMapEnableZoomSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableZoomSetting", false);

            GoogleMapShowInfoWindowSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapShowInfoWindowSetting", false);

            GoogleMapEnableLocalSearchSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableLocalSearchSetting", false);

            GoogleMapEnableDirectionsSetting = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GoogleMapEnableDirectionsSetting", false);

            if (moduleSettings.Contains("OdiogoFeedIDSetting"))
            {
                OdiogoFeedIDSetting = moduleSettings["OdiogoFeedIDSetting"].ToString();
            }

            addThisAccountId = BasePage.SiteInfo.AddThisDotComUsername;
            string altAddThisAccount = string.Empty;

            if (moduleSettings.Contains("BlogAddThisDotComUsernameSetting"))
            {
                altAddThisAccount = moduleSettings["BlogAddThisDotComUsernameSetting"].ToString().Trim();
            }

            if (altAddThisAccount.Length > 0)
            {
                addThisAccountId = altAddThisAccount;
            }

            useAddThisMouseOverWidget = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "BlogAddThisDotComUseMouseOverWidgetSetting", useAddThisMouseOverWidget);

            if (moduleSettings.Contains("BlogAddThisButtonImageUrlSetting"))
            {
                addThisButtonImageUrl = moduleSettings["BlogAddThisButtonImageUrlSetting"].ToString().Trim();
            }

            if (addThisButtonImageUrl.Length == 0)
            {
                addThisButtonImageUrl = "~/Data/SiteImages/addthissharebutton.gif";
            }

            if (moduleSettings.Contains("BlogAddThisCustomBrandSetting"))
            {
                addThisCustomBrand = moduleSettings["BlogAddThisCustomBrandSetting"].ToString().Trim();
            }

            if (addThisCustomBrand.Length == 0)
            {
                addThisCustomBrand = BasePage.SiteInfo.SiteName;
            }

            if (moduleSettings.Contains("BlogAddThisCustomOptionsSetting"))
            {
                addThisCustomOptions = moduleSettings["BlogAddThisCustomOptionsSetting"].ToString().Trim();
            }

            if (moduleSettings.Contains("BlogAddThisCustomLogoUrlSetting"))
            {
                addThisCustomLogoUrl = moduleSettings["BlogAddThisCustomLogoUrlSetting"].ToString().Trim();
            }

            if (moduleSettings.Contains("BlogAddThisCustomLogoBackColorSetting"))
            {
                addThisCustomLogoBackColor = moduleSettings["BlogAddThisCustomLogoBackColorSetting"].ToString().Trim();
            }

            if (moduleSettings.Contains("BlogAddThisCustomLogoForeColorSetting"))
            {
                addThisCustomLogoForeColor = moduleSettings["BlogAddThisCustomLogoForeColorSetting"].ToString().Trim();
            }

            if (moduleSettings.Contains("BlogCopyrightSetting"))
            {
                BlogCopyright = moduleSettings["BlogCopyrightSetting"].ToString();
            }

            if (moduleSettings.Contains("BlogAuthorSetting"))
            {
                BlogAuthor = moduleSettings["BlogAuthorSetting"].ToString().Trim();
            }
            BlogAuthor = BlogAuthor ?? "";

            pnlStatistics.Visible = ShowStatistics;

            divNav.Visible = false;
            if (ShowArchives ||
                ShowAddFeedLinks ||
                ShowCategories ||
                ShowFeedLinks ||
                ShowStatistics)
            {
                divNav.Visible = true;
            }

            if (!divNav.Visible)
            {
                divblog.CssClass = "blogcenter-nonav";
            }

            showLeftContent = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "ShowPageLeftContentSetting", showLeftContent);

            showRightContent = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "ShowPageRightContentSetting", showRightContent);

            if (ThePost.AllowCommentsForDays < 0)
            {
                pnlNewComment.Visible     = false;
                pnlCommentsClosed.Visible = true;
                AllowComments             = false;
            }

            if (ThePost.AllowCommentsForDays == 0)
            {
                pnlNewComment.Visible     = true;
                pnlCommentsClosed.Visible = false;
                AllowComments             = true;
            }

            if (ThePost.AllowCommentsForDays > 0)
            {
                DateTime endDate = ThePost.StartDate.AddDays((double)ThePost.AllowCommentsForDays);


                if (endDate > DateTime.UtcNow)
                {
                    pnlNewComment.Visible     = true;
                    pnlCommentsClosed.Visible = false;
                    AllowComments             = true;
                }
                else
                {
                    pnlNewComment.Visible     = false;
                    pnlCommentsClosed.Visible = true;
                    AllowComments             = false;
                }
            }

            if (AllowComments)
            {
                if ((RequireAuthenticationForComments) && (!Request.IsAuthenticated))
                {
                    AllowComments         = false;
                    pnlNewComment.Visible = false;
                    pnlCommentsRequireAuthentication.Visible = true;
                }
            }

            if (!UseCommentSpamBlocker)
            {
                pnlAntiSpam.Visible = false;
                captcha.Visible     = false;
                pnlNewComment.Controls.Remove(captcha);
            }

            //external comments service renderring
            loadExternalCommentService();

            if (!this.NavigationOnRight)
            {
                this.divNav.CssClass  = "blognavleft";
                this.divblog.CssClass = "blogcenter-leftnav";
            }

            if (Request.IsAuthenticated)
            {
                SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
                this.txtName.Text = currentUser.Name;
                txtURL.Text       = currentUser.WebSiteUrl;
                ShowExcerptOnly   = false;
            }
            else
            {
                if ((HideDetailsFromUnauthencticated) && (ThePost.Description.Length > ExcerptLength))
                {
                    pnlDetails.Visible = false;
                    pnlExcerpt.Visible = true;
                    ShowExcerptOnly    = true;
                }

                if (CookieHelper.CookieExists("blogUser"))
                {
                    this.txtName.Text = CookieHelper.GetCookieValue("blogUser");
                }
                if (CookieHelper.CookieExists("blogUrl"))
                {
                    this.txtURL.Text = CookieHelper.GetCookieValue("blogUrl");
                }
            }
        }