Exemple #1
0
        public IHttpActionResult Put(MemberInvitePutRequest requestData)
        {
            var requestService = new RequestDataHelper <MemberInvitePutRequest>();
            var checkColumnKey = new string[1] {
                "token"
            };
            var checkEmpty = requestService.CheckColumnEmpty(requestData, checkColumnKey);
            var response   = new Infrastructure.ViewModel.Base.BaseResponse <List <MemberInvite> >();

            response.Success = false;
            response.Data    = new List <MemberInvite>();
            if (checkEmpty == false)
            {
                response.Message = "遺漏參數";
                response.State   = Infrastructure.ViewModel.Base.LogState.RequestDataError;
                return(Content(HttpStatusCode.BadRequest, response));
            }
            var responseData = memberInviteService.Update(requestData);

            if (responseData != null)
            {
                response.Success = true;
                response.Message = "更新成功";
                response.Data    = responseData.ToList();
            }
            else
            {
                response.Message = "更新失敗";
                response.State   = Infrastructure.ViewModel.Base.LogState.Error;
            }
            return(Ok(response));
        }
Exemple #2
0
        public IHttpActionResult Post(MemberInvitePostRequest requestData)
        {
            var requestService = new RequestDataHelper <MemberInvitePostRequest>();
            var checkColumnKey = new string[4] {
                "token", "circlekey", "roletype", "inviteemail"
            };
            var checkEmpty = requestService.CheckColumnEmpty(requestData, checkColumnKey);
            var response   = new Infrastructure.ViewModel.Base.BaseResponse <bool>();

            response.Success = false;

            if (checkEmpty == false)
            {
                response.Message = "遺漏參數";
                response.State   = Infrastructure.ViewModel.Base.LogState.RequestDataError;
                return(Content(HttpStatusCode.BadRequest, response));
            }
            var responseData = memberInviteService.Create(requestData);

            response.Data = responseData;
            if (responseData)
            {
                response.Success = true;
                response.Message = "建立成功";
            }
            else
            {
                response.Message = "建立失敗";
                response.State   = Infrastructure.ViewModel.Base.LogState.Error;
            }
            return(Ok(response));
        }
Exemple #3
0
        private IList <SqlBuildModel> SqlBuilderModel(string scriptCode, IDictionary <string, object> parameters, object bodyJson)
        {
            Lua lua = this.GetLua();
            var res = LuaScriptRunner.ExecuteLuaScript(lua, scriptCode, parameters, bodyJson);
            IList <SqlBuildModel> result = new List <SqlBuildModel>();

            for (var i = 0; i < res.Length; i++)
            {
                var item = res[i];
                if (item is LuaTable)
                {
                    var            table         = (LuaTable)item;
                    var            extraParams   = LuaScriptRunner.LuaTableToCSharpData <IDictionary <string, object> >(table["ExtraParams"]);
                    var            sqlParameters = RequestDataHelper.MergeDictionary(parameters, extraParams);//合并附加参数到sql执行参数中
                    IList <object> relationKeys  = LuaScriptRunner.LuaTableToCSharpData <IList <object> >(table["RelationKeys"]);
                    long           codeKind      = table["CodeKind"] == null ? 0 : (long)table["CodeKind"];
                    string         key           = (string)table["Key"];
                    var            model         = new SqlBuildModel {
                        Sql = (string)table["Sql"], Parameters = sqlParameters, CodeKind = codeKind, RelationKeys = relationKeys, Key = key
                    };
                    result.Add(model);
                    this.ChildSqlBuilderModel(parameters, model, LuaScriptRunner.LuaTableToCSharpData <object>(table["Children"]));
                }
                else
                {
                    throw new CustomException(99, "构建SQL的脚本返回有误");
                }
            }
            return(result);
        }
Exemple #4
0
        public object Test([FromForm] dynamic form)
        {
            IDictionary <string, object> parameters = RequestDataHelper.GetMixParams();
            var files = RequestDataHelper.GetAllFiles();

            return(null);
        }
