Пример #1
0
        private bool url_endpoint_exists(string p_target_db_url, string p_user_name, string p_password)
        {
            bool result = false;

            var curl = new cURL("HEAD", null, p_target_db_url, null, p_user_name, p_password);

            try
            {
                curl.execute();

                /*
                 * HTTP/1.1 200 OK
                 * Cache-Control: must-revalidate
                 * Content-Type: application/json
                 * Date: Mon, 12 Aug 2013 01:27:41 GMT
                 * Server: CouchDB (Erlang/OTP)*/
                result = true;
            }
            catch (Exception ex)
            {
                // do nothing for now
            }


            return(result);
        }
Пример #2
0
        private bool sync_document(string p_document_json, string p_target_db_url, string p_user_name, string p_password)
        {
            bool result = false;

            string revision_id           = get_revision(p_target_db_url);
            string storage_document_json = null;

            if (!string.IsNullOrEmpty(revision_id))
            {
                storage_document_json = set_revision(p_document_json, revision_id);
            }
            else
            {
                storage_document_json = p_document_json;
            }

            var curl = new cURL("PUT", null, p_target_db_url, storage_document_json, p_user_name, p_password);

            try
            {
                string curl_result = curl.execute();
                System.Console.WriteLine("db_setupController.sync_document");
                System.Console.WriteLine(curl_result);
                result = true;
            }
            catch (Exception ex)
            {
                //System.Console.WriteLine("c_sync_document de_id");
                //System.Console.WriteLine(ex);
            }

            return(result);
        }
Пример #3
0
        private 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 document_json = null;

            try
            {
                document_json = document_curl.execute();
                var request_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (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);
        }
Пример #4
0
        private bool Verify_Password(string p_target_server, string p_user_name, string p_password)
        {
            bool result = false;

            var curl = new cURL("GET", null, p_target_server + "/mmrds/_design/auth", null, p_user_name, p_password);

            try
            {
                curl.execute();

                /*
                 * HTTP/1.1 200 OK
                 * Cache-Control: must-revalidate
                 * Content-Type: application/json
                 * Date: Mon, 12 Aug 2013 01:27:41 GMT
                 * Server: CouchDB (Erlang/OTP)*/
                result = true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"failed Verify_Password check: {p_target_server}/mmrds/_design/auth\n{ex}");
            }


            return(result);
        }
