示例#1
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;

            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);
            string  table  = $"{config["table"]}";

            if (string.IsNullOrEmpty(table))
            {
                return new { error = "No table Specified." }
            }
            ;

            string idField = config["id"]?.ToString();

            if (string.IsNullOrEmpty(idField))
            {
                return new { error = "No id field Specified." }
            }
            ;

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // Form document
            var data = JsonConvert.DeserializeObject <JObject>(WebTools.GetBody(context));

            // Complete external relationships
            var externals = (JArray)config["externals"];

            if (externals != null)
            {
                foreach (var external in externals)
                {
                    var extTable      = $"{external["table"]}";
                    var extIdField    = $"{external["id"]}";
                    var mapping       = external["mapping"];
                    var relationships = (JArray)external["relationships"];

                    if (mapping != null)
                    {
                        // for each value create new record on external
                        var source    = (JArray)data[$"{mapping["source"]}"];
                        var sourceKey = $"{mapping["sourceKey"]}";

                        // fetch existing records
                        IList <string> where = new List <string>();
                        if (relationships != null)
                        {
                            foreach (var relationship in relationships)
                            {
                                where.Add($"{relationship["target"]} = {data[$"{relationship["source"]}"]}");
                            }
                        }

                        try
                        {
                            var existingRecordIds = db
                                                    .Query($"SELECT {extIdField} FROM {extTable} WHERE {string.Join(" AND ", where)}")
                                                    .Select(x => $"{x[extIdField]}");

                            // delete from existingRecords
                            var sourceRecordIds = source.Select(x => $"{x[sourceKey]}");
                            var tobeDeleteIds   = existingRecordIds.Except(sourceRecordIds);
                            foreach (var item in tobeDeleteIds)
                            {
                                SQL_Delete.Delete(db, extTable, item, extIdField);
                            }
                        }
                        catch { }


                        foreach (var item in source)
                        {
                            // new record
                            var record = new Dictionary <string, object>();

                            // fill up the record with foreign key relationship
                            if (relationships != null)
                            {
                                foreach (var relationship in relationships)
                                {
                                    record[$"{relationship["target"]}"] = $"{data[$"{relationship["source"]}"]}";
                                }
                            }

                            // fill up the mapping value
                            var type = $"{mapping["type"]}";
                            if (type == "object")
                            {
                                var targets = (JArray)mapping["targets"];
                                if (targets != null)
                                {
                                    foreach (var target in targets)
                                    {
                                        record[$"{target["target"]}"] = $"{item[$"{target["source"]}"]}";
                                    }
                                }
                            }

                            // find the key
                            if (sourceKey != null && item[sourceKey] != null)
                            {
                                // update
                                record[extIdField] = $"{item[sourceKey]}";
                                Update(db, extTable, record, extIdField);
                            }
                            else
                            {
                                // insert
                                SQL_Insert.Insert(db, extTable, record, extIdField);
                            }
                        }
                    }
                }
            }

            // Exclude data
            var excludeFields = (config["excludeFields"] as JArray)?.ToObject <string[]>();

            if (excludeFields != null)
            {
                foreach (var excludeField in excludeFields)
                {
                    data.Remove(excludeField);
                }
            }

            // set default fields
            var updatedData = SetDefaults(context, config, data);

            // Update
            var doc_id = Update(db, table, updatedData, idField);

            // Return Result
            return(new { _id = data[idField] });
        }