Exemple #5
0
 //递归解析主从查询的从查询
 private void ChildSqlBuilderModel(IDictionary <string, object> parameters, SqlBuildModel parentModel, object children)
 {
     if (children == null || !(children is IEnumerable <KeyValuePair <string, object> > || children is IList <object>))
     {
         return;
     }
     if (children is IEnumerable <KeyValuePair <string, object> > )
     {
         var child       = (IDictionary <string, object>)children;
         var extraParams = !child.ContainsKey("ExtraParams") ? null : (IDictionary <string, object>)child["ExtraParams"];
         parameters = RequestDataHelper.MergeDictionary(parameters, extraParams);//合并附加参数到sql执行参数中
         IList <object> relationKeys = !child.ContainsKey("RelationKeys") ? null : (IList <object>)child["RelationKeys"];
         long           codeKind     = child.ContainsKey("CodeKind") ? (long)child["CodeKind"] : 0;
         string         key          = (string)child["Key"];
         var            model        = new SqlBuildModel {
             Sql = (string)child["Sql"], Parameters = parameters, CodeKind = codeKind, RelationKeys = relationKeys, Key = key
         };
         if (parentModel.Children == null)
         {
             parentModel.Children = new List <SqlBuildModel>();
         }
         parentModel.Children.Add(model);
         object nextChildren = child.ContainsKey("Children") ? child["Children"] : null;
         this.ChildSqlBuilderModel(parameters, model, nextChildren);
     }
     else
     {
         foreach (var child in (IList <object>)children)
         {
             this.ChildSqlBuilderModel(parameters, parentModel, child);
         }
     }
 }
        public IHttpActionResult Get([FromUri] string strAccess)
        {
            var requestData    = JsonConvert.DeserializeObject <MemberInvitePostRequest>(strAccess);
            var requestService = new RequestDataHelper <MemberInvitePostRequest>();
            var checkColumnKey = new string[3] {
                "token", "circlekey", "invitetype"
            };
            var checkEmpty = requestService.CheckColumnEmpty(requestData, checkColumnKey);
            var response   = new Infrastructure.ViewModel.Base.BaseResponse <bool>();

            response.Success = false;
            if (checkEmpty == false)
            {
                response.Message = "遺漏參數";
                response.State   = Infrastructure.ViewModel.Base.LogState.RequestDataError;
                return(Content(HttpStatusCode.BadRequest, response));
            }
            var responseData = memberInviteService.GetLearningInviteStatus(requestData.Token, requestData.CircleKey.ToLower(), requestData.InviteType);

            response.Data    = responseData;
            response.Success = true;
            if (responseData)
            {
                response.Message = "啟用邀請";
            }
            else
            {
                response.Message = "停用邀請";
            }
            return(Ok(response));
        }
Exemple #7
0
        public void SaveParam([FromBody] dynamic model)
        {
            IDictionary <string, object> parameters = RequestDataHelper.GetMixParams();

            if (parameters.Count > 0)
            {
                _configBll.SaveParam(parameters);
            }
        }
