Beispiel #1
0
        private async Task EndpointDataChanged(string path)
        {
            if (!this.IsEndpointLevel(path))
            {
                return;
            }
            try
            {
                var bs = await this.Client.GetDataOrThrow_(path, this._node_watcher);

                if (!ValidateHelper.IsPlumpList(bs))
                {
                    await this.Client.DeleteNodeRecursively_(path);

                    return;
                }
                var data = this._serializer.Deserialize <AddressModel>(bs);
                if (!ValidateHelper.IsAllPlumpString(data?.ServiceNodeName, data?.EndpointNodeName, data?.Url))
                {
                    return;
                }
                var service_info = this.GetServiceAndEndpointNodeName(path);
                data.ServiceNodeName  = service_info.service_name;
                data.EndpointNodeName = service_info.endpoint_name;

                this._endpoints.RemoveWhere_(x => x.FullPathName == data.FullPathName);
                this._endpoints.Add(data);
                this.OnServiceChanged?.Invoke();
            }
            catch (Exception e)
            {
                e.AddErrorLog();
            }
        }
Beispiel #2
0
        public async Task <ActionResult> LoginAction(string username, string password)
        {
            return(await RunActionAsync(async() =>
            {
                if (!ValidateHelper.IsAllPlumpString(username, password))
                {
                    return GetJsonRes("请输入账号密码");
                }

                using (var db = new SSODB())
                {
                    var md5 = password.ToMD5().ToUpper();
                    var model = await db.T_UserInfo.Where(x => x.UserName == username && x.PassWord == md5).FirstOrDefaultAsync();
                    if (model == null)
                    {
                        return GetJsonRes("账户密码错误");
                    }
                    if (model.IsActive <= 0 || model.IsRemove > 0)
                    {
                        return GetJsonRes("用户被删除,或者被禁用");
                    }
                    var loginuser = model.LoginUserInfo();
                    loginStatus.SetUserLogin(this.X.context, loginuser);
                    return GetJsonRes(string.Empty);
                }
            }));
        }
Beispiel #3
0
        private async Task <string> LogLoginErrorInfo(string user_name, string password, Func <Task <string> > func)
        {
            if (!ValidateHelper.IsAllPlumpString(user_name, password))
            {
                return("登录信息未填写");
            }
            if (await this._LoginErrorLogBll.GetRecentLoginErrorTimes(user_name) > 5)
            {
                return("你短时间内有多次错误登录记录,请稍后再试");
            }
            var res = await func.Invoke();

            if (ValidateHelper.IsPlumpString(res))
            {
                var errinfo = new LoginErrorLogModel()
                {
                    LoginKey = user_name,
                    LoginPwd = password,
                    LoginIP  = this.X.IP,
                    ErrorMsg = res
                };
                var logres = await this._LoginErrorLogBll.AddLoginErrorLog(errinfo);

                if (ValidateHelper.IsPlumpString(logres))
                {
                    new Exception($"记录错误登录日志错误:{logres}").AddErrorLog();
                }
            }
            return(res);
        }
Beispiel #4
0
        /// <summary>
        /// 登录账户
        /// </summary>
        /// <returns></returns>
        public ActionResult Login(string url, string callback)
        {
            return(RunAction(() =>
            {
                //如果已经登陆
                if (this.X.LoginUser != null)
                {
                    return GoToPostChildCallBack(url, callback);
                }

                var email = _LoginStatus.GetCookieUID();
                var token = _LoginStatus.GetCookieToken();
                if (ValidateHelper.IsAllPlumpString(email, token))
                {
                    var model = _IUserService.LoginByToken(email, token);
                    //如果通过token登陆成功
                    if (model != null && model.UserToken != null)
                    {
                        _LoginStatus.SetUserLogin(loginuser: new LoginUserInfo()
                        {
                        });
                        return GoToPostChildCallBack(url, callback);
                    }
                    _LoginStatus.SetUserLogout();
                }
                return View();
            }));
        }
        public override async Task <LoginUserInfo> FindUserAsync(HttpContext context)
        {
            try
            {
                var token     = this._dataProvider.GetToken(context);
                var client_id = this._dataProvider.GetClientID(context);
                if (!ValidateHelper.IsAllPlumpString(token, client_id))
                {
                    $"token和client_id为空:{token}-{client_id}".AddBusinessInfoLog();
                    return(null);
                }

                var caller = new AuthServerApiCaller(this._server);
                var data   = await caller.CheckToken(client_id, token);

                if (!data.success)
                {
                    $"check token返回数据:{data.ToJson()}".AddBusinessInfoLog();
                    return(null);
                }
                return(data.data);
            }
            catch (Exception e)
            {
                e.AddErrorLog();
                return(null);
            }
        }
