index.aspx.cs 17.3 KB
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using ADAM.CernerFHIR.Client;
using ADAM.CernerFHIR.Helper;
using ADAM.CernerFHIR.Model;
using AIAHTML5.API.Models;
using eLearningPlayer;
using eLearningPlayer.model;
using HtmlAgilityPack;

namespace ADAM.AIA
{
    public partial class index : System.Web.UI.Page
    {
        public string strIPAddress = "";
        public bool bValidIP = false;
        public string strAccountNumber = "";
        public string strEdition = "";
        public string strUrlReferer = "";
        public string strSiteReferer = "";
        public string urlParams = "";
        public string test = "";
        public bool isCalsCredantial = false;

        public string cernerEndPointURL = "";
        public string cernerLaunch = "";
        public string cernerCode = "";
        public string cernerState = "";
        public string CernerDocumentId = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            SetQueryStringCerner();

            if (Request.HttpMethod == "POST")
            {
                if (Request.Form["calsCredantial"] != null && Request.Form["calsCredantial"].ToString() == "yes")
                {
                    isCalsCredantial = true;
                 
                    urlParams = "calsCredantial=" + Request.Form["calsCredantial"].ToString() + "&username=" + Request.Form["calsUsername"].ToString() + "&password=" + Request.Form["calsPassword"].ToString();
                    //calsCredantialusername&password
                   // urlParams = Request.Form["calsCredantial"].ToString() + "&username=" + Request.Form["calsUsername"].ToString() + "&password=" + Request.Form["calsPassword"].ToString();

                }
            }
            else
            {
                if (null != cernerEndPointURL && cernerEndPointURL != "")
                {
                    if (null != cernerCode && cernerCode == "")
                    {
                        //var urlRedirect = AsyncToSyncTaskHelper.AsyncHelpers.RunSync<string>(() => ResourceProcessor.CernerConfiguration(cernerEndPointURL, "auth", true));
                        //var urlRedirect = Task.Factory.StartNew<Task<string>>(async () => await ResourceProcessor.CernerConfiguration(baseUrlFHIR, "auth", true));
                                                
                        var AsyncTask = Task.Run(async () => await ResourceProcessor.CernerConfiguration(cernerEndPointURL, "auth", true));
                        
                        var AuthorizationUriRedirect = AsyncTask.Result;
                        if (null != CernerDocumentId && CernerDocumentId != "")
                            Response.Redirect(AuthorizationUriRedirect + "&launch=" + cernerLaunch + "&documentId=" + CernerDocumentId, true);
                        else
                            Response.Redirect(AuthorizationUriRedirect + "&launch=" + cernerLaunch, true);
                    }
                    else
                    {      
                        if (null != CernerDocumentId && CernerDocumentId != "")
                        {
                            Uri url = new Uri(Request.Url.PathAndQuery, UriKind.Relative);
                            var values = new { documentId = CernerDocumentId };
                            var result = url.ExtendQuery(values);
                            //Assert.That(result, Is.EqualTo(new Uri("/test?param1=new-value&param2=val2", UriKind.Relative)));
                            //HttpContext.Current.Request.QueryString.Add("documetId", CernerDocumentId);
                            //AddParameter(Request.Url, "documetId", CernerDocumentId); 
                            //Response.Redirect(result.OriginalString, false);
                        }
                        ApiHelper.InitializeClient();// Initialize FHIR Client.                        
                        RegisterAsyncTask(new PageAsyncTask(() => ProcessCernerResourceAsync(cernerEndPointURL, cernerCode)));// Process FHIR Resource.                        
                    }
                }
                else if(null != CernerDocumentId && CernerDocumentId != "")
                {
                    //AddParameter(Request.Url, "documetId", CernerDocumentId);
                    //ApiHelper.InitializeClient();// Initialize FHIR Client if required.                        
                    //RegisterAsyncTask(new PageAsyncTask(() => ProcessCernerDocumentResourceAsync(cernerEndPointURL, CernerDocumentId)));// Process FHIR Resource.
                    //Response.Write("Loading... to previous state DA !!");
                }
                else
                {
                    //SetCookiesCerner(false,"");
                }
            }