Exemple #8
0
        /// <summary>
        /// 外部调用接口
        /// </summary>
        /// <param name="code">接口编码</param>
        /// <param name="inputParameters">可传入参数</param>
        /// <returns></returns>
        public object DynamicFetch(IDictionary <string, object> config, string code, IDictionary <string, object> inputParameters = null)
        {
            string dataBaseKey        = config.GetValue <string>("DataBaseKey");
            string pluginAssemblyPath = config.GetValue <string>("PluginAssemblyPath");
            string pluginClassName    = config.GetValue <string>("PluginClassName");

            threadLocalDataBaseKey.Value = dataBaseKey;
            ConfigApiPlugin dynamicApiPlugin = ReflectorHelper.GetPluginInstance <ConfigApiPlugin>(pluginAssemblyPath, pluginClassName);
            IDictionary <string, object>             parameters = RequestDataHelper.GetMixParams();
            IDictionary <string, IList <IFormFile> > files      = RequestDataHelper.GetAllFiles();
            IDictionary <string, object>             headers    = RequestDataHelper.GetHeaders();
            IDictionary <string, object>             cookies    = RequestDataHelper.GetCookies();
            object bodyJson = RequestDataHelper.GetBodyJsonParameters();

            if (inputParameters != null && inputParameters.Count > 0)
            {
                parameters = RequestDataHelper.MergeDictionary(parameters, inputParameters);
            }
            return(this.AopDynamicApi <object>((apiConfig, paramsData, formFiles, reqHeaders, reqCookies, json) =>
            {
                if (dynamicApiPlugin != null)
                {
                    IDbHelper dbHelper = this._dbContext.Use(dataBaseKey);
                    //调用接口前扩展处理
                    dynamicApiPlugin.Before(dbHelper, apiConfig, paramsData, formFiles, json);
                }
            }, (apiConfig, paramsData, json) =>
            {
                string scriptCode = apiConfig.GetValue <string>("ScriptCode");

                /*
                 * 1=单一结果(单个值,或者一条sql语句执行结果)
                 * 2=分页
                 * 3=列表结果集(多个值以List<object>返回
                 * 4=字典结果集(多个值以Dictionary<string,object>返回
                 * 5=主从结果集 (会查询嵌套子查询,多个值以Dictionary<string,object>返回
                 * 6=返回脚本执行结果(直接返回脚本执行结果)
                 */
                int codeKind = apiConfig.GetValue <int>("CodeKind");
                int apiKind = apiConfig.GetValue <int>("ApiKind"); //0=公共接口;1=对内接口
                int status = apiConfig.GetValue <int>("Status");   //0=禁用;1=启用
                return this.ExecuteScript(scriptCode, codeKind, paramsData, bodyJson);
            }, (apiConfig, paramsData, json, result) =>
            {
                if (dynamicApiPlugin != null)
                {
                    IDbHelper dbHelper = this._dbContext.Use(dataBaseKey);
                    //调用接口后扩展处理
                    return dynamicApiPlugin.After(dbHelper, apiConfig, paramsData, json, result);
                }
                return result;
            }, config, parameters, files, headers, cookies, bodyJson));
        }
Exemple #9
0
        private void ConvertParamsType(int paramType, string paramCode)
        {
            //0 = String,1 = Integer,2 = Long,3 = Double,4 = Float,5 = Decimal,6 = Boolean,7 = Date,8 = DateTime,9=Ulong,10 = Key/Value,11 = List,12 = File
            IDictionary <string, object> mixParams   = RequestDataHelper.GetMixParams();
            IDictionary <string, object> queryParams = RequestDataHelper.GetQueryParameters();
            IDictionary <string, object> formParams  = RequestDataHelper.GetFormParameters();
            object bodyJson = RequestDataHelper.GetBodyJsonParameters();

            this.ConvertParamsType(mixParams, paramType, paramCode);
            this.ConvertParamsType(queryParams, paramType, paramCode);
            this.ConvertParamsType(formParams, paramType, paramCode);
            this.ConvertParamsType(bodyJson, paramType, paramCode);
        }
Exemple #10
0
        private void GetUserClaimsPrincipal(IDictionary <string, object> config)
        {
            string tokenStr = this.GetToken();

            if (!IsCanReadToken(tokenStr))
            {
                throw new CustomException(1, "无效token");
            }
            HttpContext context = RequestDataHelper.GetHttpContext();

            if (context != null)
            {
                context.User = this.ValidateToken(config, tokenStr);
            }
        }
Exemple #11
0
 public void SaveGroup([FromBody] dynamic model)
 {
     try
     {
         IDictionary <string, object> parameters = RequestDataHelper.GetMixParams();
         if (parameters.Count > 0)
         {
             _configBll.SaveGroup(parameters);
         }
     }
     catch (Exception e) {
         _logger.LogError(e, "接口分组配置异常");
         throw;
     }
 }
        public override void InitParams()
        {
            base.InitParams();
            //将登录信息缓存入系统变量字典
            var context = RequestDataHelper.GetHttpContext();
            if (context.User != null)
            {
                Claim claim = context.User.FindFirst(ClaimTypes.Sid);
                if (claim != null)
                {
                    string userId = claim.Value;
                    ParamsPlugin.Set("UserId", long.Parse(userId == "" ? "0" : userId));
                }

            }
        }