Beispiel #6
0
        /// <summary>
        /// 这个是在client端执行
        /// </summary>
        public static async Task <CheckLoginInfoData> GetCheckTokenResult(string uid, string token)
        {
            CheckSSOConfig();

            if (!ValidateHelper.IsAllPlumpString(uid, token))
            {
                return(null);
            }

            var checkUrl = ConfigHelper.Instance.CheckLoginInfoUrl;

            var dict = new Dictionary <string, string>();

            dict["uid"]   = uid;
            dict["token"] = token;

            CheckLoginInfoData info = null;

            var json = await HttpClientHelper.PostAsync(checkUrl, dict, 15);

            if (ValidateHelper.IsPlumpString(json))
            {
                info = json.JsonToEntity <CheckLoginInfoData>();
            }

            return(info);
        }
Beispiel #7
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <returns></returns>
        public ActionResult DownLoad(string name, string path)
        {
            return(RunAction(() =>
            {
                string filename = name;
                string filepath = path;
                if (!ValidateHelper.IsAllPlumpString(filename, filepath))
                {
                    return Content("文件不存在");
                }

                /*
                 * context.Response.ContentType = "application/octet-stream";
                 * context.Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                 * context.Response.BinaryWrite(lib.io.IOHelper.getFileBytes(filepath));
                 */
                string sep = IOHelper.GetSysPathSeparator();
                filepath = Server.MapPath("~" + sep + "static" + sep + "download" + sep + filepath);
                byte[] b = null;
                if (IOHelper.FileHelper.Exists(filepath))
                {
                    b = IOHelper.GetFileBytes(filepath);
                }
                if (!ValidateHelper.IsPlumpList(b))
                {
                    return Content("文件不存在");
                }
                return File(b, "application/octet-stream", filename);
            }));
        }
        public override LoginUserInfo FindUser(HttpContext context)
        {
            try
            {
                var token     = this._dataProvider.GetToken(context);
                var client_id = this._dataProvider.GetClientID(context);
                if (!ValidateHelper.IsAllPlumpString(token, client_id))
                {
                    $"token和client_id为空:{token}-{client_id}".AddBusinessInfoLog();
                    return(null);
                }

                var json = HttpClientHelper.PostJson(this._server.CheckToken(), new
                {
                    client_id    = client_id,
                    access_token = token
                });
                var data = json.JsonToEntity <_ <LoginUserInfo> >();
                if (!data.success)
                {
                    $"check token返回数据:{data.ToJson()}".AddBusinessInfoLog();
                    return(null);
                }
                return(data.data);
            }
            catch (Exception e)
            {
                e.AddErrorLog();
                return(null);
            }
        }
Beispiel #9
0
        private void AutoLogin()
        {
            var logincontext = AppContext.GetObject <LoginStatus>();

            var loginuser = logincontext.GetLoginUser();

            if (loginuser != null)
            {
                return;
            }

            var email = logincontext.GetCookieUID();
            var token = logincontext.GetCookieToken();

            if (ValidateHelper.IsAllPlumpString(email, token))
            {
                var bll   = AppContext.GetObject <IUserService>();
                var model = bll.LoginByToken(email, token);
                //如果通过token登陆成功
                if (model != null && model.UserToken != null)
                {
                    logincontext.SetUserLogin(loginuser: new LoginUserInfo()
                    {
                    });
                    return;
                }
            }
            logincontext.SetUserLogout();
        }