示例#2
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // Calculate Pagination
            string page = WebTools.Get(context, "page"); if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            string size = WebTools.Get(context, "size"); if (string.IsNullOrEmpty(size))
            {
                size = "10";
            }

            // Query Options - Sort
            var sort = new List <string>();

            if (WebTools.GetArray(context, "_sort")?.Count() > 0)
            {
                foreach (var sortKey in WebTools.GetArray(context, "_sort"))
                {
                    sort.Add($"{sortKey}");
                }
            }

            if (WebTools.GetArray(context, "_sort_desc")?.Count() > 0)
            {
                foreach (var sortKey in WebTools.GetArray(context, "_sort_desc"))
                {
                    sort.Add($"{sortKey} DESC");
                }
            }

            // Query - Filters
            var where = new List <string>();
            var parameters = new Dictionary <string, object>();

            // get body
            var data = JsonConvert.DeserializeObject <JObject>(WebTools.GetBody(context));

            if (data == null)
            {
                data = new JObject();
            }

            // append querystring to the data
            foreach (var key in context.Request.Query.Keys)
            {
                data[key] = new JArray(context.Request.Query[key].ToArray());
            }

            string[] searchFields = config["searchFields"]?.ToObject <string[]>();
            if (data != null && data.Count > 0)
            {
                foreach (var item in data)
                {
                    string parameterName = item.Key
                                           .Replace(".", "_")
                                           .Replace("_lte", "")
                                           .Replace("_gte", "")
                                           .Replace("_lt", "")
                                           .Replace("_gt", "")
                    ;

                    if (item.Key == "page")
                    {
                        continue;
                    }
                    else if (item.Key == "size")
                    {
                        continue;
                    }
                    else if (item.Key == "_export")
                    {
                        continue;
                    }
                    else if (item.Key == "_aggregation")
                    {
                        continue;
                    }
                    else if (item.Key == "_sort")
                    {
                        continue;
                    }
                    else if (item.Key == "_sort_desc")
                    {
                        continue;
                    }

                    // search keyword
                    else if (item.Key == "_search" && searchFields != null)
                    {
                        if (string.IsNullOrEmpty($"{item.Value.FirstOrDefault()}") == false)
                        {
                            IList <string> search = new List <string>();
                            foreach (var searchKey in searchFields)
                            {
                                search.Add($"{searchKey} LIKE '%'+@{parameterName}+'%'");
                            }
                            where.Add($"({string.Join(" OR ", search)})");

                            parameters[parameterName] = $"{item.Value.FirstOrDefault()}";
                        }
                        continue;
                    }

                    // range filter
                    else if (item.Key.EndsWith("_date_gte"))
                    {
                        where.Add($"{item.Key.Replace("_gte", "")} >= @{parameterName}");
                    }

                    else if (item.Key.EndsWith("_date_lte"))
                    {
                        where.Add($"{item.Key.Replace("_lte", "")} <= @{parameterName}");
                    }

                    else if (item.Key.EndsWith("_date_gt"))
                    {
                        where.Add($"{item.Key.Replace("_gt", "")} > @{parameterName}");
                    }

                    else if (item.Key.EndsWith("_date_lt"))
                    {
                        where.Add($"{item.Key.Replace("_lt", "")} < @{parameterName}");
                    }

                    // otherwise string filter
                    else
                    {
                        foreach (var str in item.Value)
                        {
                            where.Add($"{item.Key} = @{parameterName}");
                        }
                    }

                    // add to parameters
                    parameters[parameterName] = $"{item.Value.FirstOrDefault()}";
                }
            }

            // check if any filter options exists
            JArray defaultFilters = (JArray)config["defaultFilters"];

            if (defaultFilters != null)
            {
                foreach (var filter in defaultFilters)
                {
                    string filterType = $"{filter["type"]}";
                    switch (filterType)
                    {
                    case "headers":
                        string key    = $"{filter["key"]}";
                        string column = $"{filter["column"]}";

                        if (context.Request.Headers.ContainsKey(key))
                        {
                            where.Add($"{column} = @{column}");
                            parameters[column] = $"{context.Request.Headers[key]}";
                        }
                        break;
                    }
                }
            }

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // get sql list parameters
            string sqlTemplate = $"{config["sql"]}";

            if (string.IsNullOrEmpty(sqlTemplate))
            {
                return new { error = "No sql template specified." }
            }
            ;

            var result = List(
                db
                , sqlTemplate
                , config
                , where
                , parameters
                , sort
                , Int64.Parse(size)
                , Int64.Parse(page));

            var total = Count(db, sqlTemplate, where, parameters);

            // Return Result
            var pagedResult = new
            {
                page,
                size,
                total,
                data = result
            };

            return(JsonConvert.SerializeObject(
                       pagedResult,
                       new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }
                       ));
        }
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                configuration = "{}";
            }
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check if admin
            bool admin = false;

            if (config["admin"] != null && config["admin"].ToObject <bool>() == true)
            {
                admin = true;
            }

            // Get Navigation ID
            string navigation_id = context.Request.Headers["X-App-Key"];

            if (string.IsNullOrEmpty(navigation_id))
            {
                return new { error = "No X-App-Key specified" }
            }
            ;

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // IWebToolsService
            var data = JsonConvert.DeserializeObject <JObject>(WebTools.GetBody(context));

            // error check
            if (data["new_password"] == null)
            {
                return new { error = "new password missing" }
            }
            ;
            if (data["old_password"] == null && !admin)
            {
                return new { error = "current password missing" }
            }
            ;
            if (data["new_password_confirm"] == null && !admin)
            {
                return new { error = "repeated password missing" }
            }
            ;
            if ($"{data["new_password_confirm"]}" != $"{data["new_password"]}" && !admin)
            {
                return new { error = "new password and repeated password mismatch" }
            }
            ;

            // find the user
            // Find Item
            string sql   = $@"SELECT * FROM core_user WHERE _id=@_id";
            var    param = new Dictionary <string, object>();

            param["_id"] = $"{data["_id"]}";

            var results = db.Query(sql, param);

            if (results != null && results.Count() > 0)
            {
                // account exists
                var user = results.First();

                if (admin == false)
                {
                    // check if the password matches
                    if (SecurePasswordHasher.Verify($"{data["old_password"]}", $"{user["password"]}") == false)
                    {
                        return new { error = "password doesn't match" }
                    }
                }
                ;

                // update password
                var password = SecurePasswordHasher.Hash($"{data["new_password"]}");

                // update user
                var updatedId = SQL_Update.Update(
                    db
                    , "core_user"
                    , JsonConvert.DeserializeObject <IDictionary <string, object> >(
                        JsonConvert.SerializeObject(new { password, _id = data["_id"] })
                        )
                    , "_id"
                    );

                // return result
                return(new { id = data["_id"] });
            }

            return(new { error = "not matching user found" });
        }
    }
}
示例#4
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check parameters
            string table = $"{config["table"]}"; if (string.IsNullOrEmpty(table) == true)

            {
                return new { error = "No table specified." }
            }
            ;
            string idField = $"{config["id"]}"; if (string.IsNullOrEmpty(idField) == true)

            {
                return new { error = "No id field specified." }
            }
            ;

            // Get Navigation ID
            string navigation_id = context.Request.Headers["X-App-Key"];

            if (string.IsNullOrEmpty(navigation_id))
            {
                return new { error = "No X-App-Key specified" }
            }
            ;

            // IWebToolsService
            var data = JsonConvert.DeserializeObject <JObject>(WebTools.GetBody(context));

            data["navigation_id"] = navigation_id;

            // Get Group ID
            string[] group_ids = data["group_id"]?.ToObject <string[]>();
            if (group_ids == null || group_ids.Length == 0)
            {
                return(JsonConvert.SerializeObject(new { error = "No Group Specified." }));
            }

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // data validation - id and password is mandatory
            if (string.IsNullOrEmpty($"{data["id"]}") == true)
            {
                return new { error = "id is mandatory field" }
            }
            ;

            // if _id exists - Is it existing user?
            if (data["_id"] != null)
            {
                // Find Item
                string sql = $@"SELECT * FROM core_user WHERE _id=@_id";

                var param = new Dictionary <string, object>();
                param["_id"] = $"{data["_id"]}";

                var results = db.Query(sql, param);
                if (results != null && results.Count() > 0)
                {
                    // account exists
                    var user = results.First();

                    // check if the password matches
                    if (data["password"] != null && $"{user["password"]}" != $"{data["password"]}")
                    {
                        if (SecurePasswordHasher.Verify($"{data["password"]}", $"{user["password"]}") == false)
                        {
                            return new { error = "password doesn't match" }
                        }
                    }
                    ;

                    // update the password
                    if (data["password"] != null)
                    {
                        data["password"] = SecurePasswordHasher.Hash($"{data["password"]}");
                    }

                    // Exclude data
                    var excludeFields = (config["excludeFields"] as JArray)?.ToObject <string[]>();
                    if (excludeFields != null)
                    {
                        foreach (var excludeField in excludeFields)
                        {
                            data.Remove(excludeField);
                        }
                    }

                    var updatedData = SQL_Update.SetDefaults(context, config, data);

                    // update user
                    SQL_Update.Update(db, table, updatedData, idField);

                    // update group
                    UpdateGroup(db, navigation_id, group_ids, $"{data["_id"]}");

                    return(new { _id = data["_id"] });
                }
            }


            // new user creation
            else
            {
                // check if the user with same id already exists
                string sql   = $@"SELECT * FROM core_user WHERE id=@id AND navigation_id=@navigation_id";
                var    param = new Dictionary <string, object>();
                param["id"]            = $"{data["id"]}";
                param["navigation_id"] = navigation_id;

                var results = db.Query(sql, param);
                if (results != null && results.Count() > 0)
                {
                    return new { error = "same id already exists" }
                }
                ;

                // create new user
                data["password"] = SecurePasswordHasher.Hash($"{data["password"]}");
                var updatedData = SQL_Update.SetDefaults(context, config, data);

                // Exclude data
                var excludeFields = (config["excludeFields"] as JArray)?.ToObject <string[]>();
                if (excludeFields != null)
                {
                    foreach (var excludeField in excludeFields)
                    {
                        updatedData.Remove(excludeField);
                    }
                }

                // update user
                var insertedId = SQL_Insert.Insert(db, table, updatedData, idField);

                // update group
                UpdateGroup(db, navigation_id, group_ids, $"{insertedId}");

                return(new { _id = insertedId });
            }
            return(null);
        }
