Esempio n. 1
0
        public CaptchaHelperModel SendAuthCode(CaptchaEnum captchaEnum, int accId, CaptchaPhoneEmailEnum typeEnum,
                                               string phoneOrEmail)
        {
            var redisCacheService = new RedisCacheService();

            if (string.IsNullOrWhiteSpace(phoneOrEmail))
            {
                throw new ArgumentNullException("phoneOrEmail", "手机号码邮箱地址为空");
            }


            //获取失败次数
            var strWrongTimesKey = GetWrongTimesKey(captchaEnum, accId);



            int iWrongTimes = redisCacheService.Get <int>(strWrongTimesKey);

            //判断验证码错误次数
            if (iWrongTimes > _checkWrongTimes)
            {
                return(new CaptchaHelperModel(false, "验证码错误次数过多,请1小时后重试或联系客服", typeEnum));
            }

            //获取验证码key
            var strCaptchaKey = GetCaptchaKey(captchaEnum, accId, phoneOrEmail);

            if (string.IsNullOrEmpty(strCaptchaKey))
            {
                return(new CaptchaHelperModel(false, "错误的手机号或邮箱", typeEnum));
            }


            //判断是否之前发过验证码
            int iCaptcha = redisCacheService.Get <int>(strCaptchaKey);

            if (iCaptcha == 0)
            {
                iCaptcha = Helper.GetInt32(Helper.GetRandomNum(), 111111);
            }

            var smsStr = string.Format("【生意专家】您本次获取的验证码为:{0},此验证码{1}分钟内有效。维护您的数据安全是生意专家义不容辞的责任。", iCaptcha,
                                       _outTimeMinutes);
            var mailSend = new EmailSend();
            var smsSend  = new SmsSend();
            var result   = typeEnum == CaptchaPhoneEmailEnum.Phone
                ? smsSend.SendSys(phoneOrEmail, smsStr, 13)
                : mailSend.SendVerifiEmail(accId, "", phoneOrEmail, iCaptcha.ToString());

            if (result)
            {
                _logger.Debug("发送验证码成功:" + iCaptcha);
                redisCacheService.Set(strCaptchaKey, iCaptcha, _outTimeMinutes * 60);
                return(new CaptchaHelperModel(true, "发送验证码成功", CaptchaPhoneEmailEnum.Email));
            }
            else
            {
                return(new CaptchaHelperModel(false, "发送失败", CaptchaPhoneEmailEnum.Email));
            }
        }
Esempio n. 2
0
        public bool IsHasDailyMaterialCoupon(int accId, int groupId)
        {
            string key = RedisConsts.DailyMaterialCoupon + groupId.ToString() + accId.ToString();
            var    redisCacheService = new RedisCacheService();
            var    redisvalue        = redisCacheService.Get(key);

            return(redisvalue != "True");
        }
        /// <summary>
        ///     获取城市列表(包括省列表、城市列表)
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetProvinceCityList()
        {
            var catchTime         = 1440 * 60;
            var redisCacheService = new RedisCacheService();

            return(new ResponseModel
            {
                Code = (int)ErrorCodeEnum.Success,
                Data = redisCacheService.Get(RedisConsts.ConstructedProvinceCityList, () =>
                {
                    {
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            var basedata = redisCacheService.Get(RedisConsts.AddressBaseData, catchTime,
                                                                 GetAllProvinceFromDb);
                            // 获取省列表
                            var provinceList = basedata.Where(a => a.Level == 1);
                            var result = new Address.RetAddressData();

                            // 遍历省列表追加市列表
                            foreach (var province in provinceList)
                            {
                                var provinceSelfId = province.SelfId;
                                var provinceModel = new Address.Province {
                                    Id = province.Id, Name = province.Name
                                };
                                result.ProvinceList.Add(provinceModel);

                                var cities = basedata.Where(a => a.Level == 2 && a.ParentId == provinceSelfId);
                                result.CityList.Add(new Address.City
                                {
                                    ProvinceId = province.Id,
                                    CityValues =
                                        cities.Select(c => new Address.CityValues {
                                        CityId = c.Id, CityName = c.Name
                                    })
                                        .ToList()
                                });
                            }

                            return result;
                        }
                    }
                })
            });
        }
Esempio n. 4
0
        public CaptchaHelperModel CheckCaptchaCode(CaptchaEnum captchaEnum, int accId, CaptchaPhoneEmailEnum typeEnum,
                                                   int captchaCode, string phoneOrEmail)
        {
            var redisCacheService = new RedisCacheService();
            CaptchaHelperModel model;

            //获取失败次数
            var strWrongTimesKey = GetWrongTimesKey(captchaEnum, accId);
            int iWrongTimes      = redisCacheService.Get <int>(strWrongTimesKey);

            //判断验证码错误次数
            if (iWrongTimes > 10)
            {
                return(new CaptchaHelperModel(false, "验证码错误次数过多,请1小时后重试或联系客服", typeEnum));
            }

            //获取验证码key
            string strCaptchaKey = GetCaptchaKey(captchaEnum, accId, phoneOrEmail);

            if (string.IsNullOrWhiteSpace(strCaptchaKey))
            {
                return(new CaptchaHelperModel(false, "验证码校验失败", typeEnum));
            }

            //获取发过的验证码
            int iCaptcha = redisCacheService.Get <int>(strCaptchaKey);

            if (iCaptcha == captchaCode)
            {
                _logger.Debug("验证验证码成功:" + iCaptcha);
                redisCacheService.RemoveKey(strWrongTimesKey);
                redisCacheService.RemoveKey(strCaptchaKey);
                return(new CaptchaHelperModel(true, "验证码校验成功", typeEnum));
            }
            else if (iCaptcha == 0)
            {
                _logger.Debug("验证验证码失败:" + captchaCode);
                return(new CaptchaHelperModel(false, "验证码过期,请重新申请发送验证码", typeEnum));
            }
            else
            {
                //失败添加失败次数
                redisCacheService.Set(strWrongTimesKey, iWrongTimes + 1, 60 * 60);
                return(new CaptchaHelperModel(false, "验证码校验失败", typeEnum));
            }
        }
        /// <summary>
        ///     获取支出分类
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetExpensesCategory(UserContext userContext)
        {
            var setCatchKey       = string.Format("I200:{0}:{1}", RedisConsts.PayClassList, userContext.AccId);
            var redisCacheService = new RedisCacheService();
            var data = redisCacheService.Get <PayClassResult>(setCatchKey);

            return(new ResponseModel
            {
                Code = (int)ErrorCodeEnum.Success,
                Data = data ?? GetExpensesCategoryFromDb(userContext)
            });
        }