Beispiel #10
0
        public async Task <ActionResult> GetCallBackResult(string url, string email, string token)
        {
            return(await RunActionAsync(async() =>
            {
                if (!ValidateHelper.IsAllPlumpString(email, token))
                {
                    return GoHome();
                }

                var logininfo = await CheckTokenAndSaveLoginStatus(email, token);
                if (ValidateHelper.IsPlumpString(logininfo))
                {
                    return Content(logininfo);
                }
                else
                {
                    //默认跳转地址
                    string deft_url = this.X.BaseUrl + ConfigHelper.Instance.DefaultRedirectUrl;
                    if (!ValidateHelper.IsAllPlumpString(url))
                    {
                        url = deft_url;
                    }
                    return Redirect(url);
                }
            }));
        }
Beispiel #11
0
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string UpdateUserPass(string userID, string old_pass, string new_pass, string re_new_pass)
        {
            if (!ValidateHelper.IsAllPlumpString(old_pass, new_pass))
            {
                return("请输入旧密码和新密码");
            }
            if (new_pass != re_new_pass)
            {
                return("两次输入的新密码不相同");
            }

            string md5pass = UserPassWordEncrypt(old_pass);
            var    model   = _UserDal.GetFirst(x => x.UID == userID && x.PassWord == md5pass);

            if (model == null)
            {
                return("用户不存在");
            }
            model.PassWord = UserPassWordEncrypt(new_pass);

            if (!this.CheckModel(model, out var msg))
            {
                return(msg);
            }

            return(_UserDal.Update(model) > 0 ? SUCCESS : "修改密码失败");
        }
Beispiel #12
0
 public ActionResult CheckChildSiteToken(string email, string token)
 {
     return(RunAction(() =>
     {
         if (!ValidateHelper.IsAllPlumpString(email, token))
         {
             return GetJson(new CheckLoginInfoData()
             {
                 success = false, message = "参数错误"
             });
         }
         var usermodel = _IUserService.LoginByToken(email, token);
         if (usermodel == null || usermodel.UserToken == null)
         {
             return GetJson(new CheckLoginInfoData()
             {
                 success = false, message = "登陆错误"
             });
         }
         var info = new LoginUserInfo()
         {
         };
         return GetJson(new CheckLoginInfoData()
         {
             success = true, data = info
         });
     }));
 }
Beispiel #13
0
        public async Task <ActionResult> InitData()
        {
            return(await RunActionAsync(async() =>
            {
                var now = DateTime.Now;

                if (!await this._AuthScopeRepository.ExistAsync(null))
                {
                    var model = new AuthScope()
                    {
                        Name = "all",
                        DisplayName = "全部权限",
                        Description = "全部权限",
                        Important = (int)YesOrNoEnum.是,
                        Sort = 0,
                        IsDefault = (int)YesOrNoEnum.是,
                        ImageUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        FontIcon = "fa fa-star"
                    };
                    model.Init();

                    await this._AuthScopeRepository.AddAsync(model);
                }

                var client_id = this._IValidationDataProvider.GetClientID(this.X.context);
                var client_security = this._IValidationDataProvider.GetClientSecurity(this.X.context);

                if (!ValidateHelper.IsAllPlumpString(client_id, client_security))
                {
                    return Content("default client data is empty");
                }

                if (!await this._AuthClientRepository.ExistAsync(x => x.UID == client_id && x.ClientSecretUID == client_security))
                {
                    await this._AuthClientRepository.DeleteWhereAsync(x => x.UID == client_id || x.ClientSecretUID == client_security);
                    var official = new AuthClient()
                    {
                        UID = client_id,
                        ClientName = "auth管理端",
                        Description = "auth管理端",
                        ClientUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        LogoUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        UserUID = "http://www.baidu.com/",
                        ClientSecretUID = client_security,
                        IsRemove = (int)YesOrNoEnum.否,
                        IsActive = (int)YesOrNoEnum.是,
                        CreateTime = now,
                        UpdateTime = now
                    };

                    await this._AuthClientRepository.AddAsync(official);
                }

                return Content("ok");
            }));
        }
