<%@ WebHandler Language="C#" Class="RefreshTokenHandler" %>

using System;
using System.Web;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Collections.Generic;

public class RefreshTokenHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest (HttpContext context)
    {

        RefreshTokenIfSessionActive();
        context.Response.ContentType = "application/json";
        var token = HttpContext.Current.Session["AccessToken"] != null ? HttpContext.Current.Session["AccessToken"].ToString() : null;


        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { token = token }));
    }

    public bool IsReusable { get { return false; } }

    private void RefreshTokenIfSessionActive()
    {
        if (HttpContext.Current.Session["UserName"] != null)
        {

            HighriseCommonUtls.BaseResponse Resp = new HighriseCommonUtls.BaseResponse();
            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers["Content-type"] = "application/json";
            // client.Headers["Authorization"] = "Bearer " + AccessToken;
            client.Encoding = Encoding.UTF8;

            try
            {
                string apiUrl = HighriseCommonUtls.GetURL("Authentication") + "/ReGenerateToken";

                Dictionary<string, object> objFilter = new Dictionary<string, object>();
                objFilter.Add("UserID", HttpContext.Current.Session["UserId"]);
                string jsonData = JsonConvert.SerializeObject(objFilter);

                string jsonResponse = client.UploadString(apiUrl , jsonData);
                Resp = JsonConvert.DeserializeObject<HighriseCommonUtls.BaseResponse>(jsonResponse);
            }
            catch(WebException webEx)
            {
                string responseText = "";
                if (webEx.Response != null)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)webEx.Response;
                    if (httpResponse.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        using (Stream stream = webEx.Response.GetResponseStream())
                        {
                            if (stream != null)
                            {
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    responseText = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
                Resp = JsonConvert.DeserializeObject<HighriseCommonUtls.BaseResponse>(responseText);
            }

            var token = Resp.ClientMessage;
            HttpContext.Current.Session["AccessToken"] = token;
            StoreTokenInCookie(token);
            PageBase p = new PageBase();
            p.PageLoad();

        }
        else
        {
            HttpContext.Current.Session["AccessToken"] = "";
            StoreTokenInCookie("");
        }
    }

    private void StoreTokenInCookie(string token)
    {
        HttpCookie tokenCookie = new HttpCookie("JwtToken_"+HttpContext.Current.Session["UserId"], token)
        {
            //HttpOnly = true,
            // Secure = true, // Set to true if using HTTPS
            Expires = DateTime.UtcNow.AddHours(15)
        };
        HttpContext.Current.Response.Cookies.Add(tokenCookie);
    }

}