Esempio n. 1
0
        public ActionResult MeCache()
        {
            var key = "tkey";

            UserCache.Set(key, "测试数据");
            return(Succeed(UserCache.Get(key)));
        }
Esempio n. 2
0
        public async Task InvokeAsync(HttpContext context, UserCache userCache)
        {
            // currently ids are "protected" when sent to front end, so cant just paste in another players id as it hasn't been protected.
            var playerIdExists = context.Request.Cookies.ContainsKey("GHPID");

            var protector = DataProtectionProvider.Create("Gamehub.Web").CreateProtector("CookieEncryptPlayerId");

            string playerId = "";

            if (playerIdExists)
            {
                try
                {
                    playerId = protector.Unprotect(context.Request.Cookies["GHPID"]);
                }
                catch (Exception ex)
                {
                    // todo logging
                    playerId = Guid.NewGuid().ToString();
                }
            }
            else
            {
                playerId = Guid.NewGuid().ToString();
            }

            var userRequestMeta = new UserRequestMeta();

            var userProfile = userCache.Get(playerId);

            userRequestMeta.isSignedIn = userProfile != null;

            if (userProfile != null)
            {
                userRequestMeta.profile = userProfile;
            }
            else
            {
                userRequestMeta.profile = new User {
                    Id = playerId
                };
            }

            var protectedPlayerId = protector.Protect(playerId);

            // todo: encode datetime expire with cookie to help date tampering.
            // todo: perhaps remove ids and just use unique temporary names chosen on page load. check if in use like any other username.
            // consider signed jwts or something
            context.Response.Cookies.Append("GHPID", protectedPlayerId, new CookieOptions
            {
                HttpOnly = true,
                Expires  = DateTimeOffset.Now + TimeSpan.FromHours(1),
                SameSite = SameSiteMode.Strict
            });

            context.Items.Add("user", userRequestMeta);

            await _next(context);
        }
Esempio n. 3
0
        public async Task <long> Create(WorkCreateInput input)
        {
            var work     = input.MapTo <Deskwork>();
            var receiver = UserCache.Get(input.ReceiverId);

            work.CreateStep(new DeskworkStep(AbpSession.UserId.Value, AbpSession.GetCurrentUser().Name, input.ReceiverId, receiver.Name, receiver.OrganizationUnitName));
            return(await _workRepository.InsertAndGetIdAsync(work));
        }
 protected override string ResolveCore(string source)
 {
     if (!String.IsNullOrEmpty(source))
     {
         return(((ApplicationUser)_cache.Get(source)).FullName);
     }
     else
     {
         return("");
     }
 }
        public UserDto[] GetCachedUsers()
        {
            //var unexisted = UserCache.Get("UserTheFourth");

            return(new UserDto[]
            {
                UserCache.Get("UserthefIRST"),
                UserCache.Get("UserTheSecond"),
                UserCache.Get("UserThethirD"),
            });
        }
Esempio n. 6
0
        public ActionResult MeCache()
        {
            //测试
            var headersKeys = DemoWeb.HttpContext.Request.Headers.Keys;
            var token       = DemoWeb.HttpContext.Request.Headers["token"];
            var sid         = DemoWeb.HttpContext.Request.Headers["sid"];

            var key = "tkey";

            UserCache.Set(key, "测试数据");
            return(Succeed(UserCache.Get(key)));
        }
Esempio n. 7
0
        private void RemoveFromCacheArray <T> (string key, Guid toDeleteId, Func <Guid, T, bool> compare)
        {
            var cached = UserCache.Get <T[]> (key);

            if (cached != null && cached.Length > 0)
            {
                var list     = new List <T> (cached);
                var toDelete = list.SingleOrDefault(item => compare(toDeleteId, item));
                list.Remove(toDelete);
                UserCache.Set(key, list.ToArray());
            }
        }
Esempio n. 8
0
        public async Task <ReferenceData> GetReferenceData()
        {
            var cached = UserCache.Get <ReferenceData>(RefDataCacheKey);

            if (cached == null)
            {
                var refData = await UseServiceClientAsync <ReferenceDataServiceClient, ReferenceData>(service => service.GetReferenceData());

                UserCache.Set(RefDataCacheKey, refData, DateTime.Now.AddHours(1));
                return(refData);
            }
            return(cached);
        }
