예제 #1
0
        public override TPrivate CheckUpdate(int id, TPrivate dto, HttpContext ctxt)
        {
            CheckCredentials(id);
            CheckDTOForUpdating(dto);
            AccountService.CheckDTOForUpdating(dto.Account);
            if (Entities.Any(e => e.ConnectionId == dto.ConnectionId && e.Id != id))
            {
                throw new AppException($"'{dto.ConnectionId}' is already used as connectionId", 400);
            }
            TEntity entity = FindEntity(id);
            IRequestCookieCollection cookies = ctxt.Request.Cookies;

            if (
                entity.User.Password != dto.Password &&
                cookies.ContainsKey(Credentials.PASSWORD_KEY) &&
                !String.IsNullOrEmpty(cookies[Credentials.PASSWORD_KEY])
                )
            {
                ctxt.Response.Cookies.Append(Credentials.PASSWORD_KEY, dto.Password);
            }
            dto.Account.Balance = entity.Account.Balance;
            int userId = entity.UserId;

            entity         = DTOToUserEntity(dto, userId, id);
            entity.Id      = id;
            entity         = Repo.Update(entity);
            entity.User    = UserService.QuickUpdate(userId, dto);
            entity.Account = AccountService.QuickUpdate(entity.AccountId, dto.Account);
            return(EntityToDTO(entity));
        }
예제 #2
0
        private static string BuildComparisonLine(string name, System.Web.HttpCookieCollection a, IRequestCookieCollection b)
        {
            var result = new StringBuilder();

            result.AppendLine(BuildComparisonLine(name, a.Count, b.Count));

            foreach (var key in a.AllKeys)
            {
                if (b.ContainsKey(key))
                {
                    result.AppendLine(BuildComparisonLine(" " + key, a[key], b[key]));
                }
                else
                {
                    result.AppendLine(BuildComparisonLine(" " + key, a[key], "null"));
                }
            }

            foreach (var keyValue in b)
            {
                var valueFound = a.Get(keyValue.Key);
                if (valueFound == null)
                {
                    result.AppendLine(BuildComparisonLine(" " + keyValue.Key, "null", keyValue.Value));
                }
            }

            return(result.ToString());
        }
예제 #3
0
        public async Task <int?> LoggedInUserIdAsync(HttpContext context)
        {
            IRequestCookieCollection requestCookies = context.Request.Cookies;

            if (!requestCookies.ContainsKey("login"))
            {
                return(null);
            }

            string[] cookieParts = requestCookies["login"].Split(':');

            if (!long.TryParse(cookieParts[0], out long identifier))
            {
                return(null);
            }

            if (!await savedLoginRepository.ContainsIDAsync(identifier))
            {
                return(null);
            }

            string hex = cookieParts[1];

            byte[] unhashedToken = Enumerable.Range(0, hex.Length >> 1)
                                   .Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16))
                                   .ToArray();

            byte[] hashedToken;
            using (SHA256 sha256 = SHA256.Create())
            {
                hashedToken = sha256.ComputeHash(unhashedToken);
            }

            return(await savedLoginRepository.AuthenticatedUserAsync(identifier, hashedToken));
        }
예제 #4
0
 public AccountModel(IRequestCookieCollection cookies)
 {
     if (!cookies.ContainsKey("token") || string.IsNullOrEmpty(cookies["token"]))
     {
         return;
     }
     DatabaseManager.GetMain().FillUser(this, cookies["token"]);
 }
예제 #5
0
 public void LogOut(IRequestCookieCollection RequestCookies, HttpResponse Response)
 {
     if (RequestCookies.ContainsKey("AuthKey"))
     {
         var expirationDate = DateTime.MinValue.ToString("r");
         Response.Headers.Add("Set-Cookie", $"AuthKey=;Expires={expirationDate};Path=/");
     }
 }
