using System;
using System.Data;
using System.Configuration;
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;
using System.Web.SessionState;


namespace digioz
{
    /// <summary>
    /// Login Helper Class
    /// </summary>
    public class Login : ILogin
    {
        private static PortalSettings coPortalSettings;
        private static Utility coUtility;

        public Login()
        {
        }

        /// <summary>
        /// CheckForCookie()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        bool ILogin.CheckForCookie(System.Web.SessionState.HttpSessionState Session, Page pg)
        {
            bool result = false;

            result = (pg.Request.Cookies["DigiOzPortalAuthUser"] != null);

            return result;
        }

        /// <summary>
        /// CheckForCookie()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        bool ILogin.CheckForCookie(System.Web.SessionState.HttpSessionState Session, Page pg, string cookieName)
        {
            bool result = false;

            result = (pg.Request.Cookies[cookieName] != null);

            return result;
        }

        /// <summary>
        /// RefUrlValidation()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        void ILogin.RefUrlValidation(System.Web.SessionState.HttpSessionState Session, Page pg)
        {
            if (Session["referringURL"] == null)
            {
                try
                {
                    Session["referringURL"] = pg.Request.UrlReferrer.ToString();
                }
                catch
                {
                    Session["referringURL"] = "Default.aspx";
                }
            }
        }