Esempio n. 9
0
        private async Task SetLastOrderIdIfNecessary(Guid orderId)
        {
            var lastOrderId = UserCache.Get <string>("LastOrderId");

            if (orderId != Guid.Empty && lastOrderId != orderId.ToString())
            {
                var order = await Mvx.Resolve <IAccountService>().GetHistoryOrderAsync(orderId);

                if (order != null && order.Status == apcurium.MK.Common.Entity.OrderStatus.Created)
                {
                    UserCache.Set("LastOrderId", orderId.ToString()); // Need to be cached as a string because of a jit error on device
                }
            }
        }
 public Guid GetUnratedLastOrder()
 {
     try
     {
         if (!HasUnratedLastOrder)
         {
             throw new InvalidOperationException();
         }
         var unratedLastOrderId = UserCache.Get <string>("LastUnratedOrderId");
         return(Guid.Parse(unratedLastOrderId));
     }
     catch (Exception e)
     {
         Logger.LogError(e);
         throw;
     }
 }
 public Task <OrderStatusDetail> GetLastOrderStatus()
 {
     try
     {
         if (!HasLastOrder)
         {
             throw new InvalidOperationException();
         }
         var lastOrderId = UserCache.Get <string>("LastOrderId");  // Need to be cached as a string because of a jit error on device
         return(UseServiceClientAsync <OrderServiceClient, OrderStatusDetail>(service => service.GetOrderStatus(new Guid(lastOrderId))));
     }
     catch (Exception e)
     {
         Logger.LogError(e);
         throw;
     }
 }
Esempio n. 12
0
        // GET: App
        public ActionResult Index()
        {
            // get appliction user
            var applicationUser = _userCache.Get(User.Identity.GetUserId());

            // set viewbag and cookie for frontend use
            ViewBag.AuthenticatedUser = AutoMapper.Mapper.Map <ApplicationUser, AuthenticatedUser>(applicationUser);
            HttpCookie cookie = new HttpCookie("AuthenticatedUser");

            cookie.Value = JsonConvert.SerializeObject(ViewBag.AuthenticatedUser, new JsonSerializerSettings()
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

            return(View());
        }
Esempio n. 13
0
        public ApplicationWebContext(TenantsCache tenantsCache, UserCache <ApplicationUser> userCache)
        {
            //TODO: Obtaining the client user name and IP address from HTTPContext makes an assumption that
            //      HTTPRequest is always available,this is not always the e.g. Application Start.  As a workaround,
            //      I have put in a try... catch block to handle situation where the HTTPRequest is not available.
            //      Futurewise, we need to refactor this to remove this dependency on the HTTPContext
            try
            {
                if ((HttpContext.Current.User != null) && (!String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name)))
                {
                    var user = userCache.Get(HttpContext.Current.User.Identity.GetUserId());
                    if (user != null)
                    {
                        this.ClientUserName     = user.UserName;
                        this.ClientUserId       = user.Id;
                        this.ClientUserFullName = user.FullName;
                    }
                }
                else
                {
                    this.ClientUserName = "******";
                }

                this.ClientIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                this.ClientTimeZone  = ClientTimeZoneHelper.UserTimeZone;
                string host = HttpContext.Current.Request.Headers["Host"].Split(':')[0];

                var tenant = tenantsCache.GetTenantByHost(host);
                if (tenant == null)
                {
                    // use default
                    tenant = tenantsCache.GetTenantByName("Default");
                }

                this.TenantID   = tenant.TenantId;
                this.DbServer   = tenant.DbServer;
                this.DbName     = tenant.DbName;
                this.DbUser     = tenant.DbUser;
                this.DbPassword = tenant.DbPassword;
                //this.Metadata = @"res://*/Models.TractionModel.csdl|res://*/Models.TractionModel.ssdl|res://*/Models.TractionModel.msl";
            }
            catch
            {
            }
        }
