Esempio n. 1
0
        public async Task <IActionResult> Profile()
        {
            var days_til_password_expires = -1;

            var password_days_before_expires = Program.config_password_days_before_expires;

            if (password_days_before_expires > 0)
            {
                try
                {
                    var userName = User.Identities.First(
                        u => u.IsAuthenticated &&
                        u.HasClaim(c => c.Type == ClaimTypes.Name)).FindFirst(ClaimTypes.Name).Value;

                    //var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_date_created_user_id?startkey=[" + "{}" + $",\"{user.UserName}\"]&decending=true&limit={unsuccessful_login_attempts_number_before_lockout}";
                    var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_user_id?startkey=\"{userName}\"&endkey=\"{userName}\"";

                    var    session_event_curl   = new cURL("GET", null, session_event_request_url, null, Program.config_timer_user_name, Program.config_timer_password);
                    string response_from_server = await session_event_curl.executeAsync();

                    //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server);
                    var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.session_event> >(response_from_server);

                    DateTime first_item_date = DateTime.Now;
                    DateTime last_item_date  = DateTime.Now;

                    session_event_response.rows.Sort(new mmria.common.model.couchdb.Compare_Session_Event_By_DateCreated <mmria.common.model.couchdb.session_event>());

                    var date_of_last_password_change = DateTime.MinValue;

                    foreach (var session_event in session_event_response.rows)
                    {
                        if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed)
                        {
                            date_of_last_password_change = session_event.value.date_created;
                            break;
                        }
                    }

                    if (date_of_last_password_change != DateTime.MinValue)
                    {
                        days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - date_of_last_password_change).TotalDays;
                    }
                    else if (session_event_response.rows.Count > 0)
                    {
                        days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - session_event_response.rows[session_event_response.rows.Count - 1].value.date_created).TotalDays;
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine($"{ex}");
                }
            }

            ViewBag.days_til_password_expires           = days_til_password_expires;
            ViewBag.config_password_days_before_expires = password_days_before_expires;
            ViewBag.sams_is_enabled = _configuration["sams:is_enabled"];

            return(View());
        }
Esempio n. 2
0
        private async System.Threading.Tasks.Task <string> get_revision(string p_document_url)
        {
            string result = null;

            var    document_curl      = new cURL("GET", null, p_document_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string temp_document_json = null;

            try
            {
                temp_document_json = await document_curl.executeAsync();

                var request_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(temp_document_json);
                IDictionary <string, object> updater = request_result as IDictionary <string, object>;
                result = updater["_rev"].ToString();
            }
            catch (Exception ex)
            {
                if (!(ex.Message.IndexOf("(404) Object Not Found") > -1))
                {
                    //System.Console.WriteLine ("c_sync_document.get_revision");
                    //System.Console.WriteLine (ex);
                }
            }

            return(result);
        }
Esempio n. 3
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case Session_Event_Message sem:


                try
                {
                    var se = new mmria.common.model.couchdb.session_event();
                    se.data_type    = "session-event";
                    se._id          = sem._id;
                    se.date_created = sem.date_created;
                    se.user_id      = sem.user_id;
                    se.ip           = sem.ip;

                    switch (sem.action_result)
                    {
                    case Session_Event_Message.Session_Event_Message_Action_Enum.successful_login:
                        se.action_result = mmria.common.model.couchdb.session_event.session_event_action_enum.successful_login;
                        break;

                    case Session_Event_Message.Session_Event_Message_Action_Enum.password_changed:
                        se.action_result = mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed;
                        break;

                    case Session_Event_Message.Session_Event_Message_Action_Enum.failed_login:
                    default:
                        se.action_result = mmria.common.model.couchdb.session_event.session_event_action_enum.failed_login;
                        break;
                    }


                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    var session_event_json = Newtonsoft.Json.JsonConvert.SerializeObject(se, settings);

                    var request_url = $"{Program.config_couchdb_url}/session/{se._id}";
                    var curl        = new cURL("PUT", null, request_url, session_event_json, Program.config_timer_user_name, Program.config_timer_password);
                    curl.executeAsync().Wait();

                    //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Session_Event_Message exception: {ex}");
                }

                break;
            }
        }
Esempio n. 4
0
        private async Task <string> Post_Document_List(mmria.console.model.couchdb.cBulkDocument p_bulk_document)
        {
            string result = null;
            string bulk_document_string = Newtonsoft.Json.JsonConvert.SerializeObject(p_bulk_document);
            string URL           = string.Format("{0}/_bulk_docs", this.database_url);
            cURL   document_curl = new cURL("POST", null, URL, bulk_document_string, this.user_name, this.password);

            try
            {
                result = await document_curl.executeAsync();
            }
            catch (Exception ex)
            {
                result = ex.ToString();
            }
            return(result);
        }
Esempio n. 5
0
        private async Task <mmria.console.model.couchdb.cBulkDocument> GetDocumentList()
        {
            mmria.console.model.couchdb.cBulkDocument result = new model.couchdb.cBulkDocument();

            string URL           = string.Format("{0}/_all_docs?include_docs=true", this.database_url);
            cURL   document_curl = new cURL("GET", null, URL, null, this.user_name, this.password);
            var    curl_result   = await document_curl.executeAsync();

            dynamic all_cases      = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (curl_result);
            dynamic all_cases_rows = all_cases.rows;

            foreach (System.Dynamic.ExpandoObject case_row in all_cases_rows)
            {
                IDictionary <string, object> case_doc = ((IDictionary <string, object>)case_row) ["doc"] as IDictionary <string, object>;
                case_doc.Remove("_rev");
                result.docs.Add(case_doc);
            }

            return(result);
        }