            if (Request.QueryString["mtype"] != null)
            {
                //birendra
                //open default CA module by query string
                isCalsCredantial = true;
               
                string[] allQueryData = new string[Request.QueryString.AllKeys.Length];

                for(int i=0;i< Request.QueryString.AllKeys.Length; i++)
                {
                    allQueryData[i] = Request.QueryString.AllKeys[i] + "=" + Request.QueryString[Request.QueryString.AllKeys[i]].ToString();
                }
                urlParams = string.Join("&", allQueryData);

                //urlParams = "mtype=" + Request.QueryString[allQueryData[].ToString() + "&id=" + Request.QueryString["id"].ToString() + "&username=" + Request.QueryString["username"].ToString() + "&password=" + Request.QueryString["password"].ToString();
            }
            else if (Request.QueryString["account"] != null)
            {
                // http://stackoverflow.com/questions/9032005/request-servervariableshttp-referer-is-not-working-in-ie
                // http://stackoverflow.com/questions/5643773/http-referrer-not-always-being-passed?rq=1
                //
                strSiteReferer = Request.ServerVariables["HTTP_REFERER"];
                strAccountNumber = Request.QueryString["account"];
                strEdition = Request.QueryString["edition"];
                string remoteIPAddress = Request.ServerVariables["REMOTE_ADDR"];
                string strHttpReferer = null;
                int intSiteId = 0;




                if (Request.Form["referer"] != null)
                {
                    strUrlReferer = Request.Form["referer"];
                }
                else if (Request.QueryString["referer"] == null)
                {
                    strUrlReferer = Request.ServerVariables["HTTP_REFERER"];
                }
                else if (Request.Params["referer"] != null)
                {
                    strUrlReferer = Request.Params["referer"];
                }
                else
                {

                    strUrlReferer = Request.QueryString["referer"];
                }


                if (strUrlReferer != "" && strUrlReferer != null)
                {
                    strHttpReferer = strUrlReferer.ToLower().Replace("http://", "").Replace("https://", "").Replace("www.", "").ToString().Split('/')[0].ToString();

                    if (strHttpReferer.IndexOf(":") != -1)
                    {
                        char[] delimiters = new char[] { ':' };
                        string[] parts = strHttpReferer.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                        strHttpReferer = parts[0];
                    }
                }

                try
                {

                    if (strHttpReferer != "" && strHttpReferer != null)
                        strIPAddress = strHttpReferer;
                    if (strIPAddress == "" || strIPAddress == null)
                        strIPAddress = remoteIPAddress;


                  //  intSiteId = LicenseHelper.GetInstance().ValidateLicenseSiteIP(strIPAddress, remoteIPAddress, strAccountNumber, Convert.ToByte(strEdition));

                }
                catch (Exception objEx)
                {

                }
                //urlParams = "?siteIP=" + strIPAddress + "&status=" + intSiteId + "&accountNumber=" + strAccountNumber + "&edition=" + strEdition + "&urlReferer=" + (strSiteReferer != "" && strSiteReferer != null ? strSiteReferer : "");
                urlParams = "siteIP=" + strIPAddress + "&accountNumber=" + strAccountNumber + "&edition=" + strEdition + "&urlReferer=" + (strSiteReferer != "" && strSiteReferer != null ? strSiteReferer : "") + "&remoteIPAddress=" + remoteIPAddress;
             
                //For the ease of splitting desgined urlParms in the pattern of 
                //urlParams = siteIP&accountNumber&remoteIPAddress&edition&urlReferer; without mentioning the variableName
              //  urlParams = strIPAddress + "&" + remoteIPAddress+"&"+  strAccountNumber + "&" + strEdition + "&" + (strSiteReferer != "" && strSiteReferer != null ? strSiteReferer : "");


            }
        }


        #region Cerner FHIR Resource

        private void SetCookiesCerner(bool IsCernerUser, string CernerSessionId)
        {
            var cookieData = new
            {
                isCernerUser = IsCernerUser,
                CernerSessionId
            };
            string myObjectJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(cookieData);
            //Set Cerner Cookies.
            var cernerCookies = new HttpCookie("CernerInfo")
            {
                HttpOnly = false,
                Value = myObjectJson,
                Path = "/",
                SameSite = SameSiteMode.Lax,
                Expires = DateTime.Now.AddMinutes(Session.Timeout)
            };
            Response.Cookies.Add(cernerCookies);
        }

        private void SetQueryStringCerner()
        {
            if (Request.QueryString["iss"] != null)
                cernerEndPointURL = Request.QueryString["iss"];//https://fhir-ehr.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca;
            if (Request.QueryString["launch"] != null)
                cernerLaunch = Request.QueryString["launch"];
            if (Request.QueryString["code"] != null)
                cernerCode = Request.QueryString["code"];
            if (Request.QueryString["state"] != null)
                cernerState = Request.QueryString["state"];

            if (Request.QueryString["documentId"] != null)
                CernerDocumentId = Request.QueryString["documentId"];

            //Session store
            if (cernerEndPointURL != "" && (cernerLaunch != "" || cernerCode != ""))
                Session["iss"] = cernerEndPointURL;

            //Retreive session
            if (Session["iss"] != null && (cernerLaunch != "" || cernerCode != ""))
                cernerEndPointURL = Session["iss"].ToString();

            //Session store documetId
            if(cernerEndPointURL != "" && cernerLaunch != "" && CernerDocumentId != "")
                Session["documetId"] = CernerDocumentId;

            //Retreive session
            if (Session["documetId"] != null && (cernerLaunch != "" || cernerCode != ""))
                CernerDocumentId = Session["documetId"].ToString();

            //If any error occurs from cerner
            if (Request.QueryString["error"] != null)
            {
                var error_uri = Request.QueryString["error_uri"].ToString();
                var url = new Uri(error_uri);
                Response.Redirect(url.AbsoluteUri, true);
            }
        }