Exemple #13
0
        public object Login([FromBody] dynamic model)
        {
            IDictionary <string, object> parameters = RequestDataHelper.GetMixParams();
            string username = parameters["username"].ToString();
            string password = parameters["password"].ToString();

            if (_configuration.GetValue <string>("AdminAccount:Account") == username && _configuration.GetValue <string>("AdminAccount:Password") == password)
            {
                HttpContext.Session.SetString("User", JsonConvert.SerializeObject(parameters));
                //跳转到系统首页
                return(RsaCryptoUtils.GetPublicKey());
            }
            else
            {
                throw new CustomException(11, "用户名或密码错误");
            }
        }
Exemple #14
0
        /// <summary>
        /// 验证token,并获取其中的信息
        /// </summary>
        /// <param name="tokenStr"></param>
        /// <returns></returns>
        private ClaimsPrincipal ValidateToken(IDictionary <string, object> config, string tokenStr)
        {
            try
            {
                tokenStr = tokenStr.Substring(7);
                string securityKey = (string)config["SecurityKey"];
                byte[] aesKeyByte  = Encoding.UTF8.GetBytes(AppConfigurtaionHelper.Configuration.GetValue <string>("AesCrypto:Key"));
                byte[] aesIvByte   = Encoding.UTF8.GetBytes(AppConfigurtaionHelper.Configuration.GetValue <string>("AesCrypto:Iv"));
                securityKey = AesCryptoUtils.Decrypt(securityKey, aesKeyByte, aesIvByte);
                var jwtTokenHandler = new JwtSecurityTokenHandler();
                var tokenParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,

                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)),    // 加密解密Token的密钥

                    // 是否验证发布者
                    ValidateIssuer = true,
                    // 发布者名称
                    ValidIssuer = (string)config["Issuer"],

                    // 是否验证订阅者
                    ValidateAudience = true,
                    // 订阅者名称
                    ValidAudience = (string)config["Audience"],

                    // 是否验证令牌有效期
                    ValidateLifetime = true,
                    //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    ClockSkew = TimeSpan.FromMinutes((int)config["ClockSkew"])
                };
                SecurityToken securityToken;
                return(jwtTokenHandler.ValidateToken(tokenStr, tokenParameters, out securityToken));
            }
            catch (SecurityTokenExpiredException e)
            {
                RequestDataHelper.GetHttpContext().Response.Headers.Add("Token-Expired", "true");
                throw new CustomException(2, "token已过期");
            }
            catch (Exception e)
            {
                throw new CustomException(1, "无效token");
            }
        }
 public override void Before(IDbHelper db, IDictionary <string, object> config, IEnumerable <KeyValuePair <string, object> > parameters, IDictionary <string, IList <IFormFile> > files, object bodyJson)
 {
     try
     {
         IDictionary <string, object> paramDic = (IDictionary <string, object>)parameters;
         IDictionary <string, object> dic      = this.GetOpenId(paramDic.GetValue <string>("code"));
         string sessionKey = dic.GetValue <string>("session_key");
         string iv         = paramDic.GetValue <string>("iv");
         _logger.LogInformation($"sessionKey={sessionKey}\niv={iv}\nencryptedData={paramDic.GetValue<string>("encryptedData")}");
         string res = AesCryptoUtils.Decrypt(paramDic.GetValue <string>("encryptedData"), Convert.FromBase64String(sessionKey), Convert.FromBase64String(iv));
         IDictionary <string, object> userInfo = JsonConvert.DeserializeObject <IDictionary <string, object> >(res);
         //将用户信息合并到一个字典中
         RequestDataHelper.MergeDictionary(ref paramDic, dic, userInfo);
     }
     catch (Exception e) {
         _logger.LogError(e, "登录验证扩展异常");
         throw;
     }
 }
        public IHttpActionResult Put([FromBody] MemberInvitePostRequest requestData)
        {
            var requestService = new RequestDataHelper <MemberInvitePostRequest>();
            var checkColumnKey = new string[3] {
                "token", "circlekey", "invitetype"
            };
            var checkEmpty = requestService.CheckColumnEmpty(requestData, checkColumnKey);
            var response   = new Infrastructure.ViewModel.Base.BaseResponse <bool>();

            response.Success = false;

            if (checkEmpty == false)
            {
                response.Message = "遺漏參數";
                response.State   = Infrastructure.ViewModel.Base.LogState.RequestDataError;
                return(Content(HttpStatusCode.BadRequest, response));
            }

            var authService     = new AuthService();
            var checkManageAuth = authService.CheckCourseManageAuth(requestData.Token, requestData.CircleKey.ToLower());

            //除了課程管理者可以修改邀請開關,其他角色都不得設定
            if (checkManageAuth == null || checkManageAuth.CircleMemberSetting.AddCircleMember == false)
            {
                response.Message = "無權限邀請";
                response.State   = Infrastructure.ViewModel.Base.LogState.Error;
                return(Ok(response));
            }
            var responseData = memberInviteService.UpdateLearningInviteStatus(requestData.Token, requestData.CircleKey.ToLower(), requestData.InviteType);

            response.Data    = responseData;
            response.Success = true;
            if (responseData)
            {
                response.Message = "啟用邀請";
            }
            else
            {
                response.Message = "停用邀請";
            }
            return(Ok(response));
        }