Esempio n. 6
0
        public async System.Threading.Tasks.Task executeAsync()
        {
            string de_identified_json = new mmria.server.util.c_de_identifier(document_json).execute();

            string de_identified_revision = await get_revision(Program.config_couchdb_url + "/de_id/" + this.document_id);

            System.Text.StringBuilder de_identfied_url = new System.Text.StringBuilder();

            if (!string.IsNullOrEmpty(de_identified_revision))
            {
                //de_identfied_url = Program.config_couchdb_url + "/de_id/" + this.document_id + "?new_edits=false";

                de_identified_json = set_revision(de_identified_json, de_identified_revision);
            }

            de_identfied_url.Append(Program.config_couchdb_url);
            de_identfied_url.Append("/de_id/");
            de_identfied_url.Append(this.document_id);

            if (this.method == "DELETE")
            {
                de_identfied_url.Append("?rev=");
                de_identfied_url.Append(de_identified_revision);
            }

            var de_identfied_curl = new cURL(this.method, null, de_identfied_url.ToString(), de_identified_json, Program.config_timer_user_name, Program.config_timer_password);

            try
            {
                string de_id_result = await de_identfied_curl.executeAsync();

                System.Console.WriteLine("sync de_id");
                System.Console.WriteLine(de_id_result);
            }
            catch (Exception ex)
            {
                //System.Console.WriteLine("c_sync_document de_id");
                //System.Console.WriteLine(ex);
            }


            //string aggregate_url = Program.config_couchdb_url + "/report/" + kvp.Key + "?new_edits=false";

            try
            {
                string aggregate_json = new mmria.server.util.c_convert_to_report_object(document_json).execute();

                string aggregate_revision = await get_revision(Program.config_couchdb_url + "/report/" + this.document_id);

                System.Text.StringBuilder aggregate_url = new System.Text.StringBuilder();

                if (!string.IsNullOrEmpty(aggregate_revision))
                {
                    //aggregate_url = Program.config_couchdb_url + "/report/" + this.document_id + "?new_edits=false";
                    aggregate_json = set_revision(aggregate_json, aggregate_revision);
                }


                aggregate_url.Append(Program.config_couchdb_url);
                aggregate_url.Append("/report/");
                aggregate_url.Append(this.document_id);

                if (this.method == "DELETE")
                {
                    aggregate_url.Append("?rev=");
                    aggregate_url.Append(aggregate_revision);
                }

                var aggregate_curl = new cURL(this.method, null, aggregate_url.ToString(), aggregate_json, Program.config_timer_user_name, Program.config_timer_password);

                string aggregate_result = await aggregate_curl.executeAsync();

                System.Console.WriteLine("c_sync_document aggregate_id");
                System.Console.WriteLine(aggregate_result);
            }
            catch (Exception ex)
            {
                //System.Console.WriteLine("sync aggregate_id");
                //System.Console.WriteLine(ex);
            }
        }