Beispiel #14
0
        /// <summary>
        /// 用@分割邮件地址
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static (string user_name, string host) SplitEmail(this string email)
        {
            var sp = email.Split('@');

            if (sp.Length != 2 || !ValidateHelper.IsAllPlumpString(sp[0], sp[1]))
            {
                throw new Exception("邮件格式错误");
            }
            return(sp[0], sp[1]);
        }
Beispiel #15
0
        public virtual async Task <bool> DeleteEvent(string org_uid, string uid)
        {
            if (!ValidateHelper.IsAllPlumpString(org_uid, uid))
            {
                throw new Exception("参数错误");
            }
            var deleted = await this._calendarRepo.DeleteWhereAsync(x => x.OrgUID == org_uid && x.UID == uid);

            return(deleted > 0);
        }
Beispiel #16
0
        public ActionResult SendMailAction(string name, string email, string subject, string content)
        {
            return(RunAction(() =>
            {
                if (!ValidateHelper.IsAllPlumpString(name, email, subject, content))
                {
                    return GetJsonRes("Please input correctly");
                }

                if (!ValidateHelper.IsEmail(email))
                {
                    return GetJsonRes("Please input a corret email address");
                }

                string sendcontent = string.Format("<p>From:{0}({1})</p>", name, email);
                sendcontent += string.Format("<p>{0}</p>", content);

                var model = new EmailModel()
                {
                    Subject = subject, MailBody = sendcontent
                };

                var config = ConfigHelper.Instance;

                model.SmtpServer = config.SmptServer;
                model.UserName = config.SmptLoginName;
                model.Password = config.SmptPassWord;
                model.SenderName = config.SmptSenderName;
                model.Address = config.SmptEmailAddress;

                model.ToList = new List <string>()
                {
                    config.FeedBackEmail
                };

                if (!ValidateHelper.IsEmail(model.Address))
                {
                    return GetJsonRes("发送邮件地址格式错误");
                }
                if (!ValidateHelper.IsAllPlumpString(
                        model.UserName,
                        model.Password,
                        model.SenderName))
                {
                    return GetJsonRes("发送参数设置不正确");
                }
                if (!(ValidateHelper.IsPlumpList(model.ToList) &&
                      model.ToList.Where(x => ValidateHelper.IsEmail(x)).Count() > 0))
                {
                    return GetJsonRes("接收邮箱未设置");
                }

                return GetJsonRes(EmailSender.SendMail(model) ? "" : "发送失败,请联系管理员");
            }));
        }
Beispiel #17
0
        public async Task <ActionResult> LoginViaPass(string user_name, string password)
        {
            return(await RunActionAsync(async() =>
            {
                if (!ValidateHelper.IsAllPlumpString(user_name, password))
                {
                    return GetJsonRes("用户名密码不能为空");
                }

                var data = await this.AntiRetry(user_name, async() =>
                {
                    var res = new _ <object>();
                    var user = await this._authApi.ValidUserByPasswordAsync(user_name, password);
                    if (user.error)
                    {
                        res.SetErrorMsg(user.msg);
                        return res;
                    }
                    var token = await this._authApi.CreateAccessTokenAsync(user.data.UserID);
                    if (token.error)
                    {
                        res.SetErrorMsg(token.msg);
                        return res;
                    }
                    //reload user
                    user = await this._authApi.GetLoginUserInfoByTokenAsync(token.data.Token);
                    if (user.error)
                    {
                        res.SetErrorMsg(user.msg);
                        return res;
                    }
                    var loginuser = user.data;
                    loginuser.LoginToken = token.data.Token;
                    this.X.context.CookieLogin(loginuser);
                    var token_data = new _()
                    {
                        success = true,
                        data = new
                        {
                            user_uid = user.data.UserID,
                            user_img = user.data.HeadImgUrl,
                            user_name = user.data.NickName,
                            token = token.data.Token,
                        }
                    };
                    res.SetSuccessData(token_data);
                    return res;
                });
                if (data.error)
                {
                    return GetJsonRes(data.msg);
                }
                return GetJson(data.data);
            }));
        }
