Exemplo n.º 1
0
        public static long GetCurrentGuestId(this HttpContextBase ctx)
        {
            bool needRecookie = false;

            long   guestId     = -1;
            string guestValue  = "-1";
            var    cookieValue = ctx.Request.Cookies[guest_cookie_name];

            if (!string.IsNullOrEmpty(cookieValue?.Value))
            {
                if (RegexGuestId.IsMatch(cookieValue.Value) && !ConfigSetting.ProtectGuestId)
                {
                    guestValue = cookieValue.Value;
                    //needRecookie = ProtectGuestId;
                }
                else if (cookieValue.Value.Length > 40)
                {
                    var unprotected = XnAuthentication.UnprotectData(encryptionKey, validationKey, cookieValue.Value);
                    if (unprotected != null && RegexGuestId.IsMatch(unprotected))
                    {
                        guestValue   = unprotected;
                        needRecookie = !ConfigSetting.ProtectGuestId;
                    }
                }
            }

            long.TryParse(guestValue, out guestId);

            if (guestId > -2)
            {
                //userId = GuestHandler.GenerateGuestId();
                var ipByInt = IpExtenstions.IpToInt(ctx.GetClientIP());
                guestValue   = String.Format(guestIdFormatter, ipByInt, GetRnd());
                guestId      = long.Parse(guestValue);
                needRecookie = true;
            }
            if (needRecookie)
            {
                var newCookieValue = ConfigSetting.ProtectGuestId ? XnAuthentication.ProtectData(encryptionKey, validationKey, guestValue) : guestValue;
                var cookie         = new HttpCookie(guest_cookie_name, newCookieValue);
                var requestDomain  = ctx.Request.Url?.Host.Split('.');
                if (requestDomain?.Length > 2)
                {
                    cookie.Domain = requestDomain[requestDomain.Length - 2] + "."
                                    + requestDomain[requestDomain.Length - 1];
                }
                else
                {
#if DEBUG
                    cookie.Domain = "Xn.dev";
#else
                    cookie.Domain = "Xn.cn";
#endif
                }
                cookie.Shareable = false;
                cookie.Expires   = DateTime.Now.AddYears(5);
                ctx.Response.SetCookie(cookie);
            }
            return(guestId);
        }