Esempio n. 7
0
        public async Task Setup()
        {
            string current_directory = AppContext.BaseDirectory;

            if (!System.IO.Directory.Exists(System.IO.Path.Combine(current_directory, "database-scripts")))
            {
                current_directory = System.IO.Directory.GetCurrentDirectory();
            }

            bool is_able_to_connect = false;

            try
            {
                if (await url_endpoint_exists(Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, "GET"))
                {
                    is_able_to_connect = true;
                }
            }
            catch (Exception ex)
            {
            }

            if (!is_able_to_connect)
            {
                Log.Information("Starup pausing for 1 minute to give database a chance to start");
                int milliseconds_in_second = 1000;
                int number_of_seconds      = 60;
                int total_milliseconds     = number_of_seconds * milliseconds_in_second;

                System.Threading.Thread.Sleep(total_milliseconds);/**/
            }

            Log.Information("Starup/Install Check - start");
            if
            (
                await url_endpoint_exists(Program.config_couchdb_url, null, null, "GET") &&
                !Program.config_timer_user_name.Equals("couchdb_admin_user_name", StringComparison.OrdinalIgnoreCase) &&
                !Program.config_timer_password.Equals("couchdb_admin_password", StringComparison.OrdinalIgnoreCase) &&
                !await url_endpoint_exists(Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, "GET")
            )
            {
                try
                {
                    await new cURL("PUT", null, Program.config_couchdb_url + $"/_node/nonode@nohost/_config/admins/{Program.config_timer_user_name}", $"\"{Program.config_timer_password}\"", null, null).executeAsync();

                    //await new cURL ("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/mmria_section/app_version", $"\"{Program.config_app_version}\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/couch_httpd_auth/allow_persistent_cookies", $"\"true\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/chttpd/bind_address", $"\"0.0.0.0\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/chttpd/port", $"\"5984\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/httpd/enable_cors", $"\"true\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/origins", $"\"*\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/credentials", $"\"true\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/headers", $"\"accept, authorization, content-type, origin, referer, cache-control, x-requested-with\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/methods", $"\"GET, PUT, POST, HEAD, DELETE\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_users", null, Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    await new cURL("PUT", null, Program.config_couchdb_url + "/_replicator", null, Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    await new cURL("PUT", null, Program.config_couchdb_url + "/_global_changes", null, Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                }
                catch (Exception ex)
                {
                    Log.Information($"Failed configuration \n{ex}");
                }
            }
            Log.Information("Starup/Install Check - end");


            if (

                await url_endpoint_exists(Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, "GET")  //&&
                //Verify_Password (Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password)
                )
            {
                Log.Information("DB Repair Check - start");

                await c_db_setup.UpdateMetadata(current_directory);

                await c_db_setup.UpdateJurisdiction(current_directory);

                if (!await url_endpoint_exists(Program.config_couchdb_url + "/mmrds", Program.config_timer_user_name, Program.config_timer_password))
                {
                    var mmrds_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds", null, Program.config_timer_user_name, Program.config_timer_password);
                    Log.Information("mmrds_curl\n{0}", await mmrds_curl.executeAsync());

                    await new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_security", "{\"admins\":{\"names\":[],\"roles\":[\"form_designer\"]},\"members\":{\"names\":[],\"roles\":[\"abstractor\",\"data_analyst\",\"timer\"]}}", Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    Log.Information("mmrds/_security completed successfully");


                    try
                    {
                        string case_design_sortable      = System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/case_design_sortable.json")).ReadToEnd();
                        var    case_design_sortable_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_design/sortable", case_design_sortable, Program.config_timer_user_name, Program.config_timer_password);
                        await case_design_sortable_curl.executeAsync();

                        //await EnsureUpdate(case_design_sortable, Program.config_couchdb_url + "/mmrds/_design/sortable");

                        string case_store_design_auth = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/case_store_design_auth.json")).ReadToEndAsync();

                        var case_store_design_auth_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_design/auth", case_store_design_auth, Program.config_timer_user_name, Program.config_timer_password);
                        await case_store_design_auth_curl.executeAsync();

                        //await EnsureUpdate(case_store_design_auth, Program.config_couchdb_url + "/mmrds/_design/auth");
                    }
                    catch (Exception ex)
                    {
                        Log.Information($"unable to configure mmrds database:\n{ex}");
                    }
                }



                if (!await url_endpoint_exists(Program.config_couchdb_url + "/session", Program.config_timer_user_name, Program.config_timer_password))
                {
                    var session_curl = new cURL("PUT", null, Program.config_couchdb_url + "/session", null, Program.config_timer_user_name, Program.config_timer_password);
                    Log.Information("session_curl\n{0}", await session_curl.executeAsync());

                    await new cURL("PUT", null, Program.config_couchdb_url + "/session/_security", "{\"admins\":{\"names\":[],\"roles\":[\"_admin\"]},\"members\":{\"names\":[],\"roles\":[\"_admin\"]}}", Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    Log.Information("session/_security completed successfully");


                    try
                    {
                        /*
                         * string session_design_profile_sortable = System.IO.File.OpenText (System.IO.Path.Combine (current_directory, "database-scripts/session_design_profile_sortable.json")).ReadToEnd ();
                         * var session_design_profile_sortable_curl = new cURL ("PUT", null, Program.config_couchdb_url + "/session/_design/profile_sortable", session_design_profile_sortable, Program.config_timer_user_name, Program.config_timer_password);
                         * await session_design_profile_sortable_curl.executeAsync ();
                         */
                        //await EnsureUpdate(case_design_sortable, Program.config_couchdb_url + "/mmrds/_design/sortable");

                        string session_design_session_event_sortable = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/session_design_session_event_sortable.json")).ReadToEndAsync();

                        var session_design_session_event_sortable_curl = new cURL("PUT", null, Program.config_couchdb_url + "/session/_design/session_event_sortable", session_design_session_event_sortable, Program.config_timer_user_name, Program.config_timer_password);
                        await session_design_session_event_sortable_curl.executeAsync();


                        string session_design_session_sortable = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/session_design_session_sortable.json")).ReadToEndAsync();

                        var session_design_session_sortable_curl = new cURL("PUT", null, Program.config_couchdb_url + "/session/_design/session_sortable", session_design_session_sortable, Program.config_timer_user_name, Program.config_timer_password);
                        await session_design_session_sortable_curl.executeAsync();

                        //await EnsureUpdate(case_store_design_auth, Program.config_couchdb_url + "/mmrds/_design/auth");
                    }
        protected override void OnReceive(object message)
        {
            Console.WriteLine($"Process_DB_Synchronization_Set {System.DateTime.Now}");

            switch (message)
            {
            case ScheduleInfoMessage scheduleInfo:
                //System.Console.WriteLine ("{0} Beginning Change Synchronization.", System.DateTime.Now);
                //log.DebugFormat("iCIMS_Data_Call_Job says: Starting {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
                mmria.server.model.couchdb.c_change_result latest_change_set = get_changes(Program.Last_Change_Sequence, scheduleInfo);

                Dictionary <string, KeyValuePair <string, bool> > response_results = new Dictionary <string, KeyValuePair <string, bool> > (StringComparer.OrdinalIgnoreCase);

                if (Program.Last_Change_Sequence != latest_change_set.last_seq)
                {
                    foreach (mmria.server.model.couchdb.c_seq seq in latest_change_set.results)
                    {
                        if (response_results.ContainsKey(seq.id))
                        {
                            if (
                                seq.changes.Count > 0 &&
                                response_results [seq.id].Key != seq.changes [0].rev)
                            {
                                if (seq.deleted == null)
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, false);
                                }
                                else
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, true);
                                }
                            }
                        }
                        else
                        {
                            if (seq.deleted == null)
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, false));
                            }
                            else
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, true));
                            }
                        }
                    }
                }


                if (Program.Change_Sequence_Call_Count < int.MaxValue)
                {
                    Program.Change_Sequence_Call_Count++;
                }

                if (Program.DateOfLastChange_Sequence_Call.Count > 9)
                {
                    Program.DateOfLastChange_Sequence_Call.Clear();
                }

                Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now);

                Program.Last_Change_Sequence = latest_change_set.last_seq;

                //List<System.Threading.Tasks.Task> TaskList = new List<System.Threading.Tasks.Task> ();

                foreach (KeyValuePair <string, KeyValuePair <string, bool> > kvp in response_results)
                {
                    System.Threading.Tasks.Task.Run
                    (
                        new Action(async() =>
                    {
                        if (kvp.Value.Value)
                        {
                            try
                            {
                                mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, null, "DELETE");
                                await sync_document.executeAsync();
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync Delete case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                        else
                        {
                            string document_url  = Program.config_couchdb_url + "/mmrds/" + kvp.Key;
                            var document_curl    = new cURL("GET", null, document_url, null, Program.config_timer_user_name, Program.config_timer_password);
                            string document_json = null;

                            try
                            {
                                document_json = await document_curl.executeAsync();
                                if (!string.IsNullOrEmpty(document_json) && document_json.IndexOf("\"_id\":\"_design/") < 0)
                                {
                                    mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, document_json);
                                    await sync_document.executeAsync();
                                }
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync PUT case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                    })
                    );
                }
                //System.Threading.Tasks.Task.WhenAll (TaskList);

                try
                {
                    HashSet <string> mmrds_id_set   = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> de_id_set      = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> report_id_set  = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> deleted_id_set = null;

                    string json = null;
                    mmria.server.model.couchdb.c_all_docs all_docs = null;
                    cURL curl = null;

                    // get all non deleted cases in mmrds
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/mmrds/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        mmrds_id_set.Add(all_doc_row.id);
                    }


                    // get all non deleted cases in de_id
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/de_id/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        de_id_set.Add(all_doc_row.id);
                    }

                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(de_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/de_id/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }

                    // get all non deleted cases in report
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/report/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        report_id_set.Add(all_doc_row.id);
                    }
                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(report_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/report/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Delete sync error:\n{0}", ex);
                }

                //System.Console.WriteLine ("{0}- Ending Change Synchronization.", System.DateTime.Now);
                break;
            }
        }