示例#5
0
        public static async Task <object> Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            object result = null;

            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check parameters
            string url = $"{config["url"]}";

            if (string.IsNullOrEmpty(url) == true)
            {
                return new { error = "No url specified." }
            }
            ;

            // send request
            using (HttpClient client = new HttpClient())
            {
                // set header
                if (config["headers"] != null)
                {
                    JArray headers = (JArray)config["headers"];
                    foreach (var header in headers.Children <JObject>())
                    {
                        foreach (JProperty prop in header.Properties())
                        {
                            client.DefaultRequestHeaders.Add(prop.Name, $"{prop.Value}");
                        }
                    }
                }

                // Process Credentials
                if (config["basic"] != null)
                {
                    var auth = (JObject)config["basic"];
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
                                                          Encoding.ASCII.GetBytes($"{auth["id"]}:{auth["password"]}")));
                }

                // Process content
                var body = $"{config["body"]}";

                var data = JsonConvert.DeserializeObject <IDictionary <string, object> >(WebTools.GetBody(context));
                foreach (var key in data.Keys)
                {
                    string value = $"{data[key]}";
                    // convert key -> value
                    body = body.Replace($"@{key}@", value);
                }

                // Send the request
                if ($"{config["method"]}" == "POST")
                {
                    var content = new StringContent(body);
                    if (config["contentType"] != null)
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue($"{config["contentType"]}");
                    }
                    var response = await client.PostAsync(url, content);

                    object responseContent = await response.Content.ReadAsStringAsync();

                    try
                    {
                        // convert the response content
                        if ($"{config["convert"]}" == "xml")
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml($"{responseContent}");
                            responseContent = JsonConvert.DeserializeObject(JsonConvert.SerializeXmlNode(doc));
                        }

                        // see if to include the request
                        object request = null;
                        if ($"{config["includeRequest"]}" == "True")
                        {
                            request = body;
                        }

                        result = new
                        {
                            Status   = response.StatusCode,
                            Response = responseContent,
                            Request  = request
                        };
                    } catch
                    {
                        throw new Exception($"{responseContent}");
                    }
                }
            }

            return(result);
        }
    }
}