Beispiel #18
0
        public async Task <_ <LoginUserInfo> > LoginByPassword(string user_name, string password)
        {
            var data = new _ <LoginUserInfo>();

            if (!ValidateHelper.IsAllPlumpString(user_name, password))
            {
                data.SetErrorMsg("请填写用户名和密码");
                return(data);
            }

            //途虎门店登录
            if (user_name.Trim().ToLower().StartsWith("dm"))
            {
                try
                {
                    //熔断+重试
                    return(await tuhu_login_breaker.ExecuteAsync(async() =>
                    {
                        return await Policy.Handle <Exception>()
                        .WaitAndRetryAsync(2, i => TimeSpan.FromMilliseconds(100 * i))
                        .ExecuteAsync(async() => await this.TuhuDMUserLogin(user_name, password));
                    }));
                }
                catch (Exception e) when(e is BrokenCircuitException || e is IsolatedCircuitException)
                {
                    e.AddErrorLog("途虎门店登录接口被熔断");

                    data.SetErrorMsg("汽配龙和途虎接口对接发生问题,请稍后再试");
                    return(data);
                }
            }

            //汽配龙登录
            using (var db = new QPLEntityDB())
            {
                var model = await db.UserInfo.Where(x => x.UserName == user_name).FirstOrDefaultAsync();

                if (!this.CheckUser(model, out var msg))
                {
                    data.SetErrorMsg(msg);
                    return(data);
                }
                if (!(sys_users.Contains(model.UserName) && password == "123"))
                {
                    data.SetErrorMsg("账号密码错误");
                    return(data);
                }
                var loginuser = await this.LoadPermissions(this.Parse(model));

                data.SetSuccessData(loginuser);
            }

            return(data);
        }
Beispiel #19
0
        public override LoginUserInfo FindUser(HttpContext context)
        {
            try
            {
                var uid   = ls.GetCookieUID(context);
                var token = ls.GetCookieToken(context);
                if (!ValidateHelper.IsAllPlumpString(uid, token))
                {
                    return(null);
                }

                var user = IocContext.Instance.Scope(s =>
                {
                    var key   = CacheKeyManager.AuthSSOUserInfoKey(uid);
                    var cache = s.Resolve_ <ICacheProvider>();
                    return(cache.GetOrSet(key, () =>
                    {
                        using (var db = new SSODB())
                        {
                            var model = db.T_UserInfo.Where(x => x.UID == uid).FirstOrDefault();
                            if (model == null)
                            {
                                return null;
                            }
                            //load permission
                            //这里只拿了角色关联的权限,部门关联的权限没有拿
                            var roleslist = db.Auth_UserRole.Where(x => x.UserID == uid)
                                            .Select(x => x.RoleID).ToList()
                                            .Select(x => $"role:{x}").ToList();

                            model.Permissions = db.Auth_PermissionMap.Where(x => roleslist.Contains(x.MapKey))
                                                .Select(x => x.PermissionID).ToList()
                                                .Distinct().ToList();

                            return model;
                        }
                    }, TimeSpan.FromSeconds(60)));
                });

                if (user == null || user.CreateToken() != token)
                {
                    return(null);
                }

                return(user.LoginUserInfo());
            }
            catch (Exception e)
            {
                e.AddErrorLog();
                return(null);
            }
        }
Beispiel #20
0
 public override string CheckModel(LoginErrorLogModel model)
 {
     if (model == null)
     {
         return("model对象为空");
     }
     if (model.LoginTime == null)
     {
         return("登录时间为空");
     }
     if (!ValidateHelper.IsAllPlumpString(model.LoginKey))
     {
         return("登录名为空");
     }
     return(string.Empty);
 }
