fix #29956 - refactor cookies

This commit is contained in:
sgay
2011-01-25 12:14:05 -01:00
parent 5b99b1e803
commit 934c48cac6
14 changed files with 269 additions and 163 deletions

View File

@@ -26,23 +26,26 @@ namespace umbraco.uicontrols
}
// do NOT append extension to cookie name, because it is used in umbraco/presentation/umbraco_client/Panel/javascript.js
static umbraco.BusinessLogic.StateHelper.Cookies.Cookie panelCookie = new StateHelper.Cookies.Cookie("UMB_PANEL", false); // was umbPanel_pWidth _pHeight
protected override void OnInit(EventArgs e)
{
// We can grab the cached window size from cookie values
if (AutoResize)
{
if (!String.IsNullOrEmpty(StateHelper.GetCookieValue("umbPanel_pWidth")))
// zb-00004 #29956 : refactor cookies names & handling
if (panelCookie.HasValue)
{
int pWidth = 0;
int pHeight = 0;
if (int.TryParse(StateHelper.GetCookieValue("umbPanel_pWidth"), out pWidth))
{
string[] wh = panelCookie.GetValue().Split('x');
if (wh.Length > 0 && int.TryParse(wh[0], out pWidth))
Width = Unit.Pixel(pWidth);
}
if (int.TryParse(StateHelper.GetCookieValue("umbPanel_pHeight"), out pHeight))
{
if (wh.Length > 1 && int.TryParse(wh[1], out pHeight))
Height = Unit.Pixel(pHeight);
}
}
}

View File

@@ -194,37 +194,22 @@ namespace umbraco.BasePages {
public static string umbracoUserContextID {
get
{
if (HttpContext.Current != null)
if (HttpContext.Current.Request != null)
if (HttpContext.Current.Request.Cookies != null)
{
HttpCookie userContext = HttpContext.Current.Request.Cookies.Get("UserContext");
if (userContext != null)
return userContext.Value;
}
return "";
// zb-00004 #29956 : refactor cookies names & handling
if (StateHelper.Cookies.HasCookies && StateHelper.Cookies.UserContext.HasValue)
return StateHelper.Cookies.UserContext.GetValue();
else
return "";
}
set {
if (HttpContext.Current != null)
{
// Clearing all old cookies before setting a new one.
try
{
if (HttpContext.Current.Request != null)
if (HttpContext.Current.Request.Cookies["UserContext"] != null)
{
HttpContext.Current.Response.Cookies.Clear();
}
}
catch
{
}
// zb-00004 #29956 : refactor cookies names & handling
if (StateHelper.Cookies.HasCookies)
{
// Clearing all old cookies before setting a new one.
if (StateHelper.Cookies.UserContext.HasValue)
StateHelper.Cookies.ClearAll();
// Create new cookie.
var c = new HttpCookie("UserContext");
c.Name = "UserContext";
c.Value = value;
c.Expires = DateTime.Now.AddDays(1);
HttpContext.Current.Response.Cookies.Add(c);
StateHelper.Cookies.UserContext.SetValue(value, 1);
}
}
}

View File

@@ -197,18 +197,6 @@ namespace umbraco.BusinessLogic
#region Cookie Helpers
/// <summary>
/// Determines whether a cookie has a value with a specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the cookie has a value with the specified key; otherwise, <c>false</c>.
/// </returns>
public static bool HasCookieValue(string key)
{
return !string.IsNullOrEmpty(GetCookieValue(HttpContext.Current, key));
}
/// <summary>
/// Gets the cookie value.
/// </summary>
@@ -216,33 +204,10 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public static string GetCookieValue(string key)
{
return GetCookieValue(HttpContext.Current, key);
}
/// <summary>
/// Gets the cookie value.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static string GetCookieValue(HttpContext context, string key)
{
// Updated by NH to check against session values as well, which is an optional switch used by members
string tempValue = null;
if (context == null || context.Request == null)
if (!Cookies.HasCookies)
return null;
HttpCookie cookie = context.Request.Cookies[key];
if (cookie == null) {
// Check for session
if (context.Session != null && context.Session[key] != null)
if (context.Session[key].ToString() != "0")
tempValue = context.Session[key].ToString();
}
else
tempValue = cookie.Value;
return tempValue;
var cookie = HttpContext.Current.Request.Cookies[key];
return cookie == null ? null : cookie.Value;
}
/// <summary>
@@ -252,7 +217,7 @@ namespace umbraco.BusinessLogic
/// <param name="value">The value.</param>
public static void SetCookieValue(string key, string value)
{
SetCookieValue(HttpContext.Current, key, value);
SetCookieValue(key, value, 30d); // default Umbraco expires is 30 days
}
/// <summary>
@@ -263,52 +228,191 @@ namespace umbraco.BusinessLogic
/// <param name="daysToPersist">How long the cookie should be present in the browser</param>
public static void SetCookieValue(string key, string value, double daysToPersist)
{
SetCookieValue(HttpContext.Current, key, value, daysToPersist);
}
if (!Cookies.HasCookies)
return;
var context = HttpContext.Current;
public static void ClearCookie(string key)
{
HttpContext ctx = HttpContext.Current;
HttpCookie cookie = new HttpCookie(key, value);
cookie.Expires = DateTime.Now.AddDays(daysToPersist);
context.Response.Cookies.Set(cookie);
if (ctx.Request.Cookies[key] != null)
ctx.Response.Cookies[key].Expires = DateTime.Now;
}
cookie = context.Request.Cookies[key];
if (cookie != null)
cookie.Value = value;
}
/// <summary>
/// Sets the cookie value.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetCookieValue(HttpContext context, string key, string value)
{
SetCookieValue(context, key, value, 30);
}
// zb-00004 #29956 : refactor cookies names & handling
public static class Cookies
{
/*
* helper class to manage cookies
*
* beware! SetValue(string value) does _not_ set expires, unless the cookie has been
* configured to have one. This allows us to have cookies w/out an expires timespan.
* However, default behavior in Umbraco was to set expires to 30days by default. This
* must now be managed in the Cookie constructor or by using an overriden SetValue(...).
*
* we currently reproduce this by configuring each cookie with a 30d expires, but does
* that actually make sense? shouldn't some cookie have _no_ expires?
*/
static readonly Cookie _preview = new Cookie("UMB_PREVIEW", 30d); // was "PreviewSet"
static readonly Cookie _userContext = new Cookie("UMB_UCONTEXT", 30d); // was "UserContext"
static readonly Cookie _member = new Cookie("UMB_MEMBER", 30d); // was "umbracoMember"
/// <summary>
/// Sets the cookie value including the number of days to persist the cookie
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="daysToPersist">How long the cookie should be present in the browser</param>
public static void SetCookieValue(HttpContext context, string key, string value, double daysToPersist)
{
if (context == null || context.Request == null)
return;
HttpCookie cookie = context.Request.Cookies[key];
public static Cookie Preview { get { return _preview; } }
public static Cookie UserContext { get { return _userContext; } }
public static Cookie Member { get { return _member; } }
if (cookie == null)
cookie = new HttpCookie(key);
public static bool HasCookies
{
get
{
System.Web.HttpContext context = HttpContext.Current;
// although just checking context should be enough?!
// but in some (replaced) umbraco code, everything is checked...
return context != null
&& context.Request != null & context.Request.Cookies != null
&& context.Response != null && context.Response.Cookies != null;
}
}
cookie.Value = value;
public static void ClearAll()
{
HttpContext.Current.Response.Cookies.Clear();
}
// add default exp on a month
cookie.Expires = DateTime.Now.AddDays(daysToPersist);
public class Cookie
{
const string cookiesExtensionConfigKey = "umbracoCookiesExtension";
// if cookie exists, remove
context.Response.Cookies.Add(cookie);
}
static readonly string _ext;
TimeSpan _expires;
string _key;
static Cookie()
{
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
_ext = appSettings[cookiesExtensionConfigKey] == null ? "" : "_" + (string)appSettings[cookiesExtensionConfigKey];
}
public Cookie(string key)
: this(key, TimeSpan.Zero, true)
{ }
public Cookie(string key, double days)
: this(key, TimeSpan.FromDays(days), true)
{ }
public Cookie(string key, TimeSpan expires)
: this(key, expires, true)
{ }
public Cookie(string key, bool appendExtension)
: this(key, TimeSpan.Zero, appendExtension)
{ }
public Cookie(string key, double days, bool appendExtension)
: this(key, TimeSpan.FromDays(days), appendExtension)
{ }
public Cookie(string key, TimeSpan expires, bool appendExtension)
{
_key = appendExtension ? key + _ext : key;
_expires = expires;
}
public string Key
{
get { return _key; }
}
public bool HasValue
{
get { return RequestCookie != null; }
}
public string GetValue()
{
return RequestCookie == null ? null : RequestCookie.Value;
}
public void SetValue(string value)
{
HttpCookie cookie = new HttpCookie(_key, value);
if (!TimeSpan.Zero.Equals(_expires))
cookie.Expires = DateTime.Now + _expires;
ResponseCookie = cookie;
// original Umbraco code also does this
// so we can GetValue() back what we previously set
cookie = RequestCookie;
if (cookie != null)
cookie.Value = value;
}
public void SetValue(string value, double days)
{
SetValue(value, DateTime.Now.AddDays(days));
}
public void SetValue(string value, TimeSpan expires)
{
SetValue(value, DateTime.Now + expires);
}
public void SetValue(string value, DateTime expires)
{
HttpCookie cookie = new HttpCookie(_key, value);
cookie.Expires = expires;
ResponseCookie = cookie;
// original Umbraco code also does this
// so we can GetValue() back what we previously set
cookie = RequestCookie;
if (cookie != null)
cookie.Value = value;
}
public void Clear()
{
if (RequestCookie != null || ResponseCookie != null)
{
HttpCookie cookie = new HttpCookie(_key);
cookie.Expires = DateTime.Now.AddDays(-1);
ResponseCookie = cookie;
}
}
public void Remove()
{
// beware! will not clear browser's cookie
// you probably want to use .Clear()
HttpContext.Current.Response.Cookies.Remove(_key);
}
public HttpCookie RequestCookie
{
get
{
return HttpContext.Current.Request.Cookies[_key];
}
}
public HttpCookie ResponseCookie
{
get
{
return HttpContext.Current.Response.Cookies[_key];
}
set
{
// .Set() ensures the uniqueness of cookies in the cookie collection
// ie it is the same as .Remove() + .Add() -- .Add() allows duplicates
HttpContext.Current.Response.Cookies.Set(value);
}
}
}
}
#endregion
}

View File

@@ -32,8 +32,8 @@ namespace umbraco.cms.businesslogic.member
public static readonly Guid _objectType = new Guid("39eb0f98-b348-42a1-8662-e7eb18487560");
private static readonly object m_Locker = new object();
// zb-00035 #29931 : cleanup member state management
private static readonly string UmbracoMemberCookieKey = "umbracoMember";
// zb-00004 #29956 : refactor cookies names & handling
private const string m_SQLOptimizedMany = @"
select
@@ -762,7 +762,8 @@ namespace umbraco.cms.businesslogic.member
static void SetMemberState(int memberId, Guid memberGuid, string memberLogin)
{
string value = string.Format("{0}+{1}+{2}", memberId, memberGuid, memberLogin);
StateHelper.SetCookieValue(UmbracoMemberCookieKey, value);
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.SetValue(value);
}
static void SetMemberState(Member member, bool useSession, double cookieDays)
@@ -774,22 +775,41 @@ namespace umbraco.cms.businesslogic.member
{
string value = string.Format("{0}+{1}+{2}", memberId, memberGuid, memberLogin);
// zb-00004 #29956 : refactor cookies names & handling
if (useSession)
HttpContext.Current.Session[UmbracoMemberCookieKey] = value;
HttpContext.Current.Session[StateHelper.Cookies.Member.Key] = value;
else
StateHelper.SetCookieValue(UmbracoMemberCookieKey, value, cookieDays);
StateHelper.Cookies.Member.SetValue(value, cookieDays);
}
static void ClearMemberState()
{
StateHelper.ClearCookie(UmbracoMemberCookieKey);
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.Clear();
}
static MemberState GetMemberState()
{
string value = StateHelper.GetCookieValue(UmbracoMemberCookieKey);
// zb-00004 #29956 : refactor cookies names & handling + bring session-related stuff here
string value = null;
if (StateHelper.Cookies.Member.HasValue)
{
value = StateHelper.Cookies.Member.GetValue();
}
else
{
var context = HttpContext.Current;
if (context != null && context.Session != null && context.Session[StateHelper.Cookies.Member.Key] != null)
{
string v = context.Session[StateHelper.Cookies.Member.Key].ToString();
if (v != "0")
value = v;
}
}
if (value == null)
return null;
string[] parts = value.Split(new char[] { '+' });
if (parts.Length != 3)
return null;

View File

@@ -90,8 +90,11 @@ namespace umbraco.presentation
get
{
string currentUrl = Request.Url.AbsolutePath;
return !String.IsNullOrEmpty(StateHelper.GetCookieValue("PreviewSet")) &&
UmbracoUser != null && !currentUrl.StartsWith(IO.IOHelper.ResolveUrl(IO.SystemDirectories.Umbraco));
// zb-00004 #29956 : refactor cookies names & handling
return
StateHelper.Cookies.Preview.HasValue // has preview cookie
&& UmbracoUser != null // has user
&& !currentUrl.StartsWith(IO.IOHelper.ResolveUrl(IO.SystemDirectories.Umbraco)); // is not in admin UI
}
}
@@ -99,7 +102,8 @@ namespace umbraco.presentation
{
if (InPreviewMode)
{
PreviewContent pc = new PreviewContent(new Guid(StateHelper.GetCookieValue("PreviewSet")));
// zb-00004 #29956 : refactor cookies names & handling
PreviewContent pc = new PreviewContent(new Guid(StateHelper.Cookies.Preview.GetValue()));
pc.LoadPreviewset();
return pc.XmlContent;
}

View File

@@ -63,7 +63,7 @@ namespace umbraco.presentation
{
if (UmbracoContext.Current.InPreviewMode)
{
PreviewContent pc = new PreviewContent(new Guid(StateHelper.GetCookieValue("PreviewSet")));
PreviewContent pc = new PreviewContent(new Guid(StateHelper.Cookies.Preview.GetValue()));
pc.LoadPreviewset();
return XmlDocumentToXDocument(pc.XmlContent);
}

View File

@@ -1966,10 +1966,9 @@ namespace umbraco
/// <returns>A string with the value of the cookie</returns>
public static string RequestCookies(string key)
{
if (HttpContext.Current.Request.Cookies[key] != null)
return HttpContext.Current.Request.Cookies[key].Value;
else
return string.Empty;
// zb-00004 #29956 : refactor cookies handling
var value = StateHelper.GetCookieValue(key);
return value ?? "";
}
/// <summary>

View File

@@ -1440,7 +1440,8 @@ namespace umbraco
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// propagate the user's context
HttpCookie inCookie = HttpContext.Current.Request.Cookies["UserContext"];
// zb-00004 #29956 : refactor cookies names & handling
HttpCookie inCookie = StateHelper.Cookies.UserContext.RequestCookie;
var cookie = new Cookie(inCookie.Name, inCookie.Value, inCookie.Path,
HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);
myHttpWebRequest.CookieContainer = new CookieContainer();

View File

@@ -13,17 +13,18 @@ namespace umbraco.presentation.umbraco.developer.Xslt
{
public partial class xsltVisualize : BasePages.UmbracoEnsuredPage
{
// zb-00004 #29956 : refactor cookies names & handling
static global::umbraco.BusinessLogic.StateHelper.Cookies.Cookie cookie
= new global::umbraco.BusinessLogic.StateHelper.Cookies.Cookie("UMB_XSLTVISPG", TimeSpan.FromMinutes(20)); // was "XSLTVisualizerPage"
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpCookie cookie = Request.Cookies.Get("XSLTVisualizerPage");
// Check if cookie exists in the current request.
if (cookie != null)
{
contentPicker.Text = cookie.Value;
}
// zb-00004 #29956 : refactor cookies names & handling
if (cookie.HasValue)
contentPicker.Text = cookie.GetValue();
}
}
@@ -85,17 +86,8 @@ namespace umbraco.presentation.umbraco.developer.Xslt
// add cookie with current page
HttpCookie cookie = Request.Cookies.Get("XSLTVisualizerPage");
// Check if cookie exists in the current request.
if (cookie == null)
{
cookie = new HttpCookie("XSLTVisualizerPage");
}
cookie.Value = contentPicker.Text;
cookie.Expires = DateTime.Now.AddMinutes(20d);
Response.Cookies.Add(cookie);
// zb-00004 #29956 : refactor cookies names & handling
cookie.SetValue(contentPicker.Text);
}
}

View File

@@ -210,10 +210,8 @@ namespace umbraco.cms.presentation
return;
// clear preview cookie
if (!String.IsNullOrEmpty(StateHelper.GetCookieValue(PreviewContent.PREVIEW_COOKIE_KEY)))
{
PreviewContent.ClearPreviewCookie();
}
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Preview.Clear();
if (!IsPostBack)
{

View File

@@ -11,7 +11,7 @@ namespace umbraco.presentation
{
protected void Page_Load(object sender, EventArgs e)
{
preview.PreviewContent.ClearPreviewCookie();
preview.PreviewContent.ClearPreviewCookie();
Response.Redirect(helper.Request("redir"), true);
}
}

View File

@@ -19,11 +19,13 @@ namespace umbraco.presentation.preview
{
public class PreviewContent
{
public const string PREVIEW_COOKIE_KEY = "PreviewSet";
// zb-00004 #29956 : refactor cookies names & handling
public XmlDocument XmlContent { get; set; }
public Guid PreviewSet { get; set; }
public string PreviewsetPath { get; set; }
private int m_userId = 0;
public PreviewContent(User user)
{
m_userId = user.Id;
@@ -93,12 +95,13 @@ namespace umbraco.presentation.preview
}
public void ActivatePreviewCookie() {
StateHelper.SetCookieValue(PREVIEW_COOKIE_KEY, PreviewSet.ToString());
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Preview.SetValue(PreviewSet.ToString());
}
public static void ClearPreviewCookie() {
StateHelper.ClearCookie(PREVIEW_COOKIE_KEY);
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Preview.Clear();
}
}
}

View File

@@ -91,11 +91,10 @@ namespace umbraco.cms.presentation
// Version check goes here!
string updateCheckCookie = "";
if (Request.Cookies["updateCheck"] != null)
{
updateCheckCookie = Request.Cookies["updateCheck"].Value.ToString();
}
// zb-00004 #29956 : refactor cookies names & handling
var updChkCookie = new umbraco.BusinessLogic.StateHelper.Cookies.Cookie("UMB_UPDCHK", GlobalSettings.VersionCheckPeriod); // was "updateCheck"
string updateCheckCookie = updChkCookie.HasValue ? updChkCookie.GetValue() : "";
if (GlobalSettings.VersionCheckPeriod > 0 && String.IsNullOrEmpty(updateCheckCookie) && base.getUser().UserType.Alias == "admin")
{
@@ -106,8 +105,7 @@ namespace umbraco.cms.presentation
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "upgradeChecker", "jQuery(document).ready(function() {umbraco.presentation.webservices.CheckForUpgrade.CallUpgradeService(umbracoCheckUpgrade);});", true);
Response.Cookies["updateCheck"].Value = "1";
Response.Cookies["updateCheck"].Expires = DateTime.Now.AddDays(GlobalSettings.VersionCheckPeriod);
updChkCookie.SetValue("1");
}
DataBind();
}

View File

@@ -45,6 +45,5 @@ function resizePanelTo(PanelName, hasMenu, pWidth, pHeight) {
}
// set cookies
jQuery.cookie('umbPanel_pWidth', pWidth);
jQuery.cookie('umbPanel_pHeight', pHeight);
jQuery.cookie('UMB_PANEL', '' + pWidth + 'x' + pHeight);
}