Esempio n. 9
0
        public virtual Task Execute(IJobExecutionContext context)
        {
            //Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger();
            //log.Debug("IJob.Execute");

            JobKey jobKey = context.JobDetail.Key;


            //if (!Program.is_processing_export_queue)
            {
                System.Threading.Tasks.Task.Run
                (
                    new Action(() =>
                {
                    //System.Console.WriteLine ("{0} Beginning Export Queue Item Processing", System.DateTime.Now);
                    try
                    {
                        Process_Export_Queue_Item();
                    }
                    catch (Exception ex)
                    {
                        // to nothing for now
                        System.Console.WriteLine("{0} check_for_changes_job.Process_Export_Queue_Item: error\n{1}", System.DateTime.Now, ex);
                    }

                    try
                    {
                        Process_Export_Queue_Delete();
                    }
                    catch (Exception ex)
                    {
                        // to nothing for now
                        System.Console.WriteLine("{0} check_for_changes_job.Process_Export_Queue_Delete: error\n{1}", System.DateTime.Now, ex);
                    }

                    //System.Console.WriteLine ("{0} Ending Export Queue Item Processing", System.DateTime.Now);
                })
                );
            }


            //if (!Program.is_processing_syncronization)
            {
                //System.Console.WriteLine ("{0} Beginning Change Synchronization.", System.DateTime.Now);
                //log.DebugFormat("iCIMS_Data_Call_Job says: Starting {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
                mmria.server.model.couchdb.c_change_result latest_change_set = get_changes(Program.Last_Change_Sequence);

                Dictionary <string, KeyValuePair <string, bool> > response_results = new Dictionary <string, KeyValuePair <string, bool> > (StringComparer.OrdinalIgnoreCase);

                if (Program.Last_Change_Sequence != latest_change_set.last_seq)
                {
                    foreach (mmria.server.model.couchdb.c_seq seq in latest_change_set.results)
                    {
                        if (response_results.ContainsKey(seq.id))
                        {
                            if (
                                seq.changes.Count > 0 &&
                                response_results [seq.id].Key != seq.changes [0].rev)
                            {
                                if (seq.deleted == null)
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, false);
                                }
                                else
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, true);
                                }
                            }
                        }
                        else
                        {
                            if (seq.deleted == null)
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, false));
                            }
                            else
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, true));
                            }
                        }
                    }
                }


                if (Program.Change_Sequence_Call_Count < int.MaxValue)
                {
                    Program.Change_Sequence_Call_Count++;
                }

                if (Program.DateOfLastChange_Sequence_Call.Count > 9)
                {
                    Program.DateOfLastChange_Sequence_Call.Clear();
                }

                Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now);

                Program.Last_Change_Sequence = latest_change_set.last_seq;

                //List<System.Threading.Tasks.Task> TaskList = new List<System.Threading.Tasks.Task> ();

                foreach (KeyValuePair <string, KeyValuePair <string, bool> > kvp in response_results)
                {
                    System.Threading.Tasks.Task.Run
                    (
                        new Action(async() =>
                    {
                        if (kvp.Value.Value)
                        {
                            try
                            {
                                mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, null, "DELETE");
                                await sync_document.executeAsync();
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync Delete case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                        else
                        {
                            string document_url  = Program.config_couchdb_url + "/mmrds/" + kvp.Key;
                            var document_curl    = new cURL("GET", null, document_url, null, Program.config_timer_user_name, Program.config_timer_password);
                            string document_json = null;

                            try
                            {
                                document_json = await document_curl.executeAsync();
                                if (!string.IsNullOrEmpty(document_json) && document_json.IndexOf("\"_id\":\"_design/") < 0)
                                {
                                    mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, document_json);
                                    await sync_document.executeAsync();
                                }
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync PUT case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                    })
                    );
                }
                //System.Threading.Tasks.Task.WhenAll (TaskList);

                try
                {
                    HashSet <string> mmrds_id_set   = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> de_id_set      = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> report_id_set  = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> deleted_id_set = null;

                    string json = null;
                    mmria.server.model.couchdb.c_all_docs all_docs = null;
                    cURL curl = null;

                    // get all non deleted cases in mmrds
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/mmrds/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        mmrds_id_set.Add(all_doc_row.id);
                    }


                    // get all non deleted cases in de_id
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/de_id/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        de_id_set.Add(all_doc_row.id);
                    }

                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(de_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/de_id/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }

                    // get all non deleted cases in report
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/report/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        report_id_set.Add(all_doc_row.id);
                    }
                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(report_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/report/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Delete sync error:\n{0}", ex);
                }

                //System.Console.WriteLine ("{0}- Ending Change Synchronization.", System.DateTime.Now);
            }

            return(Task.CompletedTask);
        }