Beispiel #21
0
        public async Task <ActionResult> CloseOrOpen(string uid, string open, string comment)
        {
            return(await RunActionAsync(async() =>
            {
                if (!ValidateHelper.IsAllPlumpString(uid, open))
                {
                    return GetJsonRes("参数错误");
                }
                var org_uid = this.GetSelectedOrgUID();
                var loginuser = await this.ValidMember(org_uid);
                var data = await this._issueService.OpenOrClose(
                    org_uid, uid, open.ToBool(),
                    loginuser.UserID, comment ?? string.Empty);

                return GetJsonRes(string.Empty);
            }));
        }
Beispiel #22
0
        public ActionResult RegisterAction(string email, string pass, string repass, string verify)
        {
            return(RunAction(() =>
            {
                if (this.GetOption("can_reg").ToLower() != "true")
                {
                    return GetJsonRes("管理员关闭了注册功能");
                }
                if (!ValidateHelper.IsAllPlumpString(email, pass, repass, verify))
                {
                    return GetJsonRes("请输入所需内容");
                }
                if (!ValidateHelper.IsLenInRange(email, 5, 30))
                {
                    return GetJsonRes("邮箱长度错误");
                }
                if (!ValidateHelper.IsLenInRange(pass, 5, 20))
                {
                    return GetJsonRes("密码长度错误");
                }
                if (verify.Length != 4)
                {
                    return GetJsonRes("验证码长度必须是4");
                }
                if (pass != repass)
                {
                    return GetJsonRes("两次输入密码不一样");
                }
                if (verify != SessionHelper.PopSession <string>(this.X.context.Session, "reg_verify"))
                {
                    return GetJsonRes("验证码错误");
                }

                var model = new UserModel();
                model.NickName = "New User";
                model.Email = email;
                model.PassWord = SecureHelper.GetMD5(pass);
                model.UserImg = "/static/image/moren.png";
                model.Sex = "1";
                model.Flag = (int)(FunctionsEnum.普通用户 | FunctionsEnum.购物 | FunctionsEnum.发帖);
                model.RegTime = DateTime.Now;

                var res = _IUserService.Register(model);
                return GetJsonRes(res);
            }));
        }
Beispiel #23
0
        public ActionResult LoginAction(string email, string pass)
        {
            return(RunAction(() =>
            {
                if (!ValidateHelper.IsAllPlumpString(email, pass))
                {
                    return GetJsonRes("账户密码不能为空");
                }

                //检查登录尝试
                var err_count = _LoginErrorLogBll.GetRecentLoginErrorTimes(email);
                if (err_count > 5)
                {
                    return GetJsonRes($"你短时间内有{err_count}次错误登录记录,请稍后再试");
                }
                //开始登录
                string msg = string.Empty;
                var model = _IUserService.LoginByPassWord(email, pass, ref msg);
                if (model != null && model.UserToken?.Length > 0)
                {
                    //记录登录状态
                    AppContext.GetObject <LoginStatus>().SetUserLogin(loginuser: new LoginUserInfo()
                    {
                    });
                    return GetJson(new { success = true, msg = "登陆成功" });
                }
                //登录错误,记录错误记录
                var errorLoginLog = new LoginErrorLogModel()
                {
                    LoginKey = ConvertHelper.GetString(email),
                    LoginPwd = ConvertHelper.GetString(pass),
                    LoginIP = ConvertHelper.GetString(this.X.IP),
                    LoginTime = DateTime.Now
                };
                var errorloghandler = _LoginErrorLogBll.AddLoginErrorLog(errorLoginLog);
                if (ValidateHelper.IsPlumpString(errorloghandler))
                {
                    LogHelper.Info(this.GetType(), "记录错误登录日志错误:" + errorloghandler);
                }

                return GetJson(new { success = false, msg = msg });
            }));
        }