Esempio n. 6
0
        /// <summary>
        /// 更新远程redis缓存到本地
        /// </summary>
        /// <param name="key"></param>
        public void UpdateLocalConfig(string key)
        {
            var redisCacheService = new RedisCacheService();

            if (!redisCacheService.HasKey(key))
            {
                throw new YuanbeiException("config key {0} not existed in redis", key);
            }

            string val = redisCacheService.Get <string>(key);

            _localCache.Set(key, val, _configLastMinutes);
        }
Esempio n. 7
0
        public async Task <ResponseMessage> ExecuteRedisCommand(Command command)
        {
            if (command.DatabaseId == null)
            {
                return(new ResponseMessage
                {
                    Status = Status.fail,
                    Error = "No Database Id provided."
                });
            }

            var data = string.Empty;
            RedisCacheService redisCacheService = new RedisCacheService(command);

            try
            {
                switch (command.CommandType)
                {
                case CommandType.ClearAll:
                    await redisCacheService.Clear();

                    break;

                case CommandType.GetValue:
                    data = await redisCacheService.Get();

                    break;

                case CommandType.Remove:
                    await redisCacheService.Remove();

                    break;
                }
            }
            catch (Exception ex)
            {
                return(new ResponseMessage
                {
                    Status = Status.fail,
                    Error = ex.Message
                });
            }

            return(new ResponseMessage
            {
                Status = Status.success,
                Data = !string.IsNullOrEmpty(data) ? data : null
            });
        }
