public IActionResult SetListComplexObject() { List <SampleObject> lstSampleObject = new List <SampleObject>(); if (RedisCacheHelper.GetDatabase() != null) { lstSampleObject.Add(new SampleObject { Country = "Argentina", Id = 1, Name = "Maradona" }); lstSampleObject.Add(new SampleObject { Country = "Portugal", Id = 2, Name = "Ronaldo" }); lstSampleObject.Add(new SampleObject { Country = "Puskas", Id = 3, Name = "Hungary" }); RedisCacheHelper.Set("test2", lstSampleObject); } return(RedirectToActionPermanent("Index")); }
public async Task <string> GetRestaurantMenuItems(List <RestaurantMenu> menus, int _restaurantID, string pref = "BURGER") { string data = string.Empty; List <List <MenuDetails> > _menuDetails = new List <List <MenuDetails> >(); foreach (var menu in menus) { data = await GetDataAsync(ConfigurationManager.AppSettings["MenuByIdURL"] + menu.Id); Menu _menu = JsonConvert.DeserializeObject <Menu>(data); var menuItemsWithPref = _menu.MenuItemGroups.SelectMany( x => x.MenuItems .Where(y => y.Name.ToUpper().Contains(pref.ToUpper())) .Select(y => new MenuDetails { RestaurantID = _restaurantID, MenuItemId = y.Id, MenuItemName = y.Name, MenuName = menu.Name, DeliveryTypeCode = menu.DeliveryTypeCode }) ).ToList(); _menuDetails.Add((List <MenuDetails>)menuItemsWithPref); } //Creating the Cache Key as RestaurantID+PREF //For the assignment i am not converting this value to fixed lennth hash key string cacheKey = string.Format("{0}{1}", _restaurantID.ToString(), pref.ToUpper()); RedisCacheHelper.Set(GetCacheKey(_restaurantID, pref), _menuDetails); return(JsonConvert.SerializeObject(_menuDetails));; }
public ActionResult saveDataInRedis(string senderName, string receiverName, string msginput) { var lstSampleObject = RedisCacheHelper.Get <List <SampleObject> >("redisChat"); if (lstSampleObject == null) { lstSampleObject = new List <SampleObject> { new SampleObject { senderUName = senderName, receiverUName = receiverName, textMsg = msginput } }; } else { lstSampleObject.Add( new SampleObject { senderUName = senderName, receiverUName = receiverName, textMsg = msginput }); } RedisCacheHelper.Set("redisChat", lstSampleObject); return(Json(new { status = true })); }
public ActionResult <Account> GetAccounts(string name = "", string sort_type = "", int page_index = -1, string field_selected = "") { List <Object> list; if (string.IsNullOrEmpty(sort_type)) { sort_type = "asc"; } if (string.IsNullOrEmpty(field_selected)) { field_selected = "AccountId, NameAccount, EmailAccount, PhoneAccount, StatusId, RoleId"; } if (name == "" && sort_type == "asc" && page_index == -1 && field_selected == "AccountId, NameAccount, EmailAccount, PhoneAccount, StatusId, RoleId") { var result = RedisCacheHelper.Get("ListAccounts", _redisCache); if (result == null) { list = _accountService.getAccount(name, sort_type, page_index, ITEM_PER_PAGE, field_selected); if (list == null) { return(NotFound()); } else { var data = JsonConvert.SerializeObject(list); List <AccountDto> listDto = JsonConvert.DeserializeObject <List <AccountDto> >(data); RedisCacheHelper.Set("ListAccounts", listDto, _redisCache); return(Ok(list)); } } else { return(Ok(result)); } } else { list = _accountService.getAccount(name, sort_type, page_index, ITEM_PER_PAGE, field_selected); if (list.Count == 0) { return(NotFound()); } else { return(Ok(list)); } } }
public IActionResult SetSimpleComplexObject() { if (RedisCacheHelper.GetDatabase() != null) { SampleObject sampleObject = new SampleObject { Country = "Brazil", Id = 7, Name = "Mané" }; RedisCacheHelper.Set("test1", sampleObject); } return(RedirectToActionPermanent("Index")); }
public ActionResult EditConfig(int memberTypeId) { var entity = _memberTypeContract.Edit(memberTypeId); if (entity == null) { return(Json(OperationResult.Error("会员类型不存在"))); } var res = RedisCacheHelper.Set(RedisCacheHelper.EnterpriseMemberTypeId, memberTypeId); if (!res) { return(Json(OperationResult.Error("绑定失败"))); } return(Json(OperationResult.OK())); }
public IQueryable <T_Category> GetAllCategories() { if (!RedisCacheHelper.Exist("Categories")) { RedisCacheHelper.Set("Categories", dal.LoadEntities(c => true)); } else { var category = RedisCacheHelper.Get <IQueryable <T_Category> >("Categories"); if (category == null) { RedisCacheHelper.Set("Categories", dal.LoadEntities(c => true)); } } return(RedisCacheHelper.Get <IQueryable <T_Category> >("Categories")); }
public List <string> GetList() { var cacheKey = "list"; var lista = RedisCache.Get <List <string> >(cacheKey); if (lista != null) { return(lista); } else { RedisCache.Set(cacheKey, new List <string> { "pippo", "pluto", "paperino" }, 60); return(RedisCache.Get <List <string> >(cacheKey)); } }
private void RedisLock(string name = "") { string lock_data = RedisCacheHelper.Get(name); if (string.IsNullOrEmpty(lock_data)) { var tmp = RedisCacheHelper.Set(name, "1", 100); } else { while (true) { lock_data = RedisCacheHelper.Get(name); if (string.IsNullOrEmpty(lock_data)) { break; } System.Threading.Thread.Sleep(500); } } }
public async Task <ApiResult <string> > Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { #region 1. 从缓存获取公钥私钥解密,再解密密码 //获得公钥私钥,解密 var rsaKey = MemoryCacheHelper.Get <List <string> >(KeyModel.LoginKey); if (rsaKey == null) { apiRes.msg = "登录失败,请刷新浏览器再次登录"; return(apiRes); } //Ras解密密码 var ras = new RSAEncrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); #endregion #region 2. 判断用户登录次数限制以及过期时间 //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(Appsettings.Configuration[KeyModel.LoginCount]); //获得登录次数和过期时间 SysAdminLoginConfig loginConfig = MemoryCacheHelper.Get <SysAdminLoginConfig>(KeyModel.LoginCount) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { apiRes.msg = "您的登录以超过设定次数,请稍后再次登录~"; return(apiRes); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #endregion #region 3. 从数据库查询该用户 //查询登录结果 var dbres = _adminService.LoginAsync(parm).Result; if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(Appsettings.Configuration[KeyModel.LogindElayMinute]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); apiRes.msg = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(apiRes); } //记录登录次数,保存到session MemoryCacheHelper.Set(KeyModel.LoginCount, loginConfig); //提示用户错误和登录次数信息 apiRes.msg = dbres.msg + " 您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数"; return(apiRes); } #endregion #region 4. 设置Identity User信息 var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.ID), new Claim(ClaimTypes.Role, user.RoleId), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.RelName), new Claim(ClaimTypes.WindowsAccountName, user.Account), new Claim(ClaimTypes.UserData, user.LastLoginTime.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); if (Appsettings.Configuration[KeyModel.LoginSaveUser] == "Session") {//如果保存用户类型是Session,则默认设置cookie退出浏览器 清空,并且保存用户信息 await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { AllowRefresh = false }); } else { //根据配置保存浏览器用户信息,小时单位 var hours = int.Parse(Appsettings.Configuration[KeyModel.LoginCookieExpires]); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(hours), IsPersistent = true, AllowRefresh = false }); } #endregion #region 5. 保存权限信息到缓存 if (dbres.data.menu != null) { var menuSaveType = Appsettings.Configuration[KeyModel.LoginAuthorize]; if (menuSaveType == "Redis") { RedisCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } else { MemoryCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } } #endregion #region 6. 生成token信息,并且返回给前端 token = JwtHelper.IssueToken(new TokenModel() { UserID = user.ID, UserName = user.RelName, UserAccount = user.Account, Role = "AdminPolicy", ProjectName = "DL.Admin" }); MemoryCacheHelper.Del <string>(KeyModel.LoginKey); MemoryCacheHelper.Del <string>(KeyModel.LoginCount); #endregion #region 7. 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 1, Message = "登录", Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (Exception ex) { apiRes.msg = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 4, Message = "登录失败!" + ex.Message, Exception = ex.Message, Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(apiRes); }
public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 //如果需要验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(RedisAttribute)) is RedisAttribute) { var attributes = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(RedisAttribute)); var attributesType = ((RedisAttribute)attributes).Type; var attributesTimeout = ((RedisAttribute)attributes).Timeout; var attributesKey = GetRedisKey(invocation); var attributesData = ((RedisAttribute)attributes).Data; switch (attributesType) { case RedisAttributeType.Query: var ret = RedisCacheHelper.Get <object>(attributesKey); if (ret != null) { invocation.ReturnValue = ret; } else { invocation.Proceed(); if (invocation.ReturnValue != null) { RedisCacheHelper.Set(attributesKey, invocation.ReturnValue, attributesTimeout); } } break; case RedisAttributeType.Insert: invocation.Proceed(); if (invocation.ReturnValue != null && invocation.ReturnValue.ObjectToBool() == true) { var data = dic[attributesData]; RedisCacheHelper.Set(attributesKey, data, attributesTimeout); } break; case RedisAttributeType.Update: invocation.Proceed(); if (invocation.ReturnValue != null && invocation.ReturnValue.ObjectToBool() == true) { var data = dic[attributesData]; RedisCacheHelper.Set(attributesKey, data, attributesTimeout); } break; case RedisAttributeType.Delete: invocation.Proceed(); if (invocation.ReturnValue != null && invocation.ReturnValue.ObjectToBool() == true) { RedisCacheHelper.Del(attributesKey); } break; case RedisAttributeType.Refresh: break; } } else { invocation.Proceed();//直接执行被拦截方法 } }
/// <summary> /// 用户注册 /// </summary> /// <returns></returns> public Result <dynamic> Register(MemberRegisterRequest ent) { #region 数据验证 var result = new Result <dynamic>(); if (ent.mobile_phone.IsNullOrEmpty()) { result.Message = "用户手机号码不能为空"; return(result); } if (ent.display_name.IsNullOrEmpty()) { result.Message = "用户昵称不能为空"; return(result); } var exists = MemberRepository.Exists(ent.mobile_phone); if (exists.HasValue) { if (exists.Value) { result.Message = "存在相同的手机号码"; } } else { result.Message = "查询数据库异常"; } if (!string.IsNullOrEmpty(result.Message)) { result.Code = ResultCode.Error; return(result); } var smsService = new SmsService(); var sms = smsService.VerifySmsCode(ent.mobile_phone, 1, ent.mobile_code); if (sms.Code != ResultCode.Success) { return(sms); } #endregion MemberModel entity = new MemberModel() { MobilePhone = ent.mobile_phone, Portrait = string.Empty, EncryptedPwd = SecurityHelper.Encrypt(ent.pass_word), DisplayName = ent.display_name, Gender = ent.gender, LocationArea = ent.location_area, Birthday = ent.birthday, AccountBalance = 0, AmountTotal = 0, AmountWithdrawn = 0, TotalScore = 0, TotalWithdrawScore = 0, JpushId = string.Empty, OpenidWxMp = string.Empty, OpenidWxOpen = string.Empty, Status = 0, CreateTime = DateTime.Now, UpdateTime = DateTime.Now }; var member = MemberRepository.Add(entity); if (member.Id > 0) { string token = Guid.NewGuid().ToString().Replace("-", "").ToLower(); var cache = new RedisCacheHelper <Model.Member>(); cache.Set(token, new Model.Member() { id = entity.Id, display_name = entity.DisplayName }, TimeSpan.FromDays(5)); result.Message = "注册成功"; result.Code = ResultCode.Success; result.Data = new MemberLoginResponse { id = member.Id, mobile = member.MobilePhone, portrait = member.Portrait, display_name = member.DisplayName, gender = member.Gender, location_area = member.LocationArea, birthday = member.Birthday, account_balance = member.AccountBalance, amount_total = member.AmountTotal, amount_withdrawn = member.AmountWithdrawn, total_score = member.TotalScore, total_withdraw_score = member.TotalWithdrawScore, token = token }; } else { result.Code = ResultCode.Error; result.Message = "数据库操作异常"; } return(result); }
/// <summary> /// 用户登录 /// </summary> /// <returns></returns> public Result <dynamic> Login(string mobile, string password) { #region 数据验证 var result = new Result <dynamic>(); if (mobile.IsNullOrEmpty()) { result.Code = ResultCode.Error; result.Message = "登录账号不能为空"; return(result); } if (password.IsNullOrEmpty()) { result.Code = ResultCode.Error; result.Message = "登录密码不能为空"; return(result); } #endregion var encryptedPwd = SecurityHelper.Encrypt(password); var member = MemberRepository.Get(mobile); if (member != null) { if (member.EncryptedPwd != encryptedPwd) { result.Code = ResultCode.Error; result.Message = "账号或者密码错误"; } string token = Guid.NewGuid().ToString().Replace("-", "").ToLower(); var cache = new RedisCacheHelper <Model.Member>(); cache.Set(token, new Model.Member() { id = member.Id, display_name = member.DisplayName }, TimeSpan.FromDays(5)); result.Code = ResultCode.Success; result.Message = "登录成功"; result.Data = new MemberLoginResponse { id = member.Id, mobile = member.MobilePhone, portrait = member.Portrait, display_name = member.DisplayName, gender = member.Gender, location_area = member.LocationArea, birthday = member.Birthday, account_balance = member.AccountBalance, amount_total = member.AmountTotal, amount_withdrawn = member.AmountWithdrawn, total_score = member.TotalScore, total_withdraw_score = member.TotalWithdrawScore, token = token }; } else { result.Code = ResultCode.Error; result.Message = "数据库操作异常"; } return(result); }
public JwtAuthorizationDto CreateJwtToken(TokenModel tokenModel) { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); //秘钥 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); DateTime authTime = DateTime.UtcNow; DateTime expiresAt = authTime; #region 计算jwt有效时间 //过期时间 int exp = 0; switch (tokenModel.TokenType.ToLower()) { case "web": exp = jwtConfig.WebExp; break; case "app": exp = jwtConfig.AppExp; break; case "miniprogram": exp = jwtConfig.MiniProgramExp; break; case "other": exp = jwtConfig.OtherExp; break; } switch (tokenModel.EffectiveTimeType) { case "year": expiresAt = expiresAt.AddYears(exp); break; case "month": expiresAt = expiresAt.AddMonths(exp); break; case "day": expiresAt = expiresAt.AddDays(exp); break; case "hours": expiresAt = expiresAt.AddHours(exp); break; case "min": expiresAt = expiresAt.AddMinutes(exp); break; case "sec": expiresAt = expiresAt.AddSeconds(exp); break; } #endregion //将用户信息添加到 Claim 中 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); IEnumerable <Claim> claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //用户Id new Claim(ClaimTypes.Role, tokenModel.Role), //身份 new Claim("Project", tokenModel.Project), //项目名称 new Claim(JwtRegisteredClaimNames.Iat, authTime.ToString(), ClaimValueTypes.Integer64), new Claim(ClaimTypes.Expiration, expiresAt.ToString()) //过期时间 }; identity.AddClaims(claims); //签发一个加密后的用户信息凭证,用来标识用户的身份 _httpContextAccessor.HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); //生成jwt token var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), //创建声明信息 Issuer = jwtConfig.Issuer, //Jwt token 的签发者 Audience = jwtConfig.Audience, //Jwt token 的接收者 Expires = expiresAt, //过期时间 SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256) //创建 token }; var tokenInfo = tokenHandler.CreateToken(tokenDescriptor); string tokenStr = tokenHandler.WriteToken(tokenInfo); //存储 Token 信息 var jwt = new JwtAuthorizationDto { UserId = Guid.NewGuid().ToString(), Token = tokenStr, Auths = new DateTimeOffset(authTime).ToUnixTimeSeconds(), Expires = new DateTimeOffset(expiresAt).ToUnixTimeSeconds(), Success = true }; //写入Redis redisCacheHelper.Set(tokenStr, tokenModel, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(Convert.ToDouble(jwtConfig.WebExp)) }); return(jwt); }
private dynamic Autherize(HttpContext context) { dynamic resp = new ExpandoObject(), response = new ExpandoObject(); resp.IsValid = false; try { string sessionID = context.Request?.Headers["Authorization"]; if ((sessionID == null) || (!sessionID.Contains("Bearer "))) { resp.Message = "Missing session info in Header/Please validate format 'Bearer<Space><SessionId>'"; resp.StatusCode = 401; LogManager.Log(resp.Message, LogType.Error); } else { sessionID = sessionID.Split(" ")[1]; if (RedisCacheHelper.GetDatabase() != null) { dynamic Rc = RedisCacheHelper.Get(sessionID); if (Rc == null) { response = UserFacade.ValidateSession(sessionID); if ((!response.Success) || (response.Data.GetType() != typeof(Newtonsoft.Json.Linq.JObject)) || (!(bool)response.Data.isValid)) { resp.Message = "Invalid Session"; resp.StatusCode = 401; LogManager.Log("Invalid Session sessionID " + sessionID, LogType.Error); } else { RedisCacheHelper.Set(sessionID, response.Data); resp.IsValid = true; resp.UserInfo = response.Data; } } else { resp.IsValid = true; resp.UserInfo = Rc; } } else { resp.Message = "Internal Server Error"; resp.StatusCode = 500; LogManager.Log("Redis Connection Failure ", LogType.Error); } } } catch (Exception ex) { resp.IsValid = false; resp.Message = ex.Message; resp.StatusCode = 500; LogManager.Log(ex, LogType.Error); } context.Request.Headers.Add("SessionData", (string)CommonUtils.JsonSerialize(resp)); return(context); }