/// <summary> /// Configures an in-memory, time-based cache for the user service store. /// </summary> /// <param name="factory">The factory.</param> /// <param name="cacheDuration">Duration of the cache.</param> public static void ConfigureUserServiceCache(this IdentityServerServiceFactory factory, TimeSpan cacheDuration) { var cache = new DefaultCache <IEnumerable <Claim> >(cacheDuration); var cacheRegistration = new Registration <ICache <IEnumerable <Claim> > >(cache); factory.ConfigureUserServiceCache(cacheRegistration); }
public void When_adding_to_a_new_type_cache() { var cache = new DefaultCache(); cache.Add("test", "new", "{'type':'old value'}"); cache.Get("test", "new").ShouldBe("{'type':'old value'}"); }
/// <summary> /// Configures the default cache for the client store. /// </summary> /// <param name="factory">The factory.</param> public static void ConfigureClientStoreCache(this IdentityServerServiceFactory factory) { var cache = new DefaultCache <Client>(); var cacheRegistration = new Registration <ICache <Client> >(cache); factory.ConfigureClientStoreCache(cacheRegistration); }
public void Dispose() { DefaultCache.Reset(); DependencyResolver.Reset(); m_resolverMock.VerifyAll(); m_cacheMock.VerifyAll(); }
/// <summary> /// Configures the default cache for the scope store. /// </summary> /// <param name="factory">The factory.</param> public static void ConfigureScopeStoreCache(this IdentityServerServiceFactory factory) { var cache = new DefaultCache <IEnumerable <Scope> >(); var cacheRegistration = new Registration <ICache <IEnumerable <Scope> > >(cache); factory.ConfigureScopeStoreCache(cacheRegistration); }
public void Initialize_Twice_DoesThrow() { // Arrange // Act Assert.Throws <InvalidOperationException>(() => DefaultCache.InitializeWith(m_cacheMock.Object)); // Assert }
public void When_removing_from_a_cache() { var cache = new DefaultCache(); cache.Add("test", "new", "{'type':'old value'}"); cache.Remove("test", "new"); cache.Get("test", "new").ShouldBe(""); }
public void When_adding_to_a_type_cache_with_an_existing_id() { var cache = new DefaultCache(); cache.Add("test", "new", "{'type':'old value'}"); cache.Add("test", "new", "{'type':'new value'}"); cache.Get("test", "new").ShouldBe("{'type':'new value'}"); }
public IActionResult SendMobileCaptcha(string key) { if (string.IsNullOrEmpty(key)) { return(Content("请输入key")); } var val = DefaultCache.GetString(key); return(Content(val)); }
/// <summary> /// 校验短信验证码是否有效 /// </summary> /// <param name="guid">guid</param> /// <param name="mobile">手机号</param> /// <param name="captcha">验证码</param> /// <returns></returns> private bool ValidateSmsCaptcha(string guid, string mobile, string captcha) { if (string.IsNullOrEmpty(guid) || string.IsNullOrEmpty(mobile) || string.IsNullOrEmpty(captcha)) { return(false); } var key = $"{mobile}-{guid}"; return(DefaultCache.GetString(key) == captcha); }
public void Remove(string key) { // Arrange m_cacheMock.Setup(cache => cache.Remove(key)).Returns(true); // Act Assert.DoesNotThrow(() => DefaultCache.Remove(key)); // Assert }
public void Clear() { // Arrange m_cacheMock.Setup(cache => cache.Clear()).Returns(true); // Act DefaultCache.Clear(); // Assert }
public void Get(string key) { // Arrange m_cacheMock.Setup(cache => cache.Get <int>(key)).Returns(100); // Act var value = DefaultCache.Get <int>(key); // Assert Assert.Equal(100, value); }
public void Get_DataKey() { // Arrange var datakey = new DataKey <int>("key"); m_cacheMock.Setup(cache => cache.Get(datakey)).Returns(true); // Act DefaultCache.Get(datakey); // Assert }
public KeyVaultCache( IOptions <AzureKeyVaultTokenSigningServiceOptions> keyVaultOptions, IMemoryCache cache, ILogger <KeyVaultCache> logger) { _keyVaultOptions = keyVaultOptions.Value; _azureKeyVaultAuthentication = new AzureKeyVaultAuthentication(_keyVaultOptions.ClientId, _keyVaultOptions.ClientSecret); _cache = cache; _logger = logger; _cachedData = new DefaultCache <CacheData>(_cache); _cacheTimeStamp = new DefaultCache <TimeStamp>(_cache); }
public void When_clearing_a_cache() { var cache = new DefaultCache(); cache.Add("test", "old", "{'type':'old value'}"); cache.Add("test", "new", "{'type':'new value'}"); cache.Clear("test"); cache.Get("test", "old").ShouldBe(""); cache.Get("test", "new").ShouldBe(""); }
public void StoreExpiresAt_DataKey() { // Arrange var datakey = new DataKey <int>("key"); var expires = DateTime.Now; m_cacheMock.Setup(cache => cache.Store(datakey, expires)).Returns(true); // Act DefaultCache.Store(datakey, expires); // Assert }
public void StoreValidFor_DataKey() { // Arrange var datakey = new DataKey <int>("key"); var validFor = TimeSpan.FromMinutes(10); m_cacheMock.Setup(cache => cache.Store(datakey, validFor)).Returns(true); // Act DefaultCache.Store(datakey, validFor); // Assert }
public async Task <IActionResult> CaptchaSend(bool email) { var result = new Result <string>(); var id = GetIntSession("account-current"); if (!id.HasValue || id.Value < 1) { result.Message = "停留时间过长,请重新进行身份验证。"; return(Json(result)); } var u = DefaultStorage.UserGet(id.Value); if (email) { if (u.Email.IsNullOrEmpty()) { result.Message = "未绑定有效邮箱帐号,请选择其它方式进行身份验证。"; return(Json(result)); } // todo 发邮件 } else { if (u.Mobile.IsNullOrEmpty()) { result.Message = "未绑定有效手机号码,请选择其它方式进行身份验证。"; return(Json(result)); } // 发短信 var captcha = GenerateCaptcha(); var message = "注册验证码 " + captcha; var status = await smsService.SendMessage(u.Mobile, message, "注册验证码"); if (!status) { result.Message = "发送短信失败,请稍后再试!"; return(Json(result)); } result.Status = true; result.Message = status.Guid; var key = $"{u.Mobile}-pwd-{status.Guid}"; DefaultCache.SetString(key, captcha, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = new TimeSpan(0, 2, 0) }); return(Json(result)); } return(Json(result)); }
public void Store(string key, int value) { // Arrange m_cacheMock.Setup(cache => cache.Store(key, value)).Callback <string, object>((k, v) => { Assert.Equal(key, k); Assert.Equal(value, v); }) .Returns(true); // Act Assert.DoesNotThrow(() => DefaultCache.Store(key, value)); // Assert }
public async Task <IActionResult> SmsSend(string mobile) { var result = new Result(); var identity = User; if (!identity) { result.Message = "未登录或登录超时!"; return(Json(result)); } if (!mobile.IsMobile()) { result.Message = "请输入正确的手机号码!"; return(Json(result)); } var exist = DefaultStorage.UserExist(mobile); if (exist) { result.Message = "该手机号码已绑定其它帐号,请换个手机号码!"; return(Json(result)); } var captcha = GenerateCaptcha(); var message = "手机绑定验证码 " + captcha; var status = await smsService.SendMessage(mobile, "手机绑定验证码", message); if (!status) { result.Message = "发送短信失败,请稍后再试!"; return(Json(result)); } result.Status = true; result.Message = status.Guid; var key = $"{mobile}-{status.Guid}"; DefaultCache.SetString(key, captcha, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = new TimeSpan(0, 2, 0) }); return(Json(result)); }
public void StoreValidFor(string key, int value, string valid) { // Arrange var validFor = TimeSpan.Parse(valid, CultureInfo.InvariantCulture); m_cacheMock.Setup(cache => cache.Store(key, value, validFor)) .Callback <string, object, TimeSpan>((k, v, t) => { Assert.Equal(key, k); Assert.Equal(value, v); Assert.Equal(validFor, t); }) .Returns(true); // Act Assert.DoesNotThrow(() => DefaultCache.Store(key, value, validFor)); // Assert }
public void StoreExpiresAt(string key, int value, string expires) { // Arrange var expiresAt = DateTime.Parse(expires, CultureInfo.InvariantCulture); m_cacheMock.Setup(cache => cache.Store(key, value, expiresAt)) .Callback <string, object, DateTime>((k, v, e) => { Assert.Equal(key, k); Assert.Equal(value, v); Assert.Equal(expiresAt, e); }) .Returns(true); // Act Assert.DoesNotThrow(() => DefaultCache.Store(key, value, expiresAt)); // Assert }
public override int Execute() { var sb = new StringBuilder(); var paramters = new Dictionary <string, object>(); IEnumerable <KeyValuePair <string, string> > columns = typeRegions.ReadWrites; if (!(limits is null)) { columns = columns.Where(x => limits.Any(y => y == x.Key || y == x.Value)); } if (!(excepts is null)) { columns = columns.Where(x => !excepts.Any(y => y == x.Key || y == x.Value)); } if (!columns.Any()) { throw new DException("未指定插入字段!"); } sb.Append("INSERT INTO ") .Append(Settings.TableName(from?.Invoke(typeRegions) ?? typeRegions.TableName)) .Append("(") .Append(string.Join(",", columns.Select(x => Settings.Name(x.Value)))) .Append(")") .Append(" VALUES ") .Append(string.Join(",", this.Select((item, index) => { var context = new ValidationContext(item, null, null); return(string.Concat("(", string.Join(",", columns.Select(kv => { var storeItem = typeStore.PropertyStores.First(x => x.Name == kv.Key); var parameterKey = Settings.ParamterName($"{kv.Key.ToUrlCase()}_{index}"); var value = storeItem.Member.GetValue(item, null); if (typeRegions.Tokens.TryGetValue(kv.Key, out TokenAttribute token)) { if (value is null || storeItem.MemberType.IsValueType && Equals(value, DefaultCache.GetOrAdd(storeItem.MemberType, type => Activator.CreateInstance(type)))) { value = token.Create(); if (value is null) { throw new NoNullAllowedException("令牌不允许为空!"); } storeItem.Member.SetValue(item, value, null); } } context.MemberName = storeItem.Member.Name; Validator.ValidateValue(value, context, storeItem.Attributes.OfType <ValidationAttribute>()); paramters.Add(parameterKey, value); return parameterKey; })), ")")); }))); return(Editable.Excute(sb.ToString(), paramters)); }
/// <summary> /// Configures the default cache for the scope store. /// </summary> /// <param name="factory">The factory.</param> public static void ConfigureScopeStoreCache(this IdentityServerServiceFactory factory) { var cache = new DefaultCache<IEnumerable<Scope>>(); var cacheRegistration = new Registration<ICache<IEnumerable<Scope>>>(cache); factory.ConfigureScopeStoreCache(cacheRegistration); }
/// <summary> /// 行政区列表(从缓存里取 有效7天) /// </summary> /// <returns></returns> protected IList <Region> RegionList() { var key = "base-region"; return(DefaultCache.Put(key, () => DefaultStorage.RegionList(), DateTime.Now.AddDays(7))); }
/// <summary> /// 用户信息维护 /// </summary> /// <param name="source"></param> /// <returns></returns> public EmployeeDto AddOrUpdateEmployee(EmployeeDto source) { var isAddNew = string.IsNullOrEmpty(source.Id); if (isAddNew) { source.Id = Guid.NewGuid().ToString(); source.Password = EncryptUtil.Md5Hash(source.Password); var entity = Mapper.Map <EmployeeDto, Employee>(source); _dbContext.Set <Employee>().Add(entity); // 可访问机构 if (source.VisitMis != null && source.VisitMis.Count > 0) { foreach (var temp in source.VisitMis) { var emi = new EmployeeMi(); emi.Id = Guid.NewGuid().ToString(); emi.EmployeeId = source.Id; emi.MiId = temp.MiId; _dbContext.Set <EmployeeMi>().Add(emi); } } } else { var target = _dbContext.Set <Employee>().Where(s => s.Id == source.Id).FirstOrDefault(); if (target == null) { CommonFunc.ThrowExceptionIfRecordNotExists(EntityNames.User, source.Id, OperateType.Update, _logger); } else if (!Enumerable.SequenceEqual(source.Version, target.Version)) { var modifiedUser = GetEmployeeDetail(target.LastUpdateUserId); CommonFunc.ThrowExceptionIfRecordHasBeenModified(EntityNames.User, source.Id, modifiedUser.EmName, target.LastUpdateTime, OperateType.Update, _logger); } //若密码变更,重新加密 if (source.Password != target.Password) { source.Password = EncryptUtil.Md5Hash(source.Password); } Mapper.Map(source, target); // 可访问机构 var existsEmis = _dbContext.Set <EmployeeMi>().Where(s => s.EmployeeId == source.Id).ToList(); _dbContext.Set <EmployeeMi>().RemoveRange(existsEmis); if (source.VisitMis != null && source.VisitMis.Count > 0) { foreach (var temp in source.VisitMis) { var emi = new EmployeeMi(); emi.Id = Guid.NewGuid().ToString(); emi.EmployeeId = source.Id; emi.MiId = temp.MiId; _dbContext.Set <EmployeeMi>().Add(emi); } } } _dbContext.SaveChanges(); // 清除相关用户的可访问机构数据缓存 DefaultCache.ClearUserMiCache(source.Id); return(GetEmployeeDetail(source.Id)); }
/// <summary> /// Configures an in-memory, time-based cache for the user service store. /// </summary> /// <param name="factory">The factory.</param> /// <param name="cacheDuration">Duration of the cache.</param> public static void ConfigureUserServiceCache(this IdentityServerServiceFactory factory, TimeSpan cacheDuration) { var cache = new DefaultCache<IEnumerable<Claim>>(cacheDuration); var cacheRegistration = new Registration<ICache<IEnumerable<Claim>>>(cache); factory.ConfigureUserServiceCache(cacheRegistration); }
/// <summary> /// Configures the default cache for the client store. /// </summary> /// <param name="factory">The factory.</param> public static void ConfigureClientStoreCache(this IdentityServerServiceFactory factory) { var cache = new DefaultCache<Client>(); var cacheRegistration = new Registration<ICache<Client>>(cache); factory.ConfigureClientStoreCache(cacheRegistration); }
public DefaultCacheTest() { m_cacheMock = new Mock <ICache>(MockBehavior.Strict); DefaultCache.InitializeWith(m_cacheMock.Object); }
public static void DefaultConfiguration() { Settings = new DefaultSettings(); Cache = new DefaultCache(Settings); }
public void Dispose() { DefaultCache.Reset(); m_cacheMock.VerifyAll(); }
static EventBusConfiguration() { Cache = new DefaultCache(); Mapper = new TinyMapperMapper(); }
public void SetUp() { Cache = new DefaultCache(); FileCacheDependency = new DefaultFileCacheDependency(); }