Esempio n. 8
0
        public IEnumerable <WeatherForecast> Get()
        {
            var key = $"{nameof(WeatherForecastController)}:{nameof(Get)}";

            _logger.LogDebug("attempting to retrieve weather information using cache key {key}", key);

            //cache-aside pattern
            var weather = _redisCacheSvc.Get <WeatherForecast[]>(key);

            if (weather is null || weather.Length == 0)
            {
                _logger.LogWarning("cache item with cache key {key} doesn't exist", key);
                weather = GenerateWeather();
                _redisCacheSvc.Set(key, weather, TimeSpan.FromSeconds(10));//cache for n seconds
                _logger.LogInformation("item added with cache key {key} and data {data}", key, weather);
            }
Esempio n. 9
0
        public ResponseModel UpdatePassword(string cipherEmailId, string Password)
        {
            ResponseModel objResponseModel = new ResponseModel();

            try
            {
                StoreSecurityCaller newSecurityCaller = new StoreSecurityCaller();

                CommonService commonService = new CommonService();

                EmailProgramCode bsObj            = new EmailProgramCode();
                string           encryptedEmailId = commonService.Decrypt(cipherEmailId);
                if (encryptedEmailId != null)
                {
                    bsObj = JsonConvert.DeserializeObject <EmailProgramCode>(encryptedEmailId);
                }

                string _data = "";
                if (bsObj.ProgramCode != null)
                {
                    // bsObj.ProgramCode = SecurityService.DecryptStringAES(bsObj.ProgramCode);

                    RedisCacheService cacheService = new RedisCacheService(_radisCacheServerAddress);
                    if (cacheService.Exists("Con" + bsObj.ProgramCode))
                    {
                        _data = cacheService.Get("Con" + bsObj.ProgramCode);
                        _data = JsonConvert.DeserializeObject <string>(_data);
                    }
                }
                bool isUpdate = newSecurityCaller.UpdatePassword(new StoreSecurityService(_data), bsObj.EmailID, Password);

                if (isUpdate)
                {
                    objResponseModel.Status       = true;
                    objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.Success;
                    objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.Success);
                    objResponseModel.ResponseData = "Update password successfully";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
Esempio n. 10
0
        public string GetConfig(string key)
        {
            if (_localCache.IsSet(key))
            {
                return(_localCache.Get <string>(key));
            }

            var redisCacheService = new RedisCacheService();

            if (!redisCacheService.HasKey(key))
            {
                throw new YuanbeiException("config key {0} not existed in redis", key);
            }

            string val = redisCacheService.Get <string>(key);

            _localCache.Set(key, val, _configLastMinutes);
            return(val);
        }
        public HttpResponseMessage Get()
        {
            try
            {
                var result = redisCache.Get <ConfigurationViewModel>(1);
                if (result == null)
                {
                    var data = _iConfigurationRepo.Get(GlobalVariables.Id_Configuration);
                    result = Mapper.Map <ConfigurationViewModel>(data);

                    //MemoryCacheObject.CacheObject(ObjectCacheProfile.CACHE_SPA_CONFIG, result);
                    redisCache.Add <ConfigurationViewModel>(result);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
        /// <summary>
        /// redis获取商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        private MaterialGoodsInfo GetMaterialGoodsDetails(int goodsId)
        {
            MaterialGoodsInfo entity;
            string            key = RedisConsts.MaterialGoodsInfo + goodsId;
            var redisCacheService = new RedisCacheService();

            if (redisCacheService.HasKey(key))
            {
                entity = redisCacheService.Get <MaterialGoodsInfo>(key);
            }
            else
            {
                entity = GetMaterialGoodsDb(goodsId);
                //Insert Cache 7days
                Task.Factory.StartNew(() =>
                {
                    redisCacheService.Set(key, entity, 60 * 60 * 24 * 7);
                });
            }
            return(entity);
        }
        /// <summary>
        /// 根据ID获取硬件商品相应数据
        /// 新方法更快
        /// </summary>
        /// <param name="gidInts"></param>
        /// <returns></returns>
        private List <IndexMaterialGoods> GetIndexMaterialGoodses2(IEnumerable <int> gidInts)
        {
            var rList     = new List <IndexMaterialGoods>();
            var mList     = new List <MaterialGoodsInfo>();
            var goodsList = GetMaterialGoodsIdList();

            if (goodsList.Any() && gidInts.Any())
            {
                var redisCacheService = new RedisCacheService();
                mList =
                    redisCacheService
                    .Get <MaterialGoodsInfo>(
                        gidInts.Select(x => RedisConsts.MaterialGoodsInfo + x.ToString()).ToArray())
                    .ToList();
                if (gidInts.Count() != mList.Count)
                {
                    mList.AddRange(
                        gidInts
                        .Except(mList.Select(x => x.GoodsId))
                        .Select(GetMaterialGoodsDetails)
                        );
                }
            }
            if (mList.Any())
            {
                rList.AddRange(mList.Select(goods => new IndexMaterialGoods
                {
                    Id         = goods.Id,
                    GoodsId    = goods.GoodsId,
                    AliasName  = goods.AliasName,
                    Price      = goods.Price,
                    Status     = goods.Status,
                    RankNo     = goods.RankNo,
                    ClassId    = goods.ClassId,
                    CoverImage = goods.CoverImage
                }));
                return(rList.OrderBy(x => x.RankNo).ToList());
            }
            return(null);
        }
        /// <summary>
        /// redis获取商品列表
        /// </summary>
        /// <returns></returns>
        private IEnumerable <MaterialGoodsListRedisItem> GetMaterialGoodsIdList()
        {
            IEnumerable <MaterialGoodsListRedisItem> rModel;
            string key = RedisConsts.MaterialGoodsList;
            var    redisCacheService = new RedisCacheService();

            if (redisCacheService.HasKey(key))
            {
                rModel = redisCacheService.Get <List <MaterialGoodsListRedisItem> >(key);
            }
            else
            {
                rModel = Mapper.Map <IEnumerable <T_MaterialGoods2>, IEnumerable <MaterialGoodsListRedisItem> >(_materialGoods.FindAll());

                //Insert Cache 7days
                Task.Factory.StartNew(() =>
                {
                    redisCacheService.Set(key, rModel, 60 * 60 * 24 * 7);
                });
            }
            return(rModel);
        }
Esempio n. 15
0
        public IActionResult Index()
        {
            //var cacheKey = "key";
            //string result;
            //if(string.IsNullOrWhiteSpace(_memoryCache.GetString(cacheKey)))
            //{
            //    result = DateTime.Now.ToString();
            //    _memoryCache.SetString(cacheKey, result);
            //}
            var cacheKey = "key";

            if (_cache.Exists(cacheKey))
            {
                var cacheValue = _cache.Get <string>(cacheKey);
                return(Content(cacheValue));
            }
            else
            {
                _cache.Add(cacheKey, DateTime.Now.ToString());
                return(View());
            }
        }
        /// <summary>
        ///     根据省Id和城市id获取对应的名称
        /// </summary>
        /// <returns></returns>
        public Tuple <string, string> GetProvinceAndCityNameById(int provinceId, int cityId)
        {
            var catchTime = 1440 * 60;

            if (provinceId == 1)
            {
                return(new Tuple <string, string>("北京", "北京"));
            }
            if (provinceId == 153)
            {
                return(new Tuple <string, string>("上海", "上海"));
            }
            if (provinceId == 342)
            {
                return(new Tuple <string, string>("重庆", "重庆"));
            }
            if (provinceId == 294)
            {
                return(new Tuple <string, string>("天津", "天津"));
            }

            var redisCacheService = new RedisCacheService();
            var allProvince       = redisCacheService.Get(RedisConsts.AddressBaseData, catchTime, GetAllProvinceFromDb);
            var province          = allProvince.SingleOrDefault(a => a.Id == provinceId && a.Level == 1);

            if (province == null)
            {
                throw new YuanbeiException("未找到对应的省:" + provinceId);
            }

            var city = allProvince.SingleOrDefault(a => a.Id == cityId && a.Level == 2);

            if (city == null)
            {
                throw new YuanbeiException("未找到对应的市:" + cityId);
            }

            return(new Tuple <string, string>(province.Name, city.Name));
        }
Esempio n. 17
0
        public void Get_ObjectValue_Success()
        {
            var key = _fixture.Create <string>();

            var expected = _fixture.Create <TestType>();

            var value = expected.Serialize(_serializerSettings);

            var expectedKey = $"{_keyPrefix}{key}";

            _dataBase.Setup(b => b.StringGet(expectedKey, CommandFlags.None)).Returns(value);


            var data = _target.Get <TestType>(key);


            _mockRepository.VerifyAll();

            Assert.NotNull(data);
            Assert.AreEqual(expected.Property, data.Property);
            Assert.AreEqual(expected.Field, data.Field);
        }
Esempio n. 18
0
        public AccountVersion GetAccountVersion(int accId)
        {
            var redisCacheService  = new RedisCacheService();
            var accVersionRedisKey = RedisConsts.AccountVersion + accId.ToString();
            var accVersionResult   = redisCacheService.Get <AccountVersion>(accVersionRedisKey);

            if (accVersionResult != null)
            {
                _logger.Debug(string.Format("Get app account version from redis cache. {0},{1} ", accId, accVersionRedisKey));
                return(accVersionResult);
            }

            var accVersion = GetAccountVersionBasic(accId);
            var entity     = new AccountVersion
            {
                Version = accVersion.Version,
                VersionExpirationTime = accVersion.VersionExpirationTime
            };

            entity.VersionName = entity.Version.ToEnumDescriptionString(typeof(AccountVersionEnum));
            //行业版
            if (entity.Version == (int)AccountVersionEnum.Industry)
            {
                entity.SubVersionName = accVersion.IndustryName;
            }
            //试用高级版
            if (entity.Version == (int)AccountVersionEnum.Advanced && accVersion.BetaAdvance == (int)BetaAdvanceEnum.UsingBetaAdvance)
            {
                entity.SubVersionName = Convert.ToInt32(BetaAdvanceEnum.UsingBetaAdvance).ToEnumDescriptionString(typeof(AccountVersionEnum));
            }
            //todo:终身高级版
            //todo:购买后更新redis
            var expireSeconds = 108000;

            redisCacheService.Set(accVersionRedisKey, entity, expireSeconds);
            return(entity);
        }
Esempio n. 19
0
        /// <summary>
        /// 获取广告详情
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetAdvertDetail(string positionCode, int accountId = -1, UserContext userContext = null)
        {
            var adverApi = new Entity.Api.Advert.Advert();

            string key = RedisConsts.StationAdvertKey + positionCode.ToLower();

            var redisCacheService = new RedisCacheService();

            if (redisCacheService.HasKey(key))
            {
                adverApi = redisCacheService.Get <Entity.Api.Advert.Advert>(key);
            }
            else
            {
                var advertModel =
                    _advertDataRepository.FindAll(ad => ad.AdPositionCode == positionCode &&
                                                  ad.Enable == 1 &&
                                                  ad.StartDate <= DateTime.Now &&
                                                  ad.EndDate >= DateTime.Now
                                                  ).OrderByDescending(o => o.Id).FirstOrDefault();

                if (advertModel == null)
                {
                    //throw new YuanbeiException("获取站内广告信息失败,未找到对应信息");
                    return(new ResponseModel
                    {
                        Code = 0,
                        Message = "无数据",
                        Data = null
                    });
                }

                var adverResourcesList = _advertResourcesDataRepository.FindAll(ad => ad.AdId == advertModel.Id &&
                                                                                ad.State == 1)
                                         .OrderByDescending(o => o.Id);

                //TO DTO
                adverApi.title   = advertModel.AdTitle;
                adverApi.display = advertModel.DisplayMode;
                adverApi.width   = advertModel.AdWidth;
                adverApi.height  = advertModel.AdHieght;
                adverApi.items   = new List <Entity.Api.Advert.AdvertResources>();
                foreach (var advertResourcese in adverResourcesList)
                {
                    var advertResourceApi = new Entity.Api.Advert.AdvertResources();
                    //advertResourceApi.link = advertResourcese.AdLink;
                    advertResourceApi.link = WebConfigSetting.Instance.AdvertTransferUrl +
                                             string.Format("?adresid={0}&turl={1}", advertResourcese.Id,
                                                           HttpUtility.UrlEncode(advertResourcese.AdLink));
                    advertResourceApi.image = WebConfigSetting.Instance.ImageServer + advertResourcese.AdImageUrl;

                    adverApi.items.Add(advertResourceApi);
                }

                //Insert Cache 7days
                redisCacheService.Set(key, adverApi, 60 * 60 * 24 * 7);
            }

            //Insert View Log
            Task.Factory.StartNew(() =>
            {
                var advertModel =
                    _advertDataRepository.FindAll(ad => ad.AdPositionCode == positionCode &&
                                                  ad.Enable == 1 &&
                                                  ad.StartDate <= DateTime.Now &&
                                                  ad.EndDate >= DateTime.Now
                                                  ).OrderByDescending(o => o.Id).FirstOrDefault();

                AdvertLog advertLog = new AdvertLog();
                advertLog.AdId      = advertModel.Id;
                advertLog.AccountId = accountId;
                if (userContext != null)
                {
                    advertLog.Ip = userContext.IpAddress;
                }
                advertLog.Type       = 1;
                advertLog.CreateTime = DateTime.Now;
                _advertLogDataRepository.Insert(advertLog);
            });

            //TODO 店铺权限判断
            if (accountId != -1)
            {
            }

            //2.返回查询结果
            return(new ResponseModel
            {
                Code = 0,
                Message = "获取数据成功",
                Data = adverApi
            });
        }
        private AuthenticateResult Authenticate()
        {
            //ETSContext _DBContext = new ETSContext();
            string token  = Context.Request.Headers["X-Authorized-Token"];
            string userId = Context.Request.Headers["X-Authorized-userId"];

            if (token == null)
            {
                return(AuthenticateResult.Fail("No Authorization token provided"));
            }
            try
            {
                //string _userId = Decrypt(userId);
                //string isValidToken = validatetoken(token, _userId);

                //if (isValidToken == "1")
                //{
                //    var claims = new[] { new Claim(ClaimTypes.Name, isValidToken) };
                //    var identity = new ClaimsIdentity(claims, Scheme.Name);
                //    var principal = new ClaimsPrincipal(identity);
                //    var ticket = new AuthenticationTicket(principal, Scheme.Name);
                //    return AuthenticateResult.Success(ticket);

                //}
                //else
                //{
                //    return AuthenticateResult.Fail("Invalid Authorization");
                //}

                var routeData = Context.Request.Path.Value;
                //var XAuthorizedToken = Convert.ToString(context.Request.Headers["X-Authorized-Token"]);
                if (!string.IsNullOrEmpty(routeData))
                {
                    if (!routeData.Contains("dev-Ticketingsecuritymodule"))
                    {
                        if (!routeData.Contains("validateprogramcode"))
                        {
                            var XAuthorizedProgramcode = Convert.ToString(Context.Request.Headers["X-Authorized-Programcode"]);
                            if (string.IsNullOrEmpty(XAuthorizedProgramcode))
                            {
                                var XAuthorizedToken = Convert.ToString(Context.Request.Headers["X-Authorized-Token"]);

                                Authenticate authenticates = new Authenticate();
                                authenticates          = SecurityService.GetAuthenticateDataFromToken(_radisCacheServerAddress, SecurityService.DecryptStringAES(XAuthorizedToken));
                                XAuthorizedProgramcode = authenticates.ProgramCode;
                            }
                            else
                            {
                                XAuthorizedProgramcode = SecurityService.DecryptStringAES(XAuthorizedProgramcode);
                            }
                            if (XAuthorizedProgramcode != null)
                            {
                                RedisCacheService cacheService = new RedisCacheService(_radisCacheServerAddress);
                                if (cacheService.Exists("Con" + XAuthorizedProgramcode))
                                {
                                    string _data = cacheService.Get("Con" + XAuthorizedProgramcode);
                                    _data = JsonConvert.DeserializeObject <string>(_data);
                                    Configurations["ConnectionStrings:DataAccessMySqlProvider"] = _data;
                                }
                            }
                        }
                    }
                }


                Authenticate authenticate = SecurityService.GetAuthenticateDataFromToken(_radisCacheServerAddress, SecurityService.DecryptStringAES(token));

                if (!string.IsNullOrEmpty(authenticate.Token))
                {
                    var claims    = new[] { new Claim(ClaimTypes.Name, "1") };
                    var identity  = new ClaimsIdentity(claims, Scheme.Name);
                    var principal = new ClaimsPrincipal(identity);
                    var ticket    = new AuthenticationTicket(principal, Scheme.Name);
                    return(AuthenticateResult.Success(ticket));
                }
                else
                {
                    return(AuthenticateResult.Fail("Invalid Authorization"));
                }
            }
            catch (Exception ex)
            {
                return(AuthenticateResult.Fail("Failed to validate token"));
            }
        }
Esempio n. 21
0
        public async Task UpdateBookingModelInCache(Message msg)
        {
            RedisCacheService rCache   = new RedisCacheService();
            List <EventBase>  events   = new List <EventBase>();
            Track             tracking = new Track();
            var bookingId = string.Empty;
            List <OrderHistory> trackingHistory = new List <OrderHistory>();

            try
            {
                if (msg.Label == "BookingAdd")
                {
                    BookingAddIntegrationEvent eventMsg = JsonConvert.DeserializeObject <BookingAddIntegrationEvent>(Encoding.UTF8.GetString(msg.Body));

                    string messageType = "BookingCreated";

                    BookingCreated bookingCreated = new
                                                    BookingCreated(eventMsg.BookingId, string.Empty, eventMsg.Id
                                                                   , messageType, eventMsg.CreationDate, eventMsg.Origin, eventMsg.Destination);

                    bookingId = eventMsg.BookingId;
                    tracking.BookingAdd(bookingCreated);
                }
                else if (msg.Label == "OrderPicked")
                {
                    OrderPickedIntegrationEvent eventMsg = JsonConvert.DeserializeObject <OrderPickedIntegrationEvent>(Encoding.UTF8.GetString(msg.Body));

                    string messageType = "OrderPicked";

                    OrderPicked orderPicked = new
                                              OrderPicked(eventMsg.BookingId, eventMsg.Description, eventMsg.Id
                                                          , messageType, eventMsg.CreationDate);

                    bookingId = eventMsg.BookingId;
                    tracking.OrderPicked(orderPicked);
                }

                else if (msg.Label == "OrderTransit")
                {
                    OrderTransitIntegrationEvent eventMsg = JsonConvert.DeserializeObject <OrderTransitIntegrationEvent>(Encoding.UTF8.GetString(msg.Body));

                    string messageType = "OrderInTransit";

                    OrderInTransit orderInTransit = new
                                                    OrderInTransit(eventMsg.BookingId, eventMsg.Description, eventMsg.Id
                                                                   , messageType, eventMsg.CreationDate);


                    bookingId = eventMsg.BookingId;
                    tracking.OrderInTransit(orderInTransit);
                }
                else if (msg.Label == "OrderDelivered")
                {
                    OrderDeliveredIntegrationEvent eventMsg = JsonConvert.DeserializeObject <OrderDeliveredIntegrationEvent>(Encoding.UTF8.GetString(msg.Body));

                    string messageType = "OrderDelivered";

                    OrderDelivered orderDelivered = new
                                                    OrderDelivered(eventMsg.BookingId, eventMsg.Description, eventMsg.Id
                                                                   , messageType, eventMsg.CreationDate, eventMsg.SignedBy);


                    bookingId = eventMsg.BookingId;
                    tracking.OrderDelivered(orderDelivered);
                }
                else if (msg.Label == "PaymentProcessed")
                {
                    PaymentProcessedIntegrationEvent eventMsg = JsonConvert.DeserializeObject <PaymentProcessedIntegrationEvent>(Encoding.UTF8.GetString(msg.Body));

                    string messageType = "PaymentProcessed";

                    string description = string.Empty;
                    if (eventMsg.PaymentStatus == PaymetStatus.Completed)
                    {
                        description = "Payment Done";
                    }
                    else if (eventMsg.PaymentStatus == PaymetStatus.Canceled)
                    {
                        description = "Payment Failed";
                    }
                    else if (eventMsg.PaymentStatus == PaymetStatus.Pending)
                    {
                        description = "Payment Pending";
                    }

                    PaymentProcessed eventPaymentProcessed = new
                                                             PaymentProcessed(eventMsg.BookingOrderId, description, eventMsg.Id, messageType, eventMsg.CreationDate);


                    bookingId = eventMsg.BookingOrderId;
                    tracking.PaymentProcessed(eventPaymentProcessed);
                }

                //If  Booking ID Exists
                if (!string.IsNullOrEmpty(bookingId))
                {
                    if (!string.IsNullOrEmpty(rCache.Get(bookingId)))
                    {
                        trackingHistory = JsonConvert.DeserializeObject <List <OrderHistory> >(rCache.Get(bookingId));
                    }

                    //Append new event to old events
                    trackingHistory.AddRange(tracking.orderHistory);

                    //Serialze the result
                    var result = JsonConvert.SerializeObject(trackingHistory);
                    await rCache.Remove(bookingId);

                    //Update the Cache
                    if (!string.IsNullOrEmpty(result))
                    {
                        await rCache.Save(bookingId, result);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 22
0
 private static string get(string key)
 {
     return(_redisCacheService.Get(key));
 }
Esempio n. 23
0
        public ResponseModel ForgetPassword(string EmailId)
        {
            ResponseModel objResponseModel = new ResponseModel();

            try
            {
                /////Validate User
                string X_Authorized_Programcode = Convert.ToString(Request.Headers["X-Authorized-Programcode"]);
                string X_Authorized_Domainname  = Convert.ToString(Request.Headers["X-Authorized-Domainname"]);
                string _data = "";
                if (X_Authorized_Programcode != null)
                {
                    X_Authorized_Programcode = SecurityService.DecryptStringAES(X_Authorized_Programcode);

                    RedisCacheService cacheService = new RedisCacheService(_radisCacheServerAddress);
                    if (cacheService.Exists("Con" + X_Authorized_Programcode))
                    {
                        _data = cacheService.Get("Con" + X_Authorized_Programcode);
                        _data = JsonConvert.DeserializeObject <string>(_data);
                    }
                }

                if (X_Authorized_Domainname != null)
                {
                    X_Authorized_Domainname = SecurityService.DecryptStringAES(X_Authorized_Domainname);
                }
                securityCaller securityCaller = new securityCaller();
                Authenticate   authenticate   = securityCaller.validateUserEmailId(new SecurityService(_data, _radisCacheServerAddress), EmailId);
                if (authenticate.UserMasterID > 0)
                {
                    MasterCaller masterCaller = new MasterCaller();
                    SMTPDetails  sMTPDetails  = masterCaller.GetSMTPDetails(new MasterServices(_data), authenticate.TenantId);

                    CommonService commonService    = new CommonService();
                    string        encryptedEmailId = commonService.Encrypt(EmailId);
                    string        url = X_Authorized_Domainname.TrimEnd('/') + "/storeUserforgotPassword?Id:" + encryptedEmailId;
                    // string body = "Hello, This is Demo Mail for testing purpose. <br/>" + url;

                    string content = "";
                    string subject = "";

                    securityCaller.GetForgetPassowrdMailContent(new SecurityService(_connectioSting), authenticate.TenantId, url, EmailId, out content, out subject);

                    bool isUpdate = securityCaller.sendMail(new SecurityService(_connectioSting), sMTPDetails, EmailId, subject, content, authenticate.TenantId);

                    if (isUpdate)
                    {
                        objResponseModel.Status       = true;
                        objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.Success;
                        objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.Success);
                        objResponseModel.ResponseData = "Mail sent successfully";
                    }
                    else
                    {
                        objResponseModel.Status       = false;
                        objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.InternalServerError;
                        objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.InternalServerError);
                        objResponseModel.ResponseData = "Mail sent failure";
                    }
                }
                else
                {
                    objResponseModel.Status       = false;
                    objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.RecordNotFound;
                    objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.RecordNotFound);
                    objResponseModel.ResponseData = "Sorry User does not exist or active";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
Esempio n. 24
0
        public ResponseModel AuthenticateUser()
        {
            string X_Authorized_Programcode = Convert.ToString(Request.Headers["X-Authorized-Programcode"]);
            string X_Authorized_userId      = Convert.ToString(Request.Headers["X-Authorized-userId"]);
            string X_Authorized_password    = Convert.ToString(Request.Headers["X-Authorized-password"]);
            string X_Authorized_Domainname  = Convert.ToString(Request.Headers["X-Authorized-Domainname"]);

            ResponseModel resp = new ResponseModel();

            try
            {
                securityCaller newSecurityCaller = new securityCaller();
                AccountModal   account           = new AccountModal();
                string         Programcode       = X_Authorized_Programcode.Replace(' ', '+');
                string         Domainname        = X_Authorized_Domainname.Replace(' ', '+');
                string         userId            = X_Authorized_userId.Replace(' ', '+');
                string         password          = X_Authorized_password.Replace(' ', '+');


                string _data = "";
                if (X_Authorized_Programcode != null)
                {
                    X_Authorized_Programcode = SecurityService.DecryptStringAES(X_Authorized_Programcode);

                    RedisCacheService cacheService = new RedisCacheService(_radisCacheServerAddress);
                    if (cacheService.Exists("Con" + X_Authorized_Programcode))
                    {
                        _data = cacheService.Get("Con" + X_Authorized_Programcode);
                        _data = JsonConvert.DeserializeObject <string>(_data);
                    }
                }

                if (!string.IsNullOrEmpty(Programcode) && !string.IsNullOrEmpty(Domainname) && !string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(password))
                {
                    account = newSecurityCaller.validateUser(new SecurityService(_data, _radisCacheServerAddress), Programcode, Domainname, userId, password);

                    if (!string.IsNullOrEmpty(account.Token))
                    {
                        account.IsActive  = true;
                        resp.Status       = true;
                        resp.StatusCode   = (int)EnumMaster.StatusCode.Success;
                        resp.ResponseData = account;
                        resp.Message      = "Valid Login";
                    }
                    else
                    {
                        account.IsActive  = false;
                        resp.Status       = true;
                        resp.StatusCode   = (int)EnumMaster.StatusCode.Success;
                        resp.ResponseData = account;
                        resp.Message      = "In-Valid Login";
                    }
                }
                else
                {
                    resp.Status       = false;
                    resp.ResponseData = account;
                    resp.Message      = "Invalid Login";
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(resp);
        }
Esempio n. 25
0
        private HomeIndex GetHomeIndexModel(int locationId)
        {
            var cacheSrv = new RedisCacheService();

            //Get the city
            var city = Cidade.Load(locationId);

            //Get the home object
            var objHome = city.Microregion.Home;

            #region GET CACHE

            //Set the const time value
            const int time = 1;

            //Set the cache key
            var key = $"Home:{objHome.Id}";

            //Find in the cache for the model
            var objModel = cacheSrv.Get <HomeIndex>(key);

            //If model exists in cache return the object
            if (objModel != null)
            {
                return(objModel);
            }
            #endregion

            //Save the current home state
            var currentHome = objHome;

            //If Home is disabled load the main home
            if (!objHome.Status)
            {
                objHome = Home.Load(1); //Home Curitiba
            }
            //Get list of news highlights
            var lstHighlights = Noticia.GetHighlightNewsByHome(objHome.Id).ToList();

            //Create initial negation list with hiloghts id's
            var notInList = lstHighlights.Select(s => s.Id).ToList();

            objModel = new HomeIndex
            {
                //Base
                Title       = "Massa News - A notícia em movimento!",
                Description = "O Massa News oferece a melhor cobertura jornalística do Paraná com notícias personalizadas da sua região.",
                Robots      = "index, follow",
                Canonical   = Constants.UrlWeb,

                //Model
                Cidade           = Cidade.Load(12), //Curitiba //objCidade,
                SidebarHighlight = objHome.SidebarHighlight,
                TemplateId       = objHome.Highlight.TemplateId,
                Highlights       = lstHighlights
            };

            //SUA REGIÃO
            //Este módulo recebe a cidade original
            objModel.DestaqueComTagsSuaRegiao = GetDestaquesComtags(Section.SuaRegiao, currentHome, ref notInList);

            //ESPORTES
            objModel.DestaqueComTagsEsportes = GetDestaquesComtags(Section.Esportes, currentHome, ref notInList);

            //ENTRETEDIMENTO
            objModel.DestaqueComTagsEntretedimento = GetDestaquesComtags(Section.Entretenimento, currentHome, ref notInList);

            //PARANÁ - TODOS OS PLANTÕES
            objModel.DestaqueComTagsParana = GetDestaquesComtags(Section.Parana, currentHome, ref notInList);

            //CATEGORIAS DESTAQUES
            objModel.CategoriasDestaquesModel = GetCategoriaDestaquesModel(objHome.Id, ref notInList);

            //VIAJAR É MASSA
            objModel.DestaqueComTagsViajarEMassa = GetDestaquesComtags(Section.ViajarEMassa, currentHome, ref notInList);

            //WHERE CURITIBA
            if (currentHome.Id == 1)
            {
                objModel.DestaqueComTagsWhereCuritiba = GetDestaquesComtags(Section.WhereCuritiba, currentHome, ref notInList);
            }

            //NEGÓCIOS DA TERRA
            objModel.DestaqueComTagsNegociosDaTerra = GetDestaquesComtags(Section.NegociosDaTerra, currentHome, ref notInList);

            //VIDEOS
            objModel.DestaqueVideo = GetVideoHighlights(city, ref notInList);

            //FOTOS (GALERIAS)
            objModel.HighlightsFotos = Noticia.GetBySection(8, Section.Fotos, 1, ref notInList, true).ToList();

            //BLOGS
            objModel.Blogs = GetBlogListByMicroregion(currentHome.MicroregiaoId);

            #region ENQUETE
            var statusEnquete = EnqueteSrv.GetStatusEnquete();

            switch (statusEnquete.Status)
            {
            case (int)EnqueteEnum.Estadual:
                objModel.ShowEnquete = true;
                objModel.EnqueteId   = Constants.EnqueteRegionalId;
                break;

            case (int)EnqueteEnum.Regional:
                foreach (var item in statusEnquete.RegioesEnquetes.Where(item => objHome.MicroregiaoId == item.MicroregiaoId && item.Status))
                {
                    objModel.ShowEnquete = true;
                    objModel.EnqueteId   = item.EnqueteId;
                }
                break;

            default:
                objModel.ShowEnquete = false;
                break;
            }
            #endregion

            //Set the cache
            cacheSrv.Set(key, objModel, time);

            return(objModel);
        }
Esempio n. 26
0
 public void Get_NullKey_Throws()
 {
     Assert.Throws <NullKeyException>(() => _target.Get <object>(null));
 }
Esempio n. 27
0
        public ResponseModel SendMailforchangepassword(int userID, int IsStoreUser = 1)
        {
            CustomChangePassword customChangePassword = new CustomChangePassword();
            ResponseModel        objResponseModel     = new ResponseModel();

            try
            {
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(_radisCacheServerAddress, SecurityService.DecryptStringAES(token));
                string            _data        = "";
                string            ProgramCode  = authenticate.ProgramCode;
                RedisCacheService cacheService = new RedisCacheService(_radisCacheServerAddress);
                if (cacheService.Exists("Con" + ProgramCode))
                {
                    _data = cacheService.Get("Con" + ProgramCode);
                    _data = JsonConvert.DeserializeObject <string>(_data);
                }
                string X_Authorized_Domainname = Convert.ToString(Request.Headers["X-Authorized-Domainname"]);
                if (X_Authorized_Domainname != null)
                {
                    X_Authorized_Domainname = SecurityService.DecryptStringAES(X_Authorized_Domainname);
                }
                UserCaller userCaller = new UserCaller();

                customChangePassword = userCaller.SendMailforchangepassword(new UserServices(_data), userID, authenticate.TenantId, IsStoreUser);
                if (customChangePassword.UserID > 0 && customChangePassword.Password != null && customChangePassword.EmailID != null)
                {
                    MasterCaller   masterCaller     = new MasterCaller();
                    SMTPDetails    sMTPDetails      = masterCaller.GetSMTPDetails(new MasterServices(_data), authenticate.TenantId);
                    securityCaller _securityCaller  = new securityCaller();
                    CommonService  commonService    = new CommonService();
                    string         encryptedEmailId = SecurityService.Encrypt(customChangePassword.EmailID);

                    string decriptedPassword = SecurityService.DecryptStringAES(customChangePassword.Password);
                    string url      = configuration.GetValue <string>("websiteURL") + "/ChangePassword";
                    string body     = "Dear User, <br/>Please find the below details.  <br/><br/>" + "Your Email ID  : " + customChangePassword.EmailID + "<br/>" + "Your Password : "******"<br/><br/>" + "Click on Below link to change the Password <br/>" + url + "?Id:" + encryptedEmailId;
                    bool   isUpdate = _securityCaller.sendMailForChangePassword(new SecurityService(_connectioSting), sMTPDetails, customChangePassword.EmailID, body, authenticate.TenantId);
                    if (isUpdate)
                    {
                        objResponseModel.Status       = true;
                        objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.Success;
                        objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.Success);
                        objResponseModel.ResponseData = "Mail sent successfully";
                    }
                    else
                    {
                        objResponseModel.Status       = false;
                        objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.InternalServerError;
                        objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.InternalServerError);
                        objResponseModel.ResponseData = "Mail sent failure";
                    }
                }

                else
                {
                    objResponseModel.Status       = false;
                    objResponseModel.StatusCode   = (int)EnumMaster.StatusCode.RecordNotFound;
                    objResponseModel.Message      = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.RecordNotFound);
                    objResponseModel.ResponseData = "Sorry User does not exist or active";
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
        internal static T GetBusinessDetailsFromCache <T>(string fpTag, bool isCacheEnabled, string domainName, bool isNFSite, T businessClass, string schema = null, string developerId = null, string customerId = null, bool isEnterprise = false, string rootAliasUri = null)
        {
            try
            {
                fpTag = fpTag.ToUpper();

                if (isCacheEnabled && isApiCacheEnabled)
                {
                    string cacheServiceResponse = string.Empty;
                    try
                    {
                        try
                        {
                            var dnsHost = string.Empty;
                            try
                            {
                                dnsHost = new Uri(rootAliasUri).DnsSafeHost?.ToUpper();
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }

                            var cacheKey     = HashUrl.GetHashAsString(fpTag);
                            var cacheHashKey = HashUrl.GetHashAsString(dnsHost);

                            var task = Task.Run(() => ApiCacheService.Get(GetMetaInfoCacheKey(cacheHashKey, cacheKey)));
                            if (task.Wait(_cacheTimeout))
                            {
                                cacheServiceResponse = task.Result;
                            }
                            else
                            {
                                ConsoleLogger.Write($"ERROR: CACHE GetExpression - Redis TimeOut");
                            }
                        }
                        catch (Exception ex)
                        {
                            ConsoleLogger.Write($"ERROR: Unable to GetBusinessDetailsFromCache() - Redis TimeOut");
                        }

                        if (!String.IsNullOrEmpty(cacheServiceResponse))
                        {
                            return(JsonConvert.DeserializeObject <T>(JsonConvert.DeserializeObject(cacheServiceResponse).ToString()));
                        }
                    }
                    catch (Exception ex) { throw ex; }
                }

                var temp = ApiHelper.GetBusinessDataFromNewAPI(fpTag, schema, customerId, developerId);

                if (isCacheEnabled && isApiCacheEnabled)
                {
                    try
                    {
                        UpdateBusinessDetailsCache(fpTag, temp, rootAliasUri);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                return(JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(temp)));
            }
            catch (Exception ex)
            {
                ConsoleLogger.Write($"ERROR: CACHE GetBusinessDetailsFromCache - {ex.ToString()}");
            }

            return(JsonConvert.DeserializeObject <T>(null));
        }
Esempio n. 29
0
        /// <summary>
        ///     根据Token和Appkey获取用户的相关信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="appKey"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserContext GetUserContext(string token, string appKey, string userId)
        {
            var redisCacheService = new RedisCacheService();
            var expireDate        = DateTime.Now.AddHours(-30);
            var intUserId         = 0;

            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentNullException("token cannot be null");
            }

            //if (!int.TryParse(userId, out intUserId))
            //{
            //    throw new ArgumentException("userId is not valid");
            //}

            var tokenRedisKey = string.IsNullOrWhiteSpace(appKey)
                ? RedisConsts.WebUserTokenKey + userId
                : RedisConsts.AppUserTokenKey + userId;

            var tokenResult = redisCacheService.Get <UserContext>(tokenRedisKey);

            if (tokenResult != null)
            {
                if (CheckSearchToken(token, tokenResult))
                {
                    return(null);
                }
                _logger.Debug(string.Format("Get app user context from redis cache. {0},{1},{2} ", token, appKey,
                                            tokenRedisKey));
                return(tokenResult);
            }

            _webTokenRepository.Find(
                t => t.Token == token && t.CreateTime > expireDate && t.CreateTime < DateTime.Now);

            var retToken = string.IsNullOrWhiteSpace(appKey)
                ? _webTokenRepository.Find(
                t => t.Token == token && t.CreateTime > expireDate && t.CreateTime < DateTime.Now, null,
                t => t.CreateTime, OrderDirection.DESC)
                : _apiTokenRepository.Find(
                t => t.Token == token && t.CreateTime > expireDate && t.CreateTime < DateTime.Now, null,
                t => t.CreateTime, OrderDirection.DESC);

            if (retToken == null)
            {
                return(null);
            }

            if (retToken.Token != token)
            {
                throw new YuanbeiHttpRequestException((int)ErrorCodeEnum.TokenIsExpired, "token不正确");
            }

            var strSql = new StringBuilder();

            strSql.Append(
                "SELECT m.accountid AS AccId,m.id AS UserId,m.name AS OperaterName,m.grade AS Grade,UserPower AS UserPower, ");
            strSql.Append(
                "n.max_shop AS masterId ,m.PhoneNumber AS PhoneNumber  FROM dbo.T_Account_User m left JOIN  dbo.T_Account n ON  ");
            strSql.Append("m.accountid =n.ID WHERE m.accountid=@accountId AND m.id=@userId ");
            var sqlParams = new
            {
                accountId = retToken.AccId,
                userId    = retToken.UserId
            };
            var dapperParam = new DynamicParameters(sqlParams);
            var sqlQuery    = new SqlQuery(strSql.ToString(), dapperParam);
            var accountUser = _accoutUserRepository.Find(sqlQuery);

            if (accountUser == null)
            {
                throw new YuanbeiHttpRequestException((int)ErrorCodeEnum.TokenIsExpired, "没有找到用户相关信息");
            }


            return(new UserContext
            {
                AccId = retToken.AccId,
                MasterId = accountUser.MasterId,
                UserId = retToken.UserId,
                PhoneNumber = accountUser.PhoneNumber,
                CompanyName = accountUser.CompanyName,
                OperaterName = retToken.UserName,
                Token = retToken.Token,
                AppKey = retToken.AppKey,
                Role = accountUser.Grade == AccountUserGradeConsts.Administrator ? 1 : 0,
                Powers = accountUser.UserPower
            });
        }