        /// <summary>
        /// Authenticate()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        /// <param name="rememberMe"></param>
        /// <param name="login1Username"></param>
        /// <param name="login1Password"></param>
        bool ILogin.Authentication(System.Web.SessionState.HttpSessionState Session, Page pg, bool rememberMe, string login1Username, string login1Password)
        {
            #region Variable Declaration
            string lsSQL = string.Empty;
            string lsSQL2 = string.Empty;
            bool result = false;
            string cipherText = String.Empty;
            string lsKey = String.Empty;
            string lsVector = String.Empty;            
            #endregion

            coPortalSettings = PortalSettingsManagement.GetPortalSettings();
            

            if (coPortalSettings.DBRelational == true)
            {
                IDataRelational loDB = DataFactory.GetDataObject(coPortalSettings);
                DataTable loLoginTable;


                lsKey = coPortalSettings.EncryptionKey;
                lsVector = coPortalSettings.EncryptionVector;

                lsSQL = "SELECT [username],[password],[permission],[id] FROM [tblUsers];";

                loDB.openConnection();
                loLoginTable = loDB.QueryDBDataset(lsSQL);

                foreach (DataRow loDR in loLoginTable.Rows)
                {
                    if (loDR.ItemArray[0].ToString() == login1Username)
                    {
                        try
                        {
                            digioz.RijndaelEnhanced rijndaelKey = new digioz.RijndaelEnhanced(lsKey, lsVector);
                            cipherText = rijndaelKey.Decrypt(loDR.ItemArray[1].ToString());
                            if (cipherText == login1Password)
                            {
                                Session["username"] = (string)loDR["username"];
                                Session["password"] = (string)loDR["password"];
                                Session["permission"] = (string)loDR["permission"];
                                Session["userid"] = (int)loDR["id"];

                                

                                if (rememberMe)
                                {
                                    ////////// Create Cookie ////////////////////////////////////////////////////////////////      
                                    HttpCookie digiAuthUser = new HttpCookie("DigiOzPortalAuthUser");
                                    pg.Response.Cookies.Remove("DigiOzPortalAuthUser");
                                    pg.Response.Cookies.Add(digiAuthUser);
                                    digiAuthUser.Values.Add("authUsrName", loDR.ItemArray[0].ToString());
                                    digiAuthUser.Values.Add("authPassword", loDR.ItemArray[1].ToString());
                                    digiAuthUser.Values.Add("authHostRequest", rijndaelKey.Encrypt(pg.Request.ServerVariables["server_name"] + pg.Request.ServerVariables["PATH_INFO"]));
                                    digiAuthUser.Values.Add("rememberMe", "true");
                                    DateTime expDate = DateTime.Now.AddDays(30);
                                    pg.Response.Cookies["DigiOzPortalAuthUser"].Expires = expDate;
                                    ////////////////////////////////////////////////////////////////////////////////////////                            
                                }
                                else
                                {
                                    //Delete Cookie /////////////////////////////////////////////////////////////////////////
                                    pg.Response.Cookies["DigiOzPortalAuthUser"].Expires = DateTime.Now.AddDays(-20);
                                    /////////////////////////////////////////////////////////////////////////////////////////
                                }
                                result = true;
                            }                            

                        }
                        catch
                        {
                            result = false;
                        }
                    }
                }
                
                //////// VisitorIP - Check if user IP is behind a proxy server ////////////////////////////
                if (pg.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                { Session["visitorIP"] = pg.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; }
                else
                { Session["visitorIP"] = pg.Request.ServerVariables["REMOTE_ADDR"]; }
                ///////////////////////////////////////////////////////////////////////////////////////////
                
                if (result == true)
                {
                    lsSQL2 = "EXEC spInsertSiteLog '" + Session["username"] + "','" + Session["visitorIP"] + "','Login Successful';";
                }
                else
                {
					string failedUser = Utility.ConvertHtmlToPlainText(login1Username);
                    lsSQL2 = "EXEC spInsertSiteLog '" + failedUser + "','" + Session["visitorIP"] + "','Login Failed';";
                }

                //Execute SQL Site Log Command
                if (lsSQL2 != "")
                {
                    loDB.ExecDB(lsSQL2);
                }

                loDB.closeConnection();
            }

            return result;
        }

        /// <summary>
        /// Authenticate()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        /// <param name="cookieName"></param>
        bool ILogin.Authentication(System.Web.SessionState.HttpSessionState Session, Page pg, HttpCookie cookie)
        {
            #region Variable Declaration and Initialization
            string authUsrName = cookie.Values["authUsrName"];
            string authPassword = cookie.Values["authPassword"];
            string authHostRequest = cookie.Values["authHostRequest"];
            string remember = cookie.Values["rememberMe"];
            string lsSQL = "SELECT [username],[password],[permission],[id] FROM [tblUsers];";
            string lsSQL2 = string.Empty;
            bool result = false;
            string hostRequest = string.Empty;
            string cipherText = String.Empty;
            string cipherCookieText = String.Empty;
            string cipherHostRequest = string.Empty;
            string lsKey = String.Empty;
            string lsVector = String.Empty;
            #endregion


            coPortalSettings = PortalSettingsManagement.GetPortalSettings();
            

            if (coPortalSettings.DBRelational == true)
            {
                IDataRelational loDB = DataFactory.GetDataObject(coPortalSettings);
                DataTable loLoginTable;


                lsKey = coPortalSettings.EncryptionKey;
                lsVector = coPortalSettings.EncryptionVector;


                lsSQL = "SELECT [username],[password],[permission],[id] FROM [tblUsers];";

                loDB.openConnection();
                loLoginTable = loDB.QueryDBDataset(lsSQL);

                foreach (DataRow loDR in loLoginTable.Rows)
                {
                    if (loDR.ItemArray[0].ToString() == authUsrName)
                    {
                        try
                        {
                            //Create Class Object For Cookie and Password Decryption
                            digioz.RijndaelEnhanced rijndaelKey = new digioz.RijndaelEnhanced(lsKey, lsVector);
                            cipherText = rijndaelKey.Decrypt(loDR.ItemArray[1].ToString());
                            hostRequest = pg.Request.ServerVariables["server_name"] + pg.Request.ServerVariables["PATH_INFO"];
                            cipherCookieText = rijndaelKey.Decrypt(authPassword);
                            cipherHostRequest = rijndaelKey.Decrypt(authHostRequest);
                            

                            if (cipherText == cipherCookieText && hostRequest == cipherHostRequest)
                            {
                                //Set Session Variables
                                Session["username"] = (string)loDR["username"];
                                Session["password"] = (string)loDR["password"];
                                Session["permission"] = (string)loDR["permission"];
                                Session["userid"] = (int)loDR["id"];

                                result = true;
                            }
                            break;
                        }
                        catch
                        {
                            result = false;
                        }
                    }
                }
                
                //////// VisitorIP - Check if user IP is behind a proxy server ////////////////////////////
                if (pg.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                { Session["visitorIP"] = pg.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; }
                else
                { Session["visitorIP"] = pg.Request.ServerVariables["REMOTE_ADDR"]; }
                ///////////////////////////////////////////////////////////////////////////////////////////
                

                if (result == true)
                {
                    lsSQL2 = "EXEC spInsertSiteLog '" + Session["username"] + "','" + Session["visitorIP"] + "','Login Successful';";
                }
                else
                {
					string failedUser = Utility.ConvertHtmlToPlainText(authUsrName);					
                    lsSQL2 = "EXEC spInsertSiteLog '" + failedUser + "','" + Session["visitorIP"] + "','Login Failed';";
                }

                //Execute SQL Site Log Command
                if (lsSQL2 != "")
                {
                    loDB.ExecDB(lsSQL2);
                }

                //Close Connection
                loDB.closeConnection();

            }
            return result;
        }

        /// <summary>
        /// PageAuthenticate()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>   
        bool ILogin.PageAuthentication(System.Web.SessionState.HttpSessionState Session, Page pg)
        {
            #region Variable Declaration
            string lsSQL = "SELECT [username],[password],[permission],[id] FROM [tblUsers];";
            string lsSQL2 = string.Empty;
            bool result = false;
            string cipherText = String.Empty;
            string lsKey = String.Empty;
            string lsVector = String.Empty;
            string username = string.Empty;
            string password = string.Empty;
            string permission = string.Empty;
            string userId = string.Empty;
            #endregion

            coPortalSettings = PortalSettingsManagement.GetPortalSettings();

            if (coPortalSettings.DBRelational == true)
            {
                IDataRelational loDB = DataFactory.GetDataObject(coPortalSettings);
                DataTable loLoginTable;


                lsKey = coPortalSettings.EncryptionKey;
                lsVector = coPortalSettings.EncryptionVector;


                //Open Connection and Query Database
                loDB.openConnection();
                loLoginTable = loDB.QueryDBDataset(lsSQL);


                foreach (DataRow loDR in loLoginTable.Rows)
                {
                    if (loDR.ItemArray[0].ToString() == Session["username"].ToString())
                    {
                        try
                        {
                            //Create Class Object For Password Decryption
                            digioz.RijndaelEnhanced rijndaelKey = new digioz.RijndaelEnhanced(lsKey, lsVector);
                            cipherText = rijndaelKey.Decrypt(loDR.ItemArray[1].ToString());

                            if (cipherText == rijndaelKey.Decrypt(Session["password"].ToString()))
                            {
                                permission = loDR.ItemArray[2].ToString();
                                userId = loDR.ItemArray[3].ToString();

                                switch (Convert.ToString(pg))
                                {
                                    case "ASP.admin_aspx":
                                        if (userId == Session["userid"].ToString() &&
                                            permission == Session["permission"].ToString() &&
                                            Session["permission"].ToString() == "1")
                                        {
                                            result = true;
                                        }
                                        else
                                        {
                                            result = false;
                                        }
                                        break;
                                    case "ASP.default_aspx":
                                        if (permission == Session["permission"].ToString() &&
                                            userId == Session["userid"].ToString())
                                        {
                                            result = true;
                                        }
                                        else
                                        {
                                            result = false;
                                        }
                                        break;
                                }
                            }
                            break;
                        }
                        catch
                        {
                            result = false;
                        }
                    }
                }

                //Close Connection
                loDB.closeConnection();
            }
            return result;
        }

        /// <summary>
        /// PageAuthenticate()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        /// <param name="cookieName"></param>
        bool ILogin.PageAuthentication(System.Web.SessionState.HttpSessionState Session, Page pg, HttpCookie cookie)
        {
            #region Variable Declaration and Initialization
            string authUsrName = cookie.Values["authUsrName"];
            string authPassword = cookie.Values["authPassword"];
            string remember = cookie.Values["rememberMe"];
            string lsSQL = "SELECT [username],[password],[permission],[id] FROM [tblUsers];";
            bool result = false;
            string cipherText = String.Empty;
            string cipherCookieText = String.Empty;
            string lsKey = String.Empty;
            string lsVector = String.Empty;
            string username = string.Empty;
            string password = string.Empty;
            string permission = string.Empty;
            string userId = string.Empty;
            #endregion

            coPortalSettings = PortalSettingsManagement.GetPortalSettings();

            if (coPortalSettings.DBRelational == true)
            {
                IDataRelational loDB = DataFactory.GetDataObject(coPortalSettings);
                DataTable loLoginTable;


                lsKey = coPortalSettings.EncryptionKey;
                lsVector = coPortalSettings.EncryptionVector;


                //Open Connection and Query Database
                loDB.openConnection();
                loLoginTable = loDB.QueryDBDataset(lsSQL);


                foreach (DataRow loDR in loLoginTable.Rows)
                {
                    if (loDR.ItemArray[0].ToString() == authUsrName)
                    {
                        try
                        {
                            //Create Class Object For Cookie and Password Decryption
                            digioz.RijndaelEnhanced rijndaelKey = new digioz.RijndaelEnhanced(lsKey, lsVector);
                            cipherText = rijndaelKey.Decrypt(loDR.ItemArray[1].ToString());
                            cipherCookieText = rijndaelKey.Decrypt(authPassword);

                            //Set Session Variables
                            Session["username"] = (string)loDR["username"];
                            Session["password"] = (string)loDR["password"];
                            Session["permission"] = (string)loDR["permission"];
                            Session["userid"] = (int)loDR["id"];


                            if (cipherText == cipherCookieText)
                            {
                                switch (Convert.ToString(pg))
                                {
                                    case "ASP.admin_aspx":
                                        if (userId == Session["userid"].ToString() &&
                                            username == Session["username"].ToString() &&
                                            password == Session["password"].ToString() &&
                                            permission == Session["permission"].ToString() &&
                                            Session["permission"].ToString() == "1")
                                        {
                                            result = true;
                                        }
                                        else
                                        {
                                            result = false;
                                        }
                                        break;
                                    case "ASP.default_aspx":
                                        if (userId == Session["userid"].ToString() &&
                                            username == Session["username"].ToString() &&
                                            password == Session["password"].ToString() &&
                                            permission == Session["permission"].ToString())
                                        {
                                            result = true;
                                        }
                                        else
                                        {
                                            result = false;
                                        }
                                        break;
                                }

                            }
                            break;
                        }
                        catch
                        {
                            result = false;
                        }
                    }
                }

                //Close Connection
                loDB.closeConnection();
            }
            return result;
        }


        /// <summary>
        /// GetCookie()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>    
        HttpCookie ILogin.GetCookie(System.Web.SessionState.HttpSessionState Session, Page pg)
        {
            HttpCookie cookie = pg.Request.Cookies.Get("DigiOzPortalAuthUser");
            return cookie;
        }

        /// <summary>
        /// GetCookie()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        /// <param name="cookieName"></param>
        HttpCookie ILogin.GetCookie(System.Web.SessionState.HttpSessionState Session, Page pg, string cookieName)
        {
            HttpCookie cookie = pg.Request.Cookies.Get(cookieName);
            return cookie;
        }

        /// <summary>
        /// Redirection()
        /// </summary>   
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        void ILogin.Redirection(System.Web.SessionState.HttpSessionState Session, Page pg)
        {
            string urlReferer = string.Empty;
            string protocol = string.Empty;
            string sysUrl = string.Empty;
            string https = string.Empty;
            string domain = string.Empty;
            string port = string.Empty;
            string app = string.Empty;

            ///////////// Retrieve Url Referer ////////////////////////////////////////////////////////                           
            urlReferer = pg.Request.Url.ToString().Substring(0, pg.Request.Url.ToString().LastIndexOf("/"));
            /////////////////////////////////////////////////////////// ///////////////////////////////

            //////////// Retrieve Server Url //////////////////////////////////////////////////////////                            
            protocol = "http";
            port = pg.Request.ServerVariables["SERVER_PORT"];
            https = pg.Request.ServerVariables["HTTPS"];

            if (https != "")
            {
                if (https != "off")
                { protocol = "https"; }
            }

            if (port != string.Empty)
            {
                domain = pg.Request.ServerVariables["SERVER_NAME"] + ":" + pg.Request.ServerVariables["SERVER_PORT"];
            }
            else
            {
                domain = pg.Request.ServerVariables["SERVER_NAME"];
            }

            app = pg.Request.ApplicationPath;
            sysUrl = protocol + "://" + domain + app;
            /////////////////////////////////////////////////////////////////////////////////////////

            if (urlReferer != sysUrl)
            {
                pg.Response.Redirect("Default.aspx");
            }
            else
            {
                string lsTmp = Convert.ToString(Session["referringURL"]);
                Session["referringURL"] = null;
                pg.Response.Redirect(lsTmp);
            }
        }

        /// <summary>
        /// Logout()
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="pg"></param>
        void ILogin.Logout(System.Web.SessionState.HttpSessionState Session, Page pg)
        {
            //Delete this user out of the chat database. 
            ChatUsersOnlineManagement.DeleteChatUserOnline(Session["username"].ToString());

            Session["username"] = null;
            Session["password"] = null;
            Session["permission"] = null;
            Session["userid"] = null;
            Session["vistorIP"] = null;
            Session["PromptShown"] = null;
            Session.Clear();

            pg.Response.Cookies["DigiOzPortalAuthUser"].Expires = DateTime.Now.AddDays(-20);
            pg.Response.Redirect("Default.aspx");
        }
    }
}