Esempio n. 10
0
        public async Task Process_Export_Queue_Delete()
        {
            //System.Console.WriteLine ("{0} check_for_changes_job.Process_Export_Queue_Delete: started", System.DateTime.Now);

            try
            {
                List <export_queue_item> result = new List <export_queue_item> ();

                var get_curl = new cURL("GET", null, Program.config_couchdb_url + "/export_queue/_all_docs?include_docs=true", null, this.user_name, this.password);

                string responseFromServer = await get_curl.executeAsync();

                IDictionary <string, object> response_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (responseFromServer) as IDictionary <string, object>;
                IList <object> enumerable_rows = response_result ["rows"] as IList <object>;

                foreach (IDictionary <string, object> enumerable_item in enumerable_rows)
                {
                    IDictionary <string, object> doc_item = enumerable_item ["doc"] as IDictionary <string, object>;

                    if (
                        doc_item ["status"] != null &&
                        doc_item ["status"].ToString().StartsWith("Deleted", StringComparison.OrdinalIgnoreCase))
                    {
                        export_queue_item item = new export_queue_item();

                        item._id               = doc_item ["_id"].ToString();
                        item._rev              = doc_item ["_rev"].ToString();
                        item._deleted          = doc_item.ContainsKey("_deleted") ? doc_item["_deleted"] as bool?: null;
                        item.date_created      = doc_item ["date_created"] as DateTime?;
                        item.created_by        = doc_item.ContainsKey("created_by") && doc_item ["created_by"] != null ? doc_item ["created_by"].ToString() : null;
                        item.date_last_updated = doc_item ["date_last_updated"] as DateTime?;
                        item.last_updated_by   = doc_item.ContainsKey("last_updated_by") && doc_item["last_updated_by"] != null ? doc_item ["last_updated_by"].ToString() : null;
                        item.file_name         = doc_item ["file_name"] != null ? doc_item ["file_name"].ToString() : null;
                        item.export_type       = doc_item ["export_type"] != null ? doc_item ["export_type"].ToString() : null;
                        item.status            = doc_item ["status"] != null ? doc_item ["status"].ToString() : null;

                        result.Add(item);
                    }
                }


                if (result.Count > 0)
                {
                    if (result.Count > 1)
                    {
                        var comparer = Comparer <export_queue_item> .Create
                                       (
                            (x, y) => x.date_created.Value.CompareTo(y.date_created.Value)
                                       );

                        result.Sort(comparer);
                    }

                    export_queue_item item_to_process = result [0];

                    try
                    {
                        string item_directory_name = item_to_process.file_name.Substring(0, item_to_process.file_name.LastIndexOf("."));
                        string export_directory    = System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings ["export_directory"], item_directory_name);

                        try
                        {
                            if (System.IO.Directory.Exists(export_directory))
                            {
                                System.IO.Directory.Delete(export_directory, true);
                            }
                        }
                        catch (Exception Ex)
                        {
                            // do nothing for now
                            System.Console.WriteLine("check_for_changes_job.Process_Export_Queue_Delete: Unable to Delete Directory {0}", export_directory);
                        }

                        string file_path = System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings ["export_directory"], item_to_process.file_name);
                        try
                        {
                            if (System.IO.File.Exists(file_path))
                            {
                                System.IO.File.Delete(file_path);
                            }
                        }
                        catch (Exception Ex)
                        {
                            // do nothing for now
                            System.Console.WriteLine("Program.Process_Export_Queue_Delete: Unable to Delete File {0}", file_path);
                        }

                        item_to_process.status          = "expunged";
                        item_to_process.last_updated_by = "mmria-server";
                        Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                        settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                        string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                        var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                        responseFromServer = await get_curl.executeAsync();
                    }
                    catch (Exception ex)
                    {
                        // do nothing for now
                    }
                }
            }
            catch (Exception method_exception)
            {
                System.Console.Write($"{System.DateTime.Now} Process_Export_Queue_Delete error\n{method_exception}");
            }
        }