Beispiel #24
0
        /// <summary>
        /// 保存标签
        /// </summary>
        /// <param name="mapkey"></param>
        /// <param name="maptype"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public string SaveTagsMap(string mapkey, string maptype, List <string> tags)
        {
            if (!ValidateHelper.IsAllPlumpString(mapkey, maptype))
            {
                return("参数错误");
            }
            tags = ConvertHelper.NotNullList(tags).Where(x => ValidateHelper.IsPlumpString(x)).Distinct().ToList();
            var mapdal      = new TagMapDal();
            var deletedlist = mapdal.GetList(x => x.MapKey == mapkey && x.MapType == maptype);

            if (deletedlist == null)
            {
                deletedlist = new List <TagMapModel>();
            }

            //交集(不用删除,不用添加)
            var mixlist = Com.GetInterSection(deletedlist.Select(x => x.TagName).Distinct().ToList(), tags);

            //不是交集内的数据删除
            deletedlist = deletedlist.Where(x => !mixlist.Contains(x.TagName)).ToList();
            //不是交集内的数据添加
            tags = tags.Where(x => !mixlist.Contains(x)).ToList();

            if (ValidateHelper.IsPlumpList(deletedlist))
            {
                if (mapdal.Delete(deletedlist.ToArray()) != deletedlist.Count())
                {
                    return("清理旧数据失败");
                }
            }
            if (!ValidateHelper.IsPlumpList(tags))
            {
                return(SUCCESS);
            }
            var addlist = tags.Select(x => new TagMapModel()
            {
                MapKey  = mapkey,
                TagName = x,
                MapType = maptype
            }).ToList();

            return(mapdal.Add(addlist.ToArray()) == addlist.Count() ? SUCCESS : "保存失败");
        }
        public static async Task <string> BaiduTranslate(string q, string from, string to)
        {
            if (!ValidateHelper.IsAllPlumpString(q))
            {
                return(q);
            }
            if (!ValidateHelper.IsAllPlumpString(from, to))
            {
                throw new Exception("from or to is empty");
            }

            var appid      = "20160923000029191";
            var securityid = "4rjkaBYXiu1IK7QsvBOh";
            var salt       = Com.GetRandomNumString(10);
            var md5        = SecureHelper.GetMD5($"{appid}{q}{salt}{securityid}").ToLower();

            //q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
            var url   = "http://api.fanyi.baidu.com/api/trans/vip/translate";
            var trans = string.Empty;

            var dict = new Dictionary <string, string>();

            dict["q"]     = EncodingHelper.UrlEncode(q);
            dict["from"]  = from;
            dict["to"]    = to;
            dict["appid"] = appid;
            dict["salt"]  = salt;
            dict["sign"]  = md5;

            var urlparam = $"{url}?{dict.ToUrlParam()}";

            //trans = await HttpClientHelper.GetAsync(urlparam);
            trans = await p.ExecuteAsync(async() => await HttpClientHelper.GetAsync(urlparam));

            if (!ValidateHelper.IsPlumpString(trans))
            {
                throw new Exception("翻译失败");
            }
            return(trans);
        }
Beispiel #26
0
        private async Task GetEndpointData(string path)
        {
            if (!this.IsEndpointLevel(path))
            {
                return;
            }
            try
            {
                var bs = await this.Client.GetDataOrThrow_(path, this._node_watcher);

                if (!ValidateHelper.IsPlumpList(bs))
                {
                    await this.Client.DeleteNodeRecursively_(path);

                    return;
                }
                var data = this._serializer.Deserialize <AddressModel>(bs) ??
                           throw new ArgumentNullException("address model");
                if (!ValidateHelper.IsAllPlumpString(data.ServiceNodeName, data.EndpointNodeName, data.Url))
                {
                    throw new Exception($"address model数据错误:{data.ToJson()}");
                }
                var service_info = this.GetServiceAndEndpointNodeName(path);
                data.ServiceNodeName  = service_info.service_name;
                data.EndpointNodeName = service_info.endpoint_name;

                this._endpoints.RemoveWhere_(x => x.FullPathName == data.FullPathName);
                this._endpoints.Add(data);

                if (this.OnServiceChangedAsync != null)
                {
                    await this.OnServiceChangedAsync.Invoke();
                }
            }
            catch (Exception e)
            {
                e.AddErrorLog($"读取节点数据失败:{path}");
            }
        }