예제 #6
0
        public static bool HasSkippedNotificationsCookie(this IRequestCookieCollection cookies, int adminId)
        {
            if (cookies.ContainsKey(CookieName))
            {
                return(cookies[CookieName] == adminId.ToString());
            }

            return(false);
        }
예제 #7
0
 public static bool TryGetValue <T>(this IRequestCookieCollection cookies, string key, out T result)
     where T : class
 {
     result = null;
     if (!cookies.ContainsKey(key))
     {
         return(false);
     }
     result = cookies.Get <T>(key);
     return(true);
 }
예제 #8
0
 public User GetUser(IRequestCookieCollection Cookies)
 {
     if (Cookies.ContainsKey("AuthKey"))
     {
         return(GetUser(Cookies["AuthKey"]));
     }
     else
     {
         return(null);
     }
 }
예제 #9
0
        private string GetOrSetUserCookie()
        {
            if (_requestCookies.ContainsKey(Constants.BASKET_COOKIENAME))
            {
                return(_requestCookies[Constants.BASKET_COOKIENAME]);
            }
            string anonymousId   = Guid.NewGuid().ToString();
            var    cookieOptions = new CookieOptions();

            cookieOptions.Expires = DateTime.Today.AddYears(10);
            _responseCookies.Append(Constants.BASKET_COOKIENAME, anonymousId, cookieOptions);
            return(anonymousId);
        }
    /// <summary>
    /// Restore the credentials from the session object, refresh if needed
    /// </summary>
    /// <returns></returns>
    public static async Task<Credentials> FromSessionAsync(IRequestCookieCollection requestCookie, IResponseCookies responseCookie)
    {
      if (requestCookie == null || !requestCookie.ContainsKey(FORGE_COOKIE)) return null;

      Credentials credentials = JsonConvert.DeserializeObject<Credentials>(requestCookie[FORGE_COOKIE]);
      if (credentials.ExpiresAt < DateTime.Now)
      {
        await credentials.RefreshAsync();
        responseCookie.Delete(FORGE_COOKIE);
        responseCookie.Append(FORGE_COOKIE, JsonConvert.SerializeObject(credentials));
      }

      return credentials;
    }
예제 #11
0
        public async Task <User> GetUserFromCookies(IRequestCookieCollection cookies)
        {
            if (cookies.ContainsKey("Token"))
            {
                string value = cookies["Token"];
                Token  token = await this.Token.Include(t => t.User).FirstOrDefaultAsync(t => t.Value == value);

                if (token != null)
                {
                    return(token.User);
                }
            }
            return(null);
        }
        private string getAuthCookie(ActionExecutingContext context, string authCookieKey = ".5173auth")
        {
            IRequestCookieCollection cookies = context.HttpContext.Request.Cookies;
            string auth5173Value             = string.Empty;

            if (cookies != null && cookies.Count > 0)
            {
                if (cookies.ContainsKey(authCookieKey))
                {
                    if (!cookies.TryGetValue(authCookieKey, out auth5173Value))
                    {
                        new Exception("没有 “5173auth” cookie").ToExceptionless().Submit();
                    }
                }
            }
            return(auth5173Value);
        }
예제 #13
0
        public void SetAndCheck(IRequestCookieCollection cookies)
        {
            Func <string, bool> IsAvailable = key =>
                                              cookies.ContainsKey(key) &&
                                              !String.IsNullOrEmpty(cookies[key]);

            if (new string[] { USER_TYPE_KEY, ID_KEY, PASSWORD_KEY }.All(IsAvailable))
            {
                string userType = cookies[USER_TYPE_KEY];
                int    id       = cookies[ID_KEY].ToInt();
                Password = cookies[PASSWORD_KEY];
                if (Password != Service(userType).FindEntity(id).User.Password)
                {
                    throw new AppException("Bad password", 400);
                }
                Credentials.Set(userType, id);
            }
        }
        public GanzAuthProvider(SessionManager sessionManager, IHttpContextAccessor httpProxy, IJSRuntime jsRuntime)
        {
            this.m_SessionManager = sessionManager;
            this.m_Http           = httpProxy;
            this.m_Javascript     = jsRuntime;

            if (this.m_Http.HttpContext != null)
            {
                IRequestCookieCollection cookies = this.m_Http.HttpContext.Request.Cookies;

                if (cookies.ContainsKey(AUTH_COOKIE))
                {
                    string cookie = cookies[AUTH_COOKIE];

                    this.CurrentSession = this.m_SessionManager.CheckTokenValidity(cookie);
                }
            }
        }