Exemple #17
0
        /// <summary>
        /// 取得邀請碼資訊
        /// </summary>
        /// <param name="strAccess"></param>
        /// <returns></returns>
        public IHttpActionResult Get(string strAccess)
        {
            var requestData    = JsonConvert.DeserializeObject <MemberInviteGetRequest>(strAccess);
            var requestService = new RequestDataHelper <MemberInviteGetRequest>();
            var checkColumnKey = new string[3] {
                "token", "circlekey", "ismaincode"
            };
            var checkEmpty = requestService.CheckColumnEmpty(requestData, checkColumnKey);
            var response   = new Infrastructure.ViewModel.Base.BaseResponse <IEnumerable <Infrastructure.Entity.MemberInvite> >();

            response.Success = false;
            response.Data    = new List <Infrastructure.Entity.MemberInvite>();
            if (checkEmpty == false)
            {
                response.State   = Infrastructure.ViewModel.Base.LogState.RequestDataError;
                response.Message = "遺漏參數";
                return(Content(HttpStatusCode.BadRequest, response));
            }
            var responseData = memberInviteService.GetList(requestData.CircleKey.ToLower(), 0, null);

            if (requestData.IsMainCode)
            {
                responseData = responseData.Where(t => t.Enable == true && t.IsCourseCode == true);
            }
            if (responseData == null)
            {
                response.Message = "查無資訊";
                response.State   = Infrastructure.ViewModel.Base.LogState.Error;
            }
            else
            {
                response.Success = true;
                response.Message = "查詢成功";
                response.Data    = responseData;
            }
            return(Ok(response));
        }
Exemple #18
0
        private string GetToken()
        {
            var headers = RequestDataHelper.GetHeaders();

            return(headers.ContainsKey("Authorization") ? headers["Authorization"].ToString() : "");
        }
Exemple #19
0
        public void BatchDelete([FromBody] dynamic model)
        {
            JArray parameters = (JArray)RequestDataHelper.GetBodyJsonParameters();

            _configBll.BatchDeleteApi(parameters);
        }
Exemple #20
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     RequestDataHelper.InitParams(context.HttpContext);
     base.OnActionExecuting(context);
 }
 public async Task Invoke(HttpContext context)
 {
     RequestDataHelper.InitParams(context);
     await this._next(context);
 }