Esempio n. 14
0
        public async Task <Address[]> GetHistoryAddresses(CancellationToken cancellationToken = default(CancellationToken))
        {
            var cached = UserCache.Get <Address[]> (HistoryAddressesCacheKey);

            if (cached != null)
            {
                return(cached);
            }

            var result = await UseServiceClientAsync <IAccountServiceClient, IList <Address> >(s => s
                                                                                               .GetHistoryAddresses(CurrentAccount.Id))
                         .ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            UserCache.Set(HistoryAddressesCacheKey, result.ToArray());
            return(result.ToArray());
        }
Esempio n. 15
0
        public async Task <Address[]> GetFavoriteAddresses(CancellationToken cancellationToken = default(CancellationToken))
        {
            var cached = UserCache.Get <Address[]> (FavoriteAddressesCacheKey);

            if (cached != null && cached.Any())
            {
                return(cached);
            }

            var result = await UseServiceClientAsync <IAccountServiceClient, IEnumerable <Address> >(s => s
                                                                                                     .GetFavoriteAddresses())
                         .ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            var favoriteAddresses = result as Address[] ?? result.ToArray();

            UserCache.Set(FavoriteAddressesCacheKey, favoriteAddresses.ToArray());

            return(favoriteAddresses);
        }
Esempio n. 16
0
        public async Task <UserTaxiHailNetworkSettings> GetUserTaxiHailNetworkSettings(bool cleanCache = false)
        {
            var cachedSetting = UserCache.Get <UserTaxiHailNetworkSettings>(UserTaxiHailNetworkSettingsCacheKey);

            if (cachedSetting != null && !cleanCache)
            {
                return(cachedSetting);
            }

            try
            {
                var settings = await UseServiceClientAsync <IAccountServiceClient, UserTaxiHailNetworkSettings>(client => client.GetUserTaxiHailNetworkSettings(CurrentAccount.Id));

                UserCache.Set(UserTaxiHailNetworkSettingsCacheKey, settings);

                return(settings);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 17
0
        private void UpdateCacheArray <T> (string key, T updated, Func <T, T, bool> compare) where T : class
        {
            var cached = UserCache.Get <T[]> (key);

            if (cached != null)
            {
                var found = cached.SingleOrDefault(c => compare(updated, c));
                if (found == null)
                {
                    var newList = new T[cached.Length + 1];
                    Array.Copy(cached, newList, cached.Length);
                    newList [cached.Length] = updated;
                    UserCache.Set(key, newList);
                }
                else
                {
                    var foundIndex = cached.IndexOf(updated, compare);
                    cached [foundIndex] = updated;
                    UserCache.Set(key, cached);
                }
            }
        }
Esempio n. 18
0
        public IList <UserSummaryViewModel> Overview([FromBody] UserSummaryParam param)
        {
            //ApplicationUser user;
            // get user
            var applicationUser = _userCache.Get(User.Identity.GetUserId());

            // convert reportDate to UTC
            param.ReportDate = param.ReportDate.ToUniversalTime();

            var summaries = new List <UserSummaryViewModel>();

            foreach (var user in _userCache.GetAll())
            {
                summaries.Add(new UserSummaryViewModel
                {
                    UserId       = user.Id,
                    UserFullName = user.FullName
                });
            }

            var query = _repository.StatusReportItems.Where(i => DbFunctions.DiffDays(i.StatusReport.ReportDate, param.ReportDate) == 0).GroupBy(i => i.StatusReport.ReportingUserId);
            UserSummaryViewModel userSummary;

            foreach (IGrouping <string, StatusReportItem> item in query.ToList())
            {
                userSummary = summaries.Where(s => s.UserId == item.Key).SingleOrDefault();

                userSummary.InProgressWork          = item.Where(i => i.StatusReportCategory.Code == StatusReportCategoryCodes.InProgess).Count();
                userSummary.CompletedWork           = item.Where(i => i.StatusReportCategory.Code == StatusReportCategoryCodes.Completed).Count();
                userSummary.NotStartedWork          = item.Where(i => i.StatusReportCategory.Code == StatusReportCategoryCodes.NotStarted).Count();
                userSummary.Impediments             = item.Where(i => i.StatusReportCategory.Code == StatusReportCategoryCodes.Impediment).Count();
                userSummary.TimeSpentInSecs         = item.Sum(i => i.TimeSpentInSecs).Value;
                userSummary.MaxTimeAvailableInHours = 8;
            }
            ;
            return(summaries);
        }
Esempio n. 19
0
        public IUser GetUser(string login)
        {
            var key = login.Trim().ToLowerInvariant();

            return(UserCache.Get(key, InternalGetUser));
        }
Esempio n. 20
0
        public async Task <NotificationSettings> GetNotificationSettings(bool companyDefaultOnly = false, bool cleanCache = false)
        {
            var cachedSetting = companyDefaultOnly ? UserCache.Get <NotificationSettings>(CompanyNotificationSettingsCacheKey)
                                                   : UserCache.Get <NotificationSettings>(UserNotificationSettingsCacheKey);

            if (cachedSetting != null && !cleanCache)
            {
                return(cachedSetting);
            }

            var companySettings = await UseServiceClientAsync <CompanyServiceClient, NotificationSettings>(client => client.GetNotificationSettings());

            UserCache.Set(CompanyNotificationSettingsCacheKey, companySettings);

            if (companyDefaultOnly)
            {
                return(companySettings);
            }

            var userSettings = await UseServiceClientAsync <IAccountServiceClient, NotificationSettings>(client => client.GetNotificationSettings(CurrentAccount.Id));

            // Merge company and user settings together
            // If the value is not null in the company settings, this means the setting is active and visible to the user
            // we check if the user has a value otherwise we put the company default value (or null if set as "not available" by the company)
            var mergedSettings = new NotificationSettings
            {
                Id      = userSettings.Id,
                Enabled = companySettings.Enabled && userSettings.Enabled,
                BookingConfirmationEmail = companySettings.BookingConfirmationEmail.HasValue && userSettings.BookingConfirmationEmail.HasValue
                        ? userSettings.BookingConfirmationEmail
                        : companySettings.BookingConfirmationEmail,
                ConfirmPairingPush = companySettings.ConfirmPairingPush.HasValue && userSettings.ConfirmPairingPush.HasValue
                        ? userSettings.ConfirmPairingPush
                        : companySettings.ConfirmPairingPush,
                DriverAssignedPush = companySettings.DriverAssignedPush.HasValue && userSettings.DriverAssignedPush.HasValue
                        ? userSettings.DriverAssignedPush
                        : companySettings.DriverAssignedPush,
                DriverBailedPush = companySettings.DriverBailedPush.HasValue && userSettings.DriverBailedPush.HasValue
                                                ? userSettings.DriverBailedPush
                                                : companySettings.DriverBailedPush,
                NearbyTaxiPush = companySettings.NearbyTaxiPush.HasValue && userSettings.NearbyTaxiPush.HasValue
                        ? userSettings.NearbyTaxiPush
                        : companySettings.NearbyTaxiPush,
                PaymentConfirmationPush = companySettings.PaymentConfirmationPush.HasValue && userSettings.PaymentConfirmationPush.HasValue
                        ? userSettings.PaymentConfirmationPush
                        : companySettings.PaymentConfirmationPush,
                ReceiptEmail = companySettings.ReceiptEmail.HasValue && userSettings.ReceiptEmail.HasValue
                        ? userSettings.ReceiptEmail
                        : companySettings.ReceiptEmail,
                PromotionUnlockedEmail = companySettings.PromotionUnlockedEmail.HasValue && userSettings.PromotionUnlockedEmail.HasValue
                                                ? userSettings.PromotionUnlockedEmail
                                                : companySettings.PromotionUnlockedEmail,
                PromotionUnlockedPush = companySettings.PromotionUnlockedPush.HasValue && userSettings.PromotionUnlockedPush.HasValue
                                                ? userSettings.PromotionUnlockedPush
                                                : companySettings.PromotionUnlockedPush,
                VehicleAtPickupPush = companySettings.VehicleAtPickupPush.HasValue && userSettings.VehicleAtPickupPush.HasValue
                        ? userSettings.VehicleAtPickupPush
                        : companySettings.VehicleAtPickupPush,
                NoShowPush = companySettings.NoShowPush.HasValue && userSettings.NoShowPush.HasValue
                                                ? userSettings.NoShowPush
                                                : companySettings.NoShowPush
            };

            UserCache.Set(UserNotificationSettingsCacheKey, mergedSettings);
            return(mergedSettings);
        }