Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
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." }
            }
            ;

            // 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" }
            }
            ;

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

            // 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));

            // set default fields
            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
            var id = $"{Insert(db, table, updatedData, idField)}";

            // Form document
            data          = JsonConvert.DeserializeObject <JObject>(WebTools.GetBody(context));
            data[idField] = $"{id}";

            // 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 { }

                        if (source != null)
                        {
                            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"]}"]}";
                                        }
                                    }
                                }

                                // navigation_id
                                if (navigation_id != null)
                                {
                                    record["navigation_id"] = navigation_id;
                                }

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

            // Return Result
            return(new { _id = id });
        }
        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" });
        }
    }
}