Exemple #22
0
 /// <summary>
 /// 参数验证
 /// </summary>
 /// <param name="code">接口编码</param>
 private void ParamsCheck(string code, IDictionary <string, object> config, IDictionary <string, object> inputParameters)
 {
     using (Lua lua = new Lua())
     {
         lua.State.Encoding = Encoding.UTF8;
         //参数整体验证
         string checkScript = config["CheckScript"].ToString();
         IDictionary <string, object> parameters = RequestDataHelper.GetMixParams();
         object bodyJson = RequestDataHelper.GetBodyJsonParameters();
         IDictionary <string, IList <IFormFile> > fileDic = RequestDataHelper.GetAllFiles();
         if (!string.IsNullOrWhiteSpace(checkScript))
         {
             object[] result = LuaScriptRunner.ExecuteLuaScript(lua, checkScript, parameters, bodyJson);//第一个返回值为验证是否通过(true|false),第二个参数为验证错误信息,为true时没有
             if (!(bool)result[0])
             {
                 if (result.Length > 1)
                 {
                     throw new CustomException(11, result[1].ToString());//通过自定义异常抛出验证失败信息
                 }
                 else
                 {
                     throw new CustomException(11, "参数验证失败");
                 }
             }
         }
         IDictionary <string, object> paramData = new Dictionary <string, object>(parameters);
         //单个参数验证
         IList <IDictionary <string, object> > apiParams = _dal.GetApiParams(code);//配置参数信息
         if (apiParams.Count > 0)
         {
             foreach (IDictionary <string, object> dic in apiParams)
             {
                 int    paramType        = (int)dic["ParamType"]; //0 = String,1 = Integer,2 = Long,3 = Double,4 = Float,5 = Decimal,6 = Boolean,7 = Date,8 = DateTime,9=Ulong,10 = Key/Value,11= List,12 = File
                 string paramCode        = dic["ParamCode"].ToString();
                 string paramName        = dic["ParamName"].ToString();
                 short  isRequire        = (short)dic["IsRequire"];
                 short  paramsKind       = (short)dic["ParamsKind"];      //ParamsKind 0 = 普通参数;1 = 系统参数;2=Id值;
                 string checkRule        = dic["CheckRule"].ToString();   //验证使用的正则表达式
                 string ruleError        = dic["RuleError"].ToString();   //正则表达式验证不通过时候的错误提示信息
                 string paramCheckScript = dic["CheckScript"].ToString(); //验证单个参数的lua脚本
                 if (paramsKind == 1)
                 {
                     if (isRequire == 1 && !ParamsPlugin.ContainsKey(paramCode))
                     {
                         throw new CustomException(11, "系统参数" + paramName + "不能为空");
                     }
                     var sysParamValue = ParamsPlugin.Get(paramCode);
                     if (isRequire == 1 && sysParamValue == null)
                     {
                         throw new CustomException(11, "系统参数" + paramName + "不能为空");
                     }
                     inputParameters[paramCode] = sysParamValue;
                     paramData[paramCode]       = sysParamValue;
                 }
                 else if (paramsKind == 2)
                 {
                     var id = DbHelper.NewLongId();
                     inputParameters[paramCode] = id;
                     paramData[paramCode]       = id;
                 }
                 //检查必录项
                 if (isRequire == 1)
                 {
                     this.CheckRequire(paramType, paramCode, paramName, paramData, fileDic);
                 }
                 //正则检查
                 if (!string.IsNullOrWhiteSpace(checkRule))
                 {
                     this.CheckRegexRule(paramType, paramCode, paramName, checkRule, ruleError, paramData);
                 }
                 //脚本验证
                 if (!string.IsNullOrWhiteSpace(paramCheckScript))
                 {
                     this.LuaScriptCheck(lua, paramType, paramCode, paramName, paramCheckScript, paramData);
                 }
                 //转换参数类型
                 this.ConvertParamsType(paramType, paramCode);
             }
         }
     }
 }