Esempio n. 11
0
        public async Task Process_Export_Queue_Item()
        {
            //System.Console.WriteLine ("{0} check_for_changes_job.Process_Export_Queue_Item: started", System.DateTime.Now);
            try
            {
                List <export_queue_item> result = new List <export_queue_item> ();

                var get_curl = new cURL("GET", null, Program.config_couchdb_url + "/export_queue/_all_docs?include_docs=true", null, this.user_name, this.password);

                string responseFromServer = await get_curl.executeAsync();

                IDictionary <string, object> response_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (responseFromServer) as IDictionary <string, object>;
                IList <object> enumerable_rows = response_result ["rows"] as IList <object>;

                foreach (IDictionary <string, object> enumerable_item in enumerable_rows)
                {
                    IDictionary <string, object> doc_item = enumerable_item ["doc"] as IDictionary <string, object>;

                    if (
                        doc_item ["status"] != null &&
                        doc_item ["status"].ToString().StartsWith("In Queue...", StringComparison.OrdinalIgnoreCase))
                    {
                        export_queue_item item = new export_queue_item();

                        item._id               = doc_item ["_id"].ToString();
                        item._rev              = doc_item ["_rev"].ToString();
                        item._deleted          = doc_item.ContainsKey("_deleted") ? doc_item["_deleted"] as bool?: null;
                        item.date_created      = doc_item ["date_created"] as DateTime?;
                        item.created_by        = doc_item.ContainsKey("created_by") && doc_item ["created_by"] != null ? doc_item ["created_by"].ToString() : null;
                        item.date_last_updated = doc_item ["date_last_updated"] as DateTime?;
                        item.last_updated_by   = doc_item.ContainsKey("last_updated_by") && doc_item ["last_updated_by"] != null ? doc_item ["last_updated_by"].ToString() : null;
                        item.file_name         = doc_item ["file_name"] != null ? doc_item ["file_name"].ToString() : null;
                        item.export_type       = doc_item ["export_type"] != null ? doc_item ["export_type"].ToString() : null;
                        item.status            = doc_item ["status"] != null ? doc_item ["status"].ToString() : null;

                        result.Add(item);
                    }
                }


                if (result.Count > 0)
                {
                    if (result.Count > 1)
                    {
                        var comparer = Comparer <export_queue_item> .Create
                                       (
                            (x, y) => x.date_created.Value.CompareTo(y.date_created.Value)
                                       );

                        result.Sort(comparer);
                    }

                    export_queue_item item_to_process = result [0];

                    item_to_process.date_last_updated = new DateTime?();
                    //item_to_process.last_updated_by = $mmria.getCookie("uid");


                    List <string> args = new List <string>();
                    args.Add("exporter:exporter");
                    args.Add("user_name:" + this.user_name);
                    args.Add("password:"******"database_url:" + this.couch_db_url);
                    args.Add("item_file_name:" + item_to_process.file_name);
                    args.Add("item_id:" + item_to_process._id);


                    if (item_to_process.export_type.StartsWith("core csv", StringComparison.OrdinalIgnoreCase))
                    {
                        item_to_process.status            = "Creating Export...";
                        item_to_process.last_updated_by   = "mmria-server";
                        item_to_process.date_last_updated = DateTime.Now;

                        Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                        settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                        string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                        var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                        responseFromServer = await set_curl.executeAsync();

                        try
                        {
                            mmria.server.util.core_element_exporter core_element_exporter = new mmria.server.util.core_element_exporter();
                            core_element_exporter.Execute(args.ToArray());
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex);
                        }
                    }
                    else if (item_to_process.export_type.StartsWith("all csv", StringComparison.OrdinalIgnoreCase))
                    {
                        item_to_process.status            = "Creating Export...";
                        item_to_process.last_updated_by   = "mmria-server";
                        item_to_process.date_last_updated = DateTime.Now;

                        Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                        settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                        string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                        var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                        responseFromServer = await set_curl.executeAsync();


                        try
                        {
                            mmria.server.util.mmrds_exporter mmrds_exporter = new mmria.server.util.mmrds_exporter();
                            mmrds_exporter.Execute(args.ToArray());
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex);
                        }
                    }
                    else if (item_to_process.export_type.StartsWith("cdc csv", StringComparison.OrdinalIgnoreCase))
                    {
                        item_to_process.status            = "Creating Export...";
                        item_to_process.last_updated_by   = "mmria-server";
                        item_to_process.date_last_updated = DateTime.Now;

                        Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                        settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                        string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                        var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                        responseFromServer = await set_curl.executeAsync();

                        args.Add("is_cdc_de_identified:true");

                        try
                        {
                            mmria.server.util.mmrds_exporter mmrds_exporter = new mmria.server.util.mmrds_exporter();
                            mmrds_exporter.Execute(args.ToArray());
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex);
                        }
                    }
                }
            }
            catch (Exception method_exception)
            {
                System.Console.Write($"{System.DateTime.Now} Process_Export_Queue_Item error\n{method_exception}");
            }
        }
Esempio n. 12
0
        public async Task <mmria.server.model.couchdb.c_change_result> get_changes(string p_last_sequence)
        {
            mmria.server.model.couchdb.c_change_result result = new mmria.server.model.couchdb.c_change_result();
            string url = null;

            try
            {
                if (string.IsNullOrWhiteSpace(p_last_sequence))
                {
                    url = Program.config_couchdb_url + "/mmrds/_changes";
                }
                else
                {
                    url = Program.config_couchdb_url + "/mmrds/_changes?since=" + p_last_sequence;
                }
                var    curl = new cURL("GET", null, url, null, this.user_name, this.password);
                string res  = await curl.executeAsync();

                result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_change_result>(res);
                //System.Console.WriteLine("get_job_info.last_seq");
                //System.Console.WriteLine(result.last_seq);


                /*
                 * curl -X GET $HOST/db/_changes
                 * curl -X GET $HOST/db/_changes?since=1
                 *
                 *      http://db1.mmria.org/mmrds/_changes?since=3235-g1AAAAIseJyV0UEKwjAQBdDRKorgGSqeIEntNK7sTTSxhVJqIuheb1L3HkJPIN5Ab1LTpCtFaDcTGIZH-L8AgHHmJTBVWukkjZXO9OFYmHVfgPSrqsozTwJ4_s7sRilyzgj5vv8jyJmZcuUQ8bACCZdbTMO2QlwL60bYWwEjwmUg2gqbWjg1wtMKQiAiW7QU1MBMOJvHIKWLYzhxcRAZIOWdoIuDbvV3rlaRgiaUR52Uu1NetVJahTOT6hY7KW-nNB335q6hCDllPw3lHw3Uqkc
                 *
                 * {
                 *      "seq":12, // update_seq created when document changed
                 *      "id":"foo", // document id
                 *      "changes":  /// one or more changes
                 *              [
                 *                      {"rev":"1-23202479633c2b380f79507a776743d5"}
                 *              ]
                 * }
                 *
                 * string get_job_search_result_json = Get_Job_Set();
                 *
                 * DGJobAPI.Models.GetJobSearchResult get_job_search_result = Newtonsoft.Json.JsonConvert.DeserializeObject<DGJobAPI.Models.GetJobSearchResult>(get_job_search_result_json);
                 *
                 * // remove duplicates
                 * IEnumerable<DGJobAPI.Models.JsonSummary> de_deplicated_list = get_job_search_result.searchResults
                 * .GroupBy(summary => summary.id)
                 * .Select(group => group.First());
                 *
                 *
                 * foreach (DGJobAPI.Models.JsonSummary json_summary in de_deplicated_list)
                 * {
                 *
                 * string get_job_detail_result_json = Get_Job(json_summary.id.ToString());
                 * DGJobAPI.Models.GetJobDetailResult get_job_detail_result = Newtonsoft.Json.JsonConvert.DeserializeObject<DGJobAPI.Models.GetJobDetailResult>(get_job_detail_result_json);
                 * result.Add(new DGJobAPI.Models.JobInfo(json_summary.id.ToString(), get_job_detail_result));
                 * }
                 *
                 * return result.OrderByDescending(j => j.date_last_updated).Take(100).ToList();
                 */
            }
            catch (Exception method_exception)
            {
                System.Console.Write($"{System.DateTime.Now} check_for_changes_job.get_changes error\n{method_exception}");
            }
            return(result);
        }