Пример #5
0
        private CookieAuthenticationEvents get_sams_authentication_events()
        {
            //https://stackoverflow.com/questions/52175302/handling-expired-refresh-tokens-in-asp-net-core

            var sams_endpoint_authorization    = Configuration["sams:endpoint_authorization"];
            var sams_endpoint_token            = Configuration["sams:endpoint_token"];
            var sams_endpoint_user_info        = Configuration["sams:endpoint_user_info"];
            var sams_endpoint_token_validation = Configuration["sams:token_validation"];
            var sams_endpoint_user_info_sys    = Configuration["sams:user_info_sys"];
            var sams_client_id     = Configuration["sams:client_id"];
            var sams_client_secret = Configuration["sams:client_secret"];
            var sams_callback_url  = Configuration["sams:callback_url"];

            var result = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = context =>
                {
                    //check to see if user is authenticated first
                    if (context.Principal.Identity.IsAuthenticated)
                    {
                        var expires_at = context.Request.Cookies["expires_at"];

                        var expires_at_time = DateTimeOffset.Parse(expires_at);

/*
 *                      var accessToken = context.Request.HttpContext.Session.GetString("access_token");
 *                      var refreshToken = context.Request.HttpContext.Session.GetString("refresh_token");
 *                      var exp = context.Request.HttpContext.Session.GetInt32("expires_in");
 */

                        /*
                         *          var tokens = context.Properties.GetTokens();
                         *          var refreshToken = tokens.FirstOrDefault(t => t.Name == "refresh_token");
                         *          var accessToken = tokens.FirstOrDefault(t => t.Name == "access_token");
                         *          var exp = tokens.FirstOrDefault(t => t.Name == "expires_at");
                         *          var expires = DateTime.Parse(exp.Value);
                         */

                        //context.Request.Cookies.["sid"].
                        // var expires = DateTime.Parse(exp.ToString());
                        //check to see if the token has expired
                        if (expires_at_time.DateTime < DateTime.Now)
                        {
                            try
                            {
                                var sid = context.Request.Cookies["sid"];

                                string request_string = Program.config_couchdb_url + $"/session/{sid}";
                                var    curl           = new cURL("GET", null, request_string, null, Program.config_timer_user_name, Program.config_timer_password);
                                string session_json   = curl.execute();
                                var    session        = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.session> (session_json);

                                var userName = context.Principal.Identities.First(
                                    u => u.IsAuthenticated &&
                                    u.HasClaim(c => c.Type == ClaimTypes.Name)).FindFirst(ClaimTypes.Name).Value;


                                if (!userName.Equals(session.user_id, StringComparison.OrdinalIgnoreCase))
                                {
                                    context.RejectPrincipal();
                                    return(Task.CompletedTask);
                                }

                                var accessToken  = session.data["access_token"];
                                var refreshToken = session.data["refresh_token"];
                                var exp          = session.data["expires_at"];
                                expires_at_time = DateTimeOffset.Parse(exp);

                                // server-side check for expiration
                                if (expires_at_time.DateTime < DateTime.Now)
                                {
                                    //token is expired, let's attempt to renew
                                    var tokenEndpoint = sams_endpoint_token;
                                    var tokenClient   = new mmria.server.util.TokenClient(Configuration);

                                    //var name = HttpContext.Session.GetString(SessionKeyName);
                                    //var name = HttpContext.Session.GetString(SessionKeyName);

                                    var tokenResponse = tokenClient.get_refresh_token(accessToken.ToString(), refreshToken.ToString()).Result;
                                    //check for error while renewing - any error will trigger a new login.
                                    if (tokenResponse.is_error)
                                    {
                                        //reject Principal
                                        context.RejectPrincipal();
                                        return(Task.CompletedTask);
                                    }
                                    //set new token values
                                    refreshToken = tokenResponse.refresh_token;
                                    accessToken  = tokenResponse.access_token;
                                    var unix_time = DateTimeOffset.UtcNow.AddSeconds(tokenResponse.expires_in);

                                    session.data["access_token"]  = accessToken;
                                    session.data["refresh_token"] = refreshToken;
                                    session.data["expires_at"]    = unix_time.ToString();

                                    context.Response.Cookies.Append("expires_at", unix_time.ToString());


                                    session.date_last_updated = DateTime.UtcNow;


                                    var Session_Message = new mmria.server.model.actor.Session_Message
                                                          (
                                        session._id,               //_id =
                                        session._rev,              //_rev =
                                        session.date_created,      //date_created =
                                        session.date_last_updated, //date_last_updated =
                                        session.date_expired,      //date_expired =

                                        session.is_active,         //is_active =
                                        session.user_id,           //user_id =
                                        session.ip,                //ip =
                                        session.session_event_id,  // session_event_id =
                                        session.data
                                                          );

                                    Program.actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Post_Session>()).Tell(Session_Message);

                                    //trigger context to renew cookie with new token values
                                    context.ShouldRenew = true;
                                    return(Task.CompletedTask);
                                }
                            }
                            catch (Exception ex)
                            {
                                // do nothing for now document doesn't exsist.
                                System.Console.WriteLine($"err caseController.Post\n{ex}");
                            }
                        }
                    }
                    return(Task.CompletedTask);
                }
            };

            return(result);
        }