        private string GenerateSessionId()
        {
            if (HttpContext.Current.Request.Cookies["CernerInfo"] == null) return Session.SessionID;

            var Cernercookie = HttpContext.Current.Request.Cookies["CernerInfo"].Value;
            var jsonData = Newtonsoft.Json.Linq.JObject.Parse(Cernercookie);
            var cernerCode = jsonData.Value<string>("CernerSessionId");

            if (cernerCode == Session["sessionId"]?.ToString()) return cernerCode;          

            return Session.SessionID;
        }

        private async Task ProcessCernerResourceAsync(string cernerEndPointURL, string cernerCode)
        {
            var token = new LoginResult();
            var cernerInfoJWT = new CernerInfoJWT();
            var sessionId = GenerateSessionId();

            if (Session["CernerToken"] == null)
            {
                // Get the Token from Authentication Server.
                token = await ResourceProcessor.GetCernerResourceToken(cernerEndPointURL, cernerCode);
                token.EndPointURL = cernerEndPointURL;
                cernerInfoJWT = await ResourceProcessor.ProcessJwtString(token);
                Session["CernerToken"] = token;
                Session["CernerInfoJWT"] = cernerInfoJWT;
                Session["Code"] = cernerCode; // set first time launch code.
                Session["sessionId"] = sessionId;


                await CernerUserSession(sessionId, token, cernerInfoJWT, cernerCode);

            }
            else
            {
                if (cernerCode == Session["Code"]?.ToString())
                {
                    token = (LoginResult)Session["CernerToken"];
                    cernerInfoJWT = (CernerInfoJWT)Session["cernerInfoJWT"];
                }
                else
                {
                    token = await ResourceProcessor.GetCernerResourceToken(cernerEndPointURL, cernerCode);
                    cernerInfoJWT = await ResourceProcessor.ProcessJwtString(token);
                    Session["CernerToken"] = token;
                    Session["CernerInfoJWT"] = cernerInfoJWT;
                    Session["Code"] = cernerCode; // New launch code.

                    await CernerUserSession(sessionId, token, cernerInfoJWT, cernerCode);
                }
            }

            SetCookiesCerner(true, sessionId);            
        }

        private async Task SaveCernerUserSessionInfo(CernerUserSessionInfo cernerUserSessionInfo)
        {
            var AIA_API_URL = System.Configuration.ConfigurationManager.AppSettings["AIAAPIURL"];
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(AIA_API_URL);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string cernerUserSessionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(cernerUserSessionInfo);

                //POST Method
                HttpResponseMessage response = await client.PostAsJsonAsync("api/CernerUserSession", cernerUserSessionInfoJson);

                if (response.IsSuccessStatusCode)
                {
                    // Get the URI of the created resource.  
                    Uri returnUrl = response.Headers.Location;
                }
            }
        }

        private async Task ProcessCernerDocumentResourceAsync(string cernerEndPointURL, string documentId)
        {
            //var result =  await Task.Run(async () => await SaveCernerUserSessionInfo(documentId));
            var AIA_API_URL = System.Configuration.ConfigurationManager.AppSettings["AIAAPIURL"];
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(AIA_API_URL);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //string cernerUserSessionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(cernerUserSessionInfo);

                //POST Method
                HttpResponseMessage response = await client.GetAsync("api/CernerUserSession/" + documentId);

                
                var receiveStream = await response.Content.ReadAsStringAsync();

                //StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                var cernerUserSessionInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<CernerUserImageAIA>(receiveStream);

                if (response.IsSuccessStatusCode)
                {
                    // Get the URI of the created resource.  
                    Uri returnUrl = response.Headers.Location;
                    var result = response.Content;
                }
            }
        }

        private async Task CernerUserSession(string sessionId, LoginResult token, CernerInfoJWT cernerInfoJWT, string cernerCode)
        {
            //Create object and save to AIA DB

            var cernerUserSessionInfo = new CernerUserSessionInfo()
            {
                FhirUserSessionId = sessionId,
                LoginResult = token,
                CernerInfoJWT = cernerInfoJWT,
                CernerCode = cernerCode
            };

            //Call API.
            await Task.Run(async () => await SaveCernerUserSessionInfo(cernerUserSessionInfo));
        }

        //public static Uri AddParameter(this Uri url, string paramName, string paramValue)
        //{
        //    var uriBuilder = new UriBuilder(url);
        //    var query = HttpUtility.ParseQueryString(uriBuilder.Query);
        //    query[paramName] = paramValue;
        //    uriBuilder.Query = query.ToString();

        //    return uriBuilder.Uri;
        //}
        #endregion
    }
}