using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MasterPages_Main : System.Web.UI.MasterPage
{
     private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;
 
    protected void Page_Init(object sender, EventArgs e)
    {
        //First, check for the existence of the Anti-XSS cookie
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;
 
        //If the CSRF cookie is found, parse the token from the cookie.
        //Then, set the global page variable and view state user
        //key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
        //method.
        if (requestCookie != null
        && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            //Set the global token variable so the cookie value can be
            //validated against the value in the view state form field in
            //the Page.PreLoad method.
            _antiXsrfTokenValue = requestCookie.Value;
 
            //Set the view state user key, which will be validated by the
            //framework during each request
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        //If the CSRF cookie is not found, then this is a new session.
        else
        {
            //Generate a new Anti-XSRF token
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
 
            //Set the view state user key, which will be validated by the
            //framework during each request
            Page.ViewStateUserKey = _antiXsrfTokenValue;
 
            //Create the non-persistent CSRF cookie
            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                //Set the HttpOnly property to prevent the cookie from
                //being accessed by client side script
                HttpOnly = true,
    
                //Add the Anti-XSRF token to the cookie value
                Value = _antiXsrfTokenValue
                //,
                //Path = Request.ApplicationPath
            };
 
            //If we are using SSL, the cookie should be set to secure to
            //prevent it from being sent over HTTP connections
            if (FormsAuthentication.RequireSSL &&
            Request.IsSecureConnection)
            responseCookie.Secure = true;
 
            //Add the CSRF cookie to the response
            Response.Cookies.Set(responseCookie);
        }
 
            Page.PreLoad += master_Page_PreLoad;
        }
 
        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            //During the initial page load, add the Anti-XSRF token and user
            //name to the ViewState
            if (!IsPostBack)
            {
                //Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
 
                //If a user name is assigned, set the user name
                ViewState[AntiXsrfUserNameKey] =
                Context.User.Identity.Name ?? String.Empty;
            }
            //During all subsequent post backs to the page, the token value from
            //the cookie should be validated against the token in the view state
            //form field. Additionally user name should be compared to the
            //authenticated users name
            else
            {
                //Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                || (string)ViewState[AntiXsrfUserNameKey] !=
                (Context.User.Identity.Name ?? String.Empty))
            {
                 throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["uid"] == null && Session["AuthToken"] == null && Request.Cookies["AuthToken"] == null)
        {
            Response.Redirect("../Security/LoginPage.aspx");
        }
        else
        {
            if (Session["pageArea"] != "A")
            {
                if (!String.IsNullOrEmpty(Session["uid"] as string))
                    Helper.LogOut(Session["uid"].ToString()); 
                HttpContext.Current.Session.Clear();
                HttpContext.Current.Session.Abandon();
                //HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

                Response.Redirect("../Security/LoginPage.aspx");
            } 
            if (Session["uid"] == null || Session["AuthToken"] == null)
            {
                Response.Redirect("../Security/LoginPage.aspx");
            }
            if (Session["uid"] == null && Session["AuthToken"] == null && Request.Cookies["AuthToken"] == null)
            {
                Response.Redirect("../Security/LoginPage.aspx");
            }
            if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value))
            {

                Response.Redirect("../Security/LoginPage.aspx");

            }
            else
            {
                string[] temp;
                string response = "", message = "";
                temp = Request.Url.ToString().Split('/');

                string path = temp[temp.Length - 2] + "/" + temp[temp.Length - 1];
                if (path.Contains("?"))
                {
                    path = path.Substring(0, path.IndexOf('?'));
                }
                string userID = Session["uid"].ToString();
                DataSet ds = new DataSet();
                ds = SecurityAgent.authenticateUserPage(userID, path, ref response, ref message);

                if (!response.Equals("0"))
                {
                    Response.Redirect("../Business/default.aspx?err=1");
                }

                applySecurity(ds);

                if (!IsPostBack)
                {
                    Label2.Text = DateTime.Now.Date.ToString("dd-MM-yyyy");
                    Label3.Text = DateTime.Now.TimeOfDay.ToString().Split('.')[0];
                    Label1.Text = Session["username"].ToString();
                    LabelVersion.Text = Helper.App_Version;
                }

            }

        }
        Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        Response.AppendHeader("Expires", "0"); // Proxies.
    }

    private void applySecurity(DataSet ds)
    {
        string fn = "";
        string[] array;
        if (ds.Tables[0].Rows.Count == 0)
            return;
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            fn = ds.Tables[0].Rows[i][3].ToString();
            if (fn[0].ToString().ToUpper().Equals("G"))
            {
                array = fn.Split('.');
                GridView gv = (GridView)ContentPlaceHolder1.FindControl(array[0]);
                gv.Columns[int.Parse(array[1])].Visible = false;
            }
            else
            {
                ContentPlaceHolder1.FindControl(fn).Visible = false;
            }
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //if(Context.User.Identity.IsAuthenticated)
          //  Page.ViewStateUserKey = Session.SessionID; 
    }
}