예제 #15
0
        public CookieHandler(
            IHttpContextAccessor httpContextAccessor, string cookieName, uint cookieLifeTimeHours)
        {
            if (string.IsNullOrWhiteSpace(cookieName))
            {
                throw new ArgumentException("does not contain valid cookie name", cookieName);
            }

            _requestCookies      = httpContextAccessor.HttpContext.Request.Cookies;
            _responseCookies     = httpContextAccessor.HttpContext.Response.Cookies;
            _cookieName          = cookieName;
            _cookieLifeTimeHours = cookieLifeTimeHours;
            _requestHasCookie    = _requestCookies.ContainsKey(_cookieName);

            _dictJsonCookie = _requestHasCookie
        ? new DictJson(_requestCookies[_cookieName])
        : new DictJson();
        }
        /// <summary>
        /// Restore the credentials from the session object, refresh if needed
        /// </summary>
        /// <returns></returns>
        public static async Task <Credentials> FromSessionAsync(IRequestCookieCollection requestCookie, IResponseCookies responseCookie)
        {
            if (requestCookie == null || !requestCookie.ContainsKey(FORGE_COOKIE))
            {
                return(null);
            }

            Credentials credentials = JsonConvert.DeserializeObject <Credentials>(requestCookie[FORGE_COOKIE]);

            if (credentials.ExpiresAt < DateTime.Now)
            {
                credentials = await FromDatabaseAsync(credentials.UserId);

                responseCookie.Delete(FORGE_COOKIE);
                responseCookie.Append(FORGE_COOKIE, JsonConvert.SerializeObject(credentials));
            }

            return(credentials);
        }
예제 #17
0
        public async Task LogoutAsync(HttpContext context)
        {
            IRequestCookieCollection requestCookies = context.Request.Cookies;

            if (!requestCookies.ContainsKey("login"))
            {
                return;
            }

            string[] cookieParts = requestCookies["login"].Split(':');

            if (!long.TryParse(cookieParts[0], out long identifier))
            {
                return;
            }

            Task deleteLogin = savedLoginRepository.DeleteAsync(identifier);

            context.Response.Cookies.Delete("login");
            await deleteLogin;
        }
예제 #18
0
        public void Logout(HttpContext context)
        {
            IRequestCookieCollection requestCookies = context.Request.Cookies;

            if (!requestCookies.ContainsKey("login"))
            {
                return;
            }

            string[] cookieParts = requestCookies["login"].Split(':');

            long identifier;

            if (!long.TryParse(cookieParts[0], out identifier))
            {
                return;
            }

            savedLoginRepository.Delete(identifier);
            context.Response.Cookies.Delete("login");
        }
예제 #19
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            IRequestCookieCollection cookies = context.HttpContext.Request.Cookies;

            if (cookies.ContainsKey("Token"))
            {
                string value = cookies["Token"];
                Token  token = _context.Token.Include(t => t.User).FirstOrDefault(t => t.Value == value);
                if (token != null)
                {
                    User user = token.User;
                    context.RouteData.Values.Add("User", user);
                    ViewBag.User = user;

                    return;
                }
            }

            context.RouteData.Values.Add("User", null);
            ViewBag.User = null;
        }
예제 #20
0
 public bool ContainsKey(string key) => _cookies.ContainsKey(key);