Beispiel #27
0
        /// <summary>
        /// post请求子站回调页面,请求子站主动验证token是否正确
        /// </summary>
        /// <param name="url"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public ActionResult PostChildCallBack(string url, string callback)
        {
            //这里不要用actionhelper,那么跳转逻辑会复杂
            var loginuser = this.X.LoginUser;

            if (loginuser == null)
            {
                return(GoHome());
            }

            //没有子站信息就跳转默认页
            if (!ValidateHelper.IsAllPlumpString(url, callback))
            {
                return(GoHome());
            }

            ViewData["token"]    = loginuser.LoginToken;
            ViewData["uid"]      = loginuser.UserID;
            ViewData["url"]      = url;
            ViewData["callback"] = callback;
            return(View());
        }
Beispiel #28
0
        public async Task <ActionResult> CloseOrOpen(string issue_uid, string open)
        {
            return(await RunActionAsync(async() =>
            {
                if (!ValidateHelper.IsAllPlumpString(issue_uid, open))
                {
                    throw new NoParamException();
                }

                var org_uid = this.GetSelectedOrgUID();
                var loginuser = await this.ValidMember(org_uid, this.MemberRole);

                var data = await this._issueService.OpenOrClose(issue_uid, loginuser.UserID, !open.ToBool());

                if (data.error)
                {
                    return GetJsonRes(data.msg);
                }

                return GetJsonRes(string.Empty);
            }));
        }
Beispiel #29
0
 private void CheckInputData(DeviceInputData model)
 {
     if (!ValidateHelper.IsPlumpString(model.OrgUID))
     {
         throw new MsgException("组织UID为空");
     }
     if (!ValidateHelper.IsPlumpString(model.DeviceUID))
     {
         throw new MsgException("设备UID为空");
     }
     if (!ValidateHelper.IsPlumpString(model.UserUID))
     {
         throw new MsgException("用户UID为空");
     }
     if (!ValidateHelper.IsPlumpList(model.Data))
     {
         throw new MsgException("数据为空");
     }
     if (!model.Data.All(x => ValidateHelper.IsAllPlumpString(x.ParamUID, x.ValueJson)))
     {
         throw new MsgException("提交数据存在错误");
     }
 }
        public async Task <_ <LoginUserInfo> > FindUserByTokenAsync(string access_token, string client_id)
        {
            var data = new _ <LoginUserInfo>();

            if (!ValidateHelper.IsAllPlumpString(access_token, client_id))
            {
                data.SetErrorMsg("参数为空");
                return(data);
            }

            var hit_status   = CacheHitStatusEnum.Hit;
            var cache_expire = TimeSpan.FromMinutes(5);

            var cache_key = AuthCacheKeyManager.TokenKey(access_token);

            //查找token
            var token = await this._cache.GetOrSetAsync(cache_key, async() =>
            {
                hit_status = CacheHitStatusEnum.NotHit;

                return(await this._IAuthTokenService.FindTokenAsync(client_id, access_token));
            }, cache_expire);

            var Actor = ActorsManager <CacheHitLogActor> .Instance.DefaultClient;

            //统计缓存命中
            Actor?.Tell(new CacheHitLog(cache_key, hit_status));

            if (token == null)
            {
                data.SetErrorMsg("token不存在");
                return(data);
            }

            hit_status = CacheHitStatusEnum.Hit;
            cache_key  = AuthCacheKeyManager.UserInfoKey(token.UserUID);
            //查找用户
            var loginuser = await this._cache.GetOrSetAsync(cache_key, async() =>
            {
                hit_status = CacheHitStatusEnum.NotHit;

                var user = await this._IAuthLoginService.GetUserInfoByUID(token.UserUID);
                return(user);
            }, cache_expire);

            //统计缓存命中
            Actor?.Tell(new CacheHitLog(cache_key, hit_status));

            if (loginuser == null)
            {
                data.SetErrorMsg("用户不存在");
                return(data);
            }

            loginuser.LoginToken   = token.UID;
            loginuser.RefreshToken = token.RefreshToken;
            loginuser.TokenExpire  = token.ExpiryTime;
            loginuser.Scopes       = token.Scopes?.Select(x => x.Name).ToList();

            data.SetSuccessData(loginuser);

            return(data);
        }