/// <summary>
        /// Apply cookies of the CommandResult to the response.
        /// </summary>
        /// <param name="commandResult">Commandresult</param>
        /// <param name="response">Response</param>
        public static void ApplyCookies(this CommandResult commandResult, HttpResponseBase response)
        {
            if (commandResult == null)
            {
                throw new ArgumentNullException(nameof(commandResult));
            }

            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            if (!string.IsNullOrEmpty(commandResult.SetCookieName))
            {
                var protectedData = HttpRequestData.ConvertBinaryData(
                    MachineKey.Protect(
                        commandResult.GetSerializedRequestState(),
                        HttpRequestBaseExtensions.ProtectionPurpose));

                response.SetCookie(new HttpCookie(
                                       commandResult.SetCookieName,
                                       protectedData)
                {
                    HttpOnly = true
                });
            }

            if (!string.IsNullOrEmpty(commandResult.ClearCookieName))
            {
                response.SetCookie(new HttpCookie(commandResult.ClearCookieName)
                {
                    Expires = new DateTime(1970, 01, 01)
                });
            }
        }
Пример #2
0
 /// <summary>
 /// Expires the specified key.
 /// </summary>
 /// <param name="key">The key.</param>
 public void Expire(string key)
 {
     response.SetCookie(new HttpCookie(key)
     {
         Expires = DateTime.Today.AddDays(-1)
     });
 }
Пример #3
0
 public void DeactivateUserMode(HttpResponseBase response)
 {
     response.SetCookie(new HttpCookie(turgunda_string)
     {
         Expires = new DateTime(DateTime.Now.Subtract(new TimeSpan(10000000)).Ticks)
     });
 }
Пример #4
0
        /// <summary>
        /// Обеспечиваем простую вещь: каждому браузеру[пользователю] - свою правильную куку и сессию.
        /// Никаких проверок и авторизаций - просто обеспечиваем наличие куки и сессии
        /// </summary>
        /// <param name="currentRequest">Текущий запрос</param>
        /// <param name="currentResponse">Текущий ответ</param>
        /// <returns>Пользовательская сессия</returns>
        public virtual TSession GetOrCreateSessionByCookie(HttpRequestBase currentRequest, HttpResponseBase currentResponse)
        {
            // если куки нет - новую сессию и куку, кука битая - новую сессию и куку, сессии нет - новую сессию и куку

            HttpCookie cookie  = currentRequest.Cookies[AUTH_COOKIE_NAME];
            TSession   session = null;

            if (cookie != null)
            {
                session = this.Find <TSession>(Guid.Parse(cookie.Value));
            }

            if (session == null)
            {
                session = this.Add <TSession>(Guid.NewGuid(), new TSession());
                if (currentResponse.Cookies.AllKeys.Contains(AUTH_COOKIE_NAME))
                {
                    currentResponse.Cookies[AUTH_COOKIE_NAME].Value = session.Key.ToString();
                }
                else
                {
                    currentResponse.SetCookie(new HttpCookie(AUTH_COOKIE_NAME, session.Key.ToString())
                    {
                        Path = AUTH_COOKIE_PATH, Expires = DateTime.MaxValue
                    });
                }
            }

            return(session);
        }
Пример #5
0
        public static void SaveUserIdentity(this HttpResponseBase response, UserModel user)
        {
            var userCookieName = AccountController.UserCookieName;

            var value = string.Format(
                "{0};{1};{2};{3};{4}",
                user.Id,
                user.Username,
                user.Email,
                user.FirstName,
                user.LastName);
            var ticket = new FormsAuthenticationTicket(
                1,
                userCookieName,
                DateTime.Now,
                DateTime.Now.AddDays(30),
                true,
                value,
                FormsAuthentication.FormsCookiePath);

            response.SetCookie(
                new HttpCookie(
                    userCookieName,
                    FormsAuthentication.Encrypt(ticket)));
        }
 /// <summary>
 /// Nastavi pozadovanu cookie do response
 /// </summary>
 /// <param name="response">Response pre ktory chceme nastavit cookie</param>
 /// <param name="name">Meno cookie</param>
 /// <param name="value">Hodnota ktoru chceme nastavit</param>
 /// <param name="expireDate">Datum expiracie</param>
 public static void SetCookieValue(this HttpResponseBase response, String name, String value, DateTime expireDate)
 {
     response.SetCookie(new HttpCookie(name, value)
     {
         Expires = expireDate
     });
 }
Пример #7
0
        public void SetToCookie(HttpResponseBase resp, CookieType type, string value)
        {
            HttpCookie cookie = new HttpCookie(GetCookTypeName(type), value);

            resp.Cookies.Remove(GetCookTypeName(type));
            resp.SetCookie(cookie);
        }
        internal static void ClearResponseCookie(HttpResponseBase response)
        {
            HttpCookie cookie = new HttpCookie("oneDriveUser", null);

            cookie.HttpOnly = true;
            response.SetCookie(cookie);
        }