Esempio n. 13
0
        public async Task <IActionResult> Login(ApplicationUser user, string returnUrl = null)
        {
            var use_sams = false;

            if (!string.IsNullOrWhiteSpace(_configuration["sams:is_enabled"]))
            {
                bool.TryParse(_configuration["sams:is_enabled"], out use_sams);
            }

            if (use_sams)
            {
                return(RedirectToAction("SignIn"));
            }

            const string badUserNameOrPasswordMessage = "Username or password is incorrect.";

            if (
                user == null ||
                string.IsNullOrWhiteSpace(user.UserName) ||
                string.IsNullOrWhiteSpace(user.Password)
                )
            {
                return(BadRequest(badUserNameOrPasswordMessage));
            }



            try
            {
                var unsuccessful_login_attempts_number_before_lockout     = Program.config_unsuccessful_login_attempts_number_before_lockout;
                var unsuccessful_login_attempts_within_number_of_minutes  = Program.config_unsuccessful_login_attempts_within_number_of_minutes;
                var unsuccessful_login_attempts_lockout_number_of_minutes = Program.config_unsuccessful_login_attempts_lockout_number_of_minutes;
                var password_days_before_expires = Program.config_password_days_before_expires;


                var is_locked_out      = false;
                var failed_login_count = 0;


                DateTime grace_period_date = DateTime.Now;

                try
                {
                    //var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_date_created_user_id?startkey=[" + "{}" + $",\"{user.UserName}\"]&decending=true&limit={unsuccessful_login_attempts_number_before_lockout}";
                    var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_user_id?startkey=\"{user.UserName}\"&endkey=\"{user.UserName}\"";

                    var    session_event_curl   = new cURL("GET", null, session_event_request_url, null, Program.config_timer_user_name, Program.config_timer_password);
                    string response_from_server = await session_event_curl.executeAsync();

                    //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server);
                    var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.session_event> >(response_from_server);

                    DateTime first_item_date = DateTime.Now;
                    DateTime last_item_date  = DateTime.Now;


                    var MaxRange = DateTime.Now.AddMinutes(-unsuccessful_login_attempts_within_number_of_minutes);
                    session_event_response.rows.Sort(new mmria.common.model.couchdb.Compare_Session_Event_By_DateCreated <mmria.common.model.couchdb.session_event>());

/*
 *                  if(password_days_before_expires > 0)
 *                  {
 *                      var date_of_last_password_change = DateTime.MinValue;
 *
 *                      foreach(var session_event in session_event_response.rows)
 *                      {
 *                          if(session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed)
 *                          {
 *                              date_of_last_password_change = session_event.value.date_created;
 *                              break;
 *                          }
 *                      }
 *
 *                      if(date_of_last_password_change != DateTime.MinValue)
 *                      {
 *                          days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - date_of_last_password_change).TotalDays;
 *                      }
 *                  }
 */

                    foreach (var session_event in session_event_response.rows.Where(row => row.value.date_created >= MaxRange))
                    {
                        if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.failed_login)
                        {
                            failed_login_count++;
                            if (failed_login_count == 1)
                            {
                                first_item_date = session_event.value.date_created;
                            }

                            if (failed_login_count >= unsuccessful_login_attempts_number_before_lockout)
                            {
                                last_item_date    = session_event.value.date_created;
                                grace_period_date = first_item_date.AddMinutes(unsuccessful_login_attempts_lockout_number_of_minutes);
                                if (DateTime.Now < grace_period_date)
                                {
                                    is_locked_out = true;
                                    break;
                                }
                            }
                        }
                        else if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.successful_login)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine($"{ex}");
                }


                if (is_locked_out)
                {
                    return(RedirectToAction("Locked", new { user_name = user.UserName, grace_period_date = grace_period_date }));
                    //return View("~/Views/Account/Locked.cshtml");
                }


                string post_data       = string.Format("name={0}&password={1}", user.UserName, user.Password);
                byte[] post_byte_array = System.Text.Encoding.ASCII.GetBytes(post_data);

                string request_string         = Program.config_couchdb_url + "/_session";
                System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));
                //request.UseDefaultCredentials = true;

                request.PreAuthenticate = false;
                //request.Credentials = new System.Net.NetworkCredential("mmrds", "mmrds");
                request.Method        = "POST";
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = post_byte_array.Length;

                using (System.IO.Stream stream = request.GetRequestStream())
                {
                    stream.Write(post_byte_array, 0, post_byte_array.Length);
                }

                System.Net.WebResponse response   = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream       dataStream = response.GetResponseStream();
                System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                string responseFromServer         = await reader.ReadToEndAsync();

                mmria.common.model.couchdb.login_response json_result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.login_response>(responseFromServer);

                mmria.common.model.couchdb.login_response[] result = new mmria.common.model.couchdb.login_response[]
                {
                    json_result
                };


                this.Response.Headers.Add("Set-Cookie", response.Headers["Set-Cookie"]);

                string[] set_cookie = response.Headers["Set-Cookie"].Split(';');
                string[] auth_array = set_cookie[0].Split('=');
                if (auth_array.Length > 1)
                {
                    string auth_session_token = auth_array[1];
                    result[0].auth_session = auth_session_token;
                }
                else
                {
                    result[0].auth_session = "";
                }


                if (json_result.ok && !string.IsNullOrWhiteSpace(json_result.name))
                {
                    const string Issuer = "https://contoso.com";
                    var          claims = new List <Claim>();
                    claims.Add(new Claim(ClaimTypes.Name, json_result.name, ClaimValueTypes.String, Issuer));


                    foreach (var role in json_result.roles)
                    {
                        if (role == "_admin")
                        {
                            claims.Add(new Claim(ClaimTypes.Role, "installation_admin", ClaimValueTypes.String, Issuer));
                        }
                    }


                    foreach (var role in mmria.server.util.authorization.get_current_user_role_jurisdiction_set_for(json_result.name).Select(jr => jr.role_name).Distinct())
                    {
                        claims.Add(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, Issuer));
                    }


                    //Response.Cookies.Append("uid", json_result.name);
                    //Response.Cookies.Append("roles", string.Join(",",json_result.roles));

                    //claims.Add(new Claim("EmployeeId", string.Empty, ClaimValueTypes.String, Issuer));
                    //claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));
                    //claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
                    //var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    var session_idle_timeout_minutes = 30;

                    if (_configuration["mmria_settings:session_idle_timeout_minutes"] != null)
                    {
                        int.TryParse(_configuration["mmria_settings:session_idle_timeout_minutes"], out session_idle_timeout_minutes);
                    }

                    var userIdentity = new ClaimsIdentity("SuperSecureLogin");
                    userIdentity.AddClaims(claims);
                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        userPrincipal,
                        new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(session_idle_timeout_minutes),
                        IsPersistent = false,
                        AllowRefresh = false,
                    });
                }

                var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message
                                            (
                    DateTime.Now,
                    user.UserName,
                    this.GetRequestIP(),
                    json_result.ok && json_result.name != null? mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.successful_login: mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.failed_login
                                            );

                _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message);

                //this.ActionContext.Response.Headers.Add("Set-Cookie", auth_session_token);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message
                                            (
                    DateTime.Now,
                    user.UserName,
                    this.GetRequestIP(),
                    mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.failed_login
                                            );

                _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message);
            }