Пример #6
0
        public IDictionary <string, string> Get
        (
            string p_target_db_user_name,
            string p_target_db_password

        )
        {
            Dictionary <string, string> result = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            //var curl = new cURL ("GET", null, p_source_db + "/mmrds/_all_docs?include_docs=true", null, p_user_name, p_password);
            if (!url_endpoint_exists(Program.config_couchdb_url, p_target_db_user_name, p_target_db_password))
            {
                result.Add("End point url NOT available:", Program.config_couchdb_url);
                return(result);
            }

            try
            {
                string current_directory = AppDomain.CurrentDomain.BaseDirectory;

                if (!url_endpoint_exists(Program.config_couchdb_url + "/metadata", p_target_db_user_name, p_target_db_password))
                {
                    var metadata_curl = new cURL("PUT", null, Program.config_couchdb_url + "/metadata", null, p_target_db_user_name, p_target_db_password);
                    System.Console.WriteLine("metadata_curl\n{0}", metadata_curl.execute());

                    new cURL("PUT", null, Program.config_couchdb_url + "/metadata/_security", "{\"admins\":{\"names\":[],\"roles\":[\"form_designer\"]},\"members\":{\"names\":[],\"roles\":[]}}", p_target_db_user_name, p_target_db_password).execute();
                    System.Console.WriteLine("metadata/_security completed successfully");
                }

                try
                {
                    string metadata_design_auth = System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/metadata_design_auth.json")).ReadToEnd();

                    sync_document(metadata_design_auth, Program.config_couchdb_url + "/metadata/_design/auth", p_target_db_user_name, p_target_db_password);

                    //var metadata_design_auth_curl = new cURL ("PUT", null, Program.config_couchdb_url + "/metadata/_design/auth", metadata_design_auth, p_target_db_user_name, p_target_db_password);
                    //metadata_design_auth_curl.execute ();

                    string metadata_json = System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/metadata.json")).ReadToEnd();
                    sync_document(metadata_json, Program.config_couchdb_url + "/metadata/2016-06-12T13:49:24.759Z", p_target_db_user_name, p_target_db_password);

                    //var metadata_json_curl = new cURL ("PUT", null, Program.config_couchdb_url + "/metadata/2016-06-12T13:49:24.759Z", metadata_json, p_target_db_user_name, p_target_db_password);
                    //metadata_json_curl.execute ();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("unable to configure metadata:\n{0}", ex);
                }



                if (!url_endpoint_exists(Program.config_couchdb_url + "/mmrds", p_target_db_user_name, p_target_db_password))
                {
                    var mmrds_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds", null, p_target_db_user_name, p_target_db_password);
                    System.Console.WriteLine("mmrds_curl\n{0}", mmrds_curl.execute());

                    new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_security", "{\"admins\":{\"names\":[],\"roles\":[\"form_designer\"]},\"members\":{\"names\":[],\"roles\":[\"abstractor\",\"data_analyst\",\"timer\"]}}", p_target_db_user_name, p_target_db_password).execute();
                    System.Console.WriteLine("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, p_target_db_user_name, p_target_db_password);
                    //case_design_sortable_curl.execute ();
                    sync_document(case_design_sortable, Program.config_couchdb_url + "/mmrds/_design/sortable", p_target_db_user_name, p_target_db_password);


                    string case_store_design_auth = System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/case_store_design_auth.json")).ReadToEnd();
                    //var case_store_design_auth_curl = new cURL ("PUT", null, Program.config_couchdb_url + "/mmrds/_design/auth", case_store_design_auth, p_target_db_user_name, p_target_db_password);
                    //case_store_design_auth_curl.execute ();
                    sync_document(case_store_design_auth, Program.config_couchdb_url + "/mmrds/_design/auth", p_target_db_user_name, p_target_db_password);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("unable to configure mmrds database:\n", ex);
                }


                if (!url_endpoint_exists(Program.config_couchdb_url + "/export_queue", p_target_db_user_name, p_target_db_password))
                {
                    System.Console.WriteLine("Creating export_queue db.");
                    var export_queue_curl = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue", null, p_target_db_user_name, p_target_db_password);
                    System.Console.WriteLine(export_queue_curl.execute());
                    new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/_security", "{\"admins\":{\"names\":[],\"roles\":[\"abstractor\"]},\"members\":{\"names\":[],\"roles\":[\"abstractor\"]}}", p_target_db_user_name, p_target_db_password).execute();
                }

                Program.StartSchedule();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                result.Add("db_setupController.Get Exception", ex.ToString());
            }


            //return result;
            return(result);
        }