Пример #9
0
        public static void SaveTwoFactorAuthenticationToken(CMSDataContext db, HttpResponseBase response)
        {
            var expirationDays = db.Setting("TwoFactorAuthExpirationDays", "30").ToInt();
            var expires        = DateTime.Now.AddDays(expirationDays);
            var key            = string.Join("", "123".Select(c => Guid.NewGuid().ToString("N")));
            var token          = new MFAToken {
                Expires = expires,
                Key     = key,
                UserId  = Util.MFAUserId ?? db.UserId
            };

            db.MFATokens.InsertOnSubmit(token);
            db.SubmitChanges();

            var cookie = new HttpCookie(TwoFactorAuthCookie, token.Key)
            {
                Expires = expires, HttpOnly = true, Secure = !Util.IsDebug()
            };

            if (!cookie.Secure) // https://stackoverflow.com/questions/26627886/not-able-to-set-cookie-from-action
            {
                cookie.Domain = null;
            }
            response.SetCookie(cookie);
        }
Пример #10
0
 /// <summary>
 /// Создает сессию для текущего пользователя
 /// </summary>
 /// <param name="Response">Необходим для вставки в coocke-файл пользователя идентификатор сессии</param>
 public void CreateSession(HttpResponseBase Response)
 {
     if (this.IsExistsInDB())
     {
         Response.SetCookie(new HttpCookie("userID", this.userID.ToString()));
     }
 }
Пример #11
0
        /// <summary>
        /// Expire a HttpCookie with the given key name.
        /// See also Create() method.
        /// </summary>
        public static void ExpireCookie(HttpResponseBase response, string name)
        {
            var cookie = Create(name);

            cookie.Expires = DateTime.UtcNow.AddDays(ExpiresDays);
            response.SetCookie(cookie);
        }
Пример #12
0
        public static void ClientCookie(this HttpResponseBase response, string userId, IProcessQueries queries)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            if (queries == null)
            {
                throw new ArgumentNullException("queries");
            }

            var cookie = new HttpCookie(CookieName, "");

            int userIdInt;

            if (int.TryParse(userId, out userIdInt))
            {
                var    data        = queries.Execute(new ClientCookieBy(userIdInt)).Result;
                var    json        = JsonConvert.SerializeObject(data);
                byte[] jsonBytes   = MachineKey.Protect(Encoding.UTF8.GetBytes(json), "Cookie");
                string cookieValue = HttpServerUtility.UrlTokenEncode(jsonBytes);
                cookie.Values[ClientCookieKey] = cookieValue;
                //cookie.Expires = DateTime.UtcNow.AddDays(60);
            }
            else
            {
                cookie.Expires = DateTime.UtcNow.AddDays(-2);
            }

            response.SetCookie(cookie);
        }
Пример #13
0
 internal static void SetCookieValue <T>(HttpResponseBase response, string name, T value, DateTime expires)
 {
     response.SetCookie(new HttpCookie(name, Convert.ToString(value))
     {
         Expires = expires, Path = "/"
     });
 }
Пример #14
0
 public void Forget(HttpResponseBase response)
 {
     response.SetCookie(new HttpCookie(AuthCookie, string.Empty)
     {
         Expires = DateTime.Now
     });
 }
        internal void SetResponseCookie(HttpResponseBase response)
        {
            HttpCookie cookie = new HttpCookie("oneDriveUser", this.UserId);

            cookie.HttpOnly = true;

            response.SetCookie(cookie);
        }
Пример #16
0
        public static void UpdateCultureCookie(HttpResponseBase response)
        {
            var cookie = new HttpCookie(CultureKey, Thread.CurrentThread.CurrentUICulture.Name)
            {
                Expires = DateTime.Now.AddYears(1)
            };

            response.SetCookie(cookie);
        }
Пример #17
0
        public static void UpdateLocalThemeCookie(HttpRequestBase request, HttpResponseBase response)
        {
            var savedCookie = new HttpCookie(LocalCookieName, GetTheme(request))
            {
                Expires = DateTime.Now.AddYears(1)
            };

            response.SetCookie(savedCookie);
        }
Пример #18
0
        /// <summary>
        /// Sets the culture for the HTTP response.
        /// </summary>
        /// <param name="response">The HTTP response.</param>
        /// <param name="culture">The culture to set.</param>
        private static void SetClientCulture(HttpResponseBase response, string culture)
        {
            var cookie = new HttpCookie(s_settings.Name, culture);

            cookie.Domain  = s_settings.Domain;
            cookie.Path    = s_settings.Path;
            cookie.Expires = DateTime.UtcNow.Add(s_settings.Expiration);
            response.SetCookie(cookie);
        }
Пример #19
0
        public void AddUserCookie(string value)
        {
            var cookie = new HttpCookie(LOGGED_USER, value);

            cookie.Expires = DateTime.Now.AddHours(1);
            cookie.Secure  = false;
            _request.Cookies.Remove(LOGGED_USER);
            _response.SetCookie(cookie);
        }
Пример #20
0
 /// <summary>
 /// Set a **SESSION** HttpCookie with the given key/value name pair.
 /// See also Create() method.
 /// </summary>
 public static void SetCookie(
     HttpResponseBase response,
     string name,
     string value  = null,
     bool httpOnly = true,
     bool secure   = true)
 {
     response.SetCookie(Create(name, value, httpOnly, secure));
 }
Пример #21
0
        public static void SignOut(HttpResponseBase response)
        {
            var httpCookie = new HttpCookie("auth")
            {
                Expires = DateTime.Now.AddDays(-1)
            };

            response.SetCookie(httpCookie);
            HttpContext.Current.User = null;
        }
Пример #22
0
 public void ActivateUserMode(HttpResponseBase response, string uuser)
 {
     if (string.IsNullOrEmpty(uuser))
     {
         return;
     }
     response.SetCookie(new HttpCookie(turgunda_string, uuser)
     {
         Expires = new DateTime(DateTime.Now.AddHours(16).Ticks)
     });
 }
Пример #23
0
 public void ClearCookie(HttpResponseBase resp)
 {
     if (resp == null)
     {
         throw new ArgumentNullException("resp");
     }
     resp.SetCookie(new HttpCookie(CookieName, null)
     {
         Expires = new DateTime(2010, 1, 1)
     });
 }
Пример #24
0
        public void SetCookie(Cookie cookie)
        {
            if (!HostContext.AppHost.AllowSetCookie(Request, cookie.Name))
            {
                return;
            }

            var httpCookie = cookie.ToHttpCookie();

            response.SetCookie(httpCookie);
        }
Пример #25
0
 public void Save(string key, string value)
 {
     if (key == null || value == null)
     {
         throw new ArgumentNullException();
     }
     _response.SetCookie(new HttpCookie(key, value)
     {
         Expires = DateTime.MaxValue
     });
 }
        /// <summary>
        /// Saves the specified language to the culture cookie
        /// </summary>
        /// <param name="response">HTTP response</param>
        /// <param name="language">Code for the language</param>
        /// <param name="expireDays">Expires in given number of days</param>
        public static void SavePreferredCulture(HttpResponseBase response,
                                                string language, int expireDays = 1)
        {
            var cookie = new HttpCookie(CookieName)
            {
                Expires = DateTime.UtcNow.AddDays(expireDays)
            };

            cookie.Values[CookieLangEntry] = language;
            response.SetCookie(cookie);
        }
Пример #27
0
        public static void SetAuthorizationCookie(this HttpResponseBase response, UserModel userModel)
        {
            var jwtToken = JwtTokenProvider.GenerateAccessToken(JwtTokenProvider.WebAudience, userModel);

            var cookie = new HttpCookie("token", jwtToken)
            {
                Expires = userModel.RememberMe ? DateTime.UtcNow.AddYears(1) : DateTime.UtcNow.AddMinutes(30)
            };

            response.SetCookie(cookie);
        }
Пример #28
0
        private void UnsetAuthorizationCookie(HttpResponseBase httpresponsebase, HttpCookieCollection cookiecollection)
        {
            HttpCookie authCookie = cookiecollection[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                cookiecollection.Remove(FormsAuthentication.FormsCookieName);
                authCookie.Expires = DateTime.Now.AddDays(-10);
                authCookie.Value   = null;
                httpresponsebase.SetCookie(authCookie);
            }
            HttpCookie userCookie = cookiecollection["userCookie"];

            if (userCookie != null)
            {
                cookiecollection.Remove("userCookie");
                userCookie.Expires = DateTime.Now.AddDays(-10);
                userCookie.Value   = null;
                httpresponsebase.SetCookie(userCookie);
            }
        }
Пример #29
0
        private void RemoveCookie(string p, HttpRequestBase Request, HttpResponseBase Response)
        {
            HttpCookie currentUserCookie = Request.Cookies[p];

            if (currentUserCookie != null)
            {
                Response.Cookies.Remove(p);
                currentUserCookie.Expires = DateTime.Now.AddDays(-10);
                currentUserCookie.Value   = null;
                Response.SetCookie(currentUserCookie);
            }
        }
        public static void AdminCache(this HttpResponseBase response, AdminCacheModel info)
        {
            var json = JsonConvert.SerializeObject(info);

            json = HttpUtility.UrlEncode(json);
            var cookie = new HttpCookie(CookieName, json)
            {
                Expires = DateTime.UtcNow.AddDays(60),
            };

            response.SetCookie(cookie);
        }