/*
 *          var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
 *          identity.AddClaim(new Claim(ClaimTypes.Name, lookupUser.UserName));
 *
 *          await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
 */
            if (returnUrl == null)
            {
                returnUrl = TempData["returnUrl"]?.ToString();
            }

            if (returnUrl != null)
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToAction(nameof(HomeController.Index), "Home"));
        }
Esempio n. 14
0
        public async Task executeAsync()
        {
            try
            {
                var delete_de_id_curl = new cURL("DELETE", null, this.couchdb_url + "/de_id", null, this.user_name, this.password);
                await delete_de_id_curl.executeAsync();
            }
            catch (Exception ex)
            {
            }


            try
            {
                var delete_report_curl = new cURL("DELETE", null, this.couchdb_url + "/report", null, this.user_name, this.password);
                await delete_report_curl.executeAsync();
            }
            catch (Exception ex)
            {
            }



            try
            {
                var create_de_id_curl = new cURL("PUT", null, this.couchdb_url + "/de_id", null, this.user_name, this.password);
                await create_de_id_curl.executeAsync();
            }
            catch (Exception ex)
            {
            }

            try
            {
                string current_directory = AppContext.BaseDirectory;
                if (!System.IO.Directory.Exists(System.IO.Path.Combine(current_directory, "database-scripts")))
                {
                    current_directory = System.IO.Directory.GetCurrentDirectory();
                }

                string result = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/case_design_sortable.json")).ReadToEndAsync();

                var create_de_id_curl = new cURL("PUT", null, this.couchdb_url + "/de_id/_design/sortable", result, this.user_name, this.password);
                await create_de_id_curl.executeAsync();
            }
            catch (Exception ex)
            {
            }



            try
            {
                var create_report_curl = new cURL("PUT", null, this.couchdb_url + "/report", null, this.user_name, this.password);
                await create_report_curl.executeAsync();
            }
            catch (Exception ex)
            {
            }



            cURL de_identified_list_curl = new cURL("GET", null, this.couchdb_url + "/metadata/de-identified-list", null, this.user_name, this.password);

            System.Dynamic.ExpandoObject de_identified_ExpandoObject = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(await de_identified_list_curl.executeAsync());
            HashSet <string>             de_identified_set           = new HashSet <string>();

            foreach (string path in (IList <object>)(((IDictionary <string, object>)de_identified_ExpandoObject) ["paths"]))
            {
                de_identified_set.Add(path);
            }
            mmria.server.util.c_de_identifier.De_Identified_Set = de_identified_set;

            var    curl = new cURL("GET", null, this.couchdb_url + "/mmrds/_all_docs?include_docs=true", null, this.user_name, this.password);
            string res  = await curl.executeAsync();

/*
 * {
 * "total_rows": 3, "offset": 0, "rows": [
 *  {"id": "doc1", "key": "doc1", "value": {"rev": "4324BB"}},
 *  {"id": "doc2", "key": "doc2", "value": {"rev":"2441HF"}},
 *  {"id": "doc3", "key": "doc3", "value": {"rev":"74EC24"}}
 * ]
 * }
 */
            System.Dynamic.ExpandoObject all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (res);
            try
            {
                IDictionary <string, object> all_docs_dictionary = all_docs as IDictionary <string, object>;
                List <object> row_list = all_docs_dictionary ["rows"] as List <object>;
                foreach (object row_item in row_list)
                {
                    try
                    {
                        IDictionary <string, object> row_dictionary = row_item as IDictionary <string, object>;
                        IDictionary <string, object> doc_dictionary = row_dictionary ["doc"] as IDictionary <string, object>;
                        string document_id = doc_dictionary ["_id"].ToString();
                        if (document_id.IndexOf("_design/") < 0)
                        {
                            string document_json = Newtonsoft.Json.JsonConvert.SerializeObject(doc_dictionary);
                            mmria.server.util.c_sync_document sync_document = new c_sync_document(document_id, document_json);
                            await sync_document.executeAsync();
                        }
                    }
                    catch (Exception document_ex)
                    {
                        System.Console.Write($"error running c_docment_sync_all.document\n{document_ex}");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.Write($"error running c_docment_sync_all\n{ex}");
            }
        }