示例#1
0
        /// Fetches the Node value from xml file of a specific node
        /// </summary>
        /// <param name="value">Name of the node whose values is to be fetched</param>
        /// <returns>Value of the node</returns>
        public static string GetProperty(string key)
        {
            if (key == null)
            {
                return("");
            }
            String retStr = s_prop.GetProperty(key, "");

            if (retStr == null || retStr.Length == 0)
            {
                return("");
            }
            //
            String value = "";

            if (retStr.Substring(0, 3) == "xyz")
            {
                value = retStr.Substring(3);
            }
            else
            {
                value = SecureEngine.Decrypt(retStr);
            }
            //	log.finer(key + "=" + value);
            if (value == null)
            {
                return("");
            }
            return(value);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpRequest q    = Request;
            string      lang = q.QueryString["lang"];

            lblEmail.InnerText           = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "EMail"));
            lblHeader.InnerText          = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_LoginInfo"));
            lblMobile.InnerText          = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "Mobile"));
            lblName.InnerText            = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "Name"));
            lblPwd.InnerText             = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "Password"));
            confirmpasswordlbl.InnerText = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "NewPasswordConfirm"));
            lblSubHeader.InnerText       = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_subHeader"));
            lblUID.InnerText             = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_UserID"));
            lblurl.InnerText             = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_clickUrl"));
            lblContent.InnerText         = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_LoginPageContent"));
            Button1.Text       = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "Save"));
            sendMail.InnerText = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_UserSaved"));
            usernotSaved       = VAdvantage.Utility.Util.CleanMnemonic(Msg.GetMsg(lang, "VIS_ErrorSavingUser"));
            if (!IsPostBack)
            {
                sendMail.Visible = false;

                string mailID = q.QueryString["mailID"];
                string url    = q.QueryString["URL"];
                if (mailID != "0")
                {
                    email.Value = SecureEngine.Decrypt(mailID);
                }
                parentUrl.InnerText = url;
                parentUrl.HRef      = url;
            }
        }
        /// <summary>`
        /// Validate OTP from Google Authenticator
        /// </summary>
        /// <param name="model"></param>
        /// <returns>true/false</returns>
        public static bool Validate2FAOTP(LoginModel model)
        {
            bool    isValid = false;
            DataSet dsUser  = DB.ExecuteDataset(@"SELECT Value, TokenKey2FA, Created, Is2FAEnabled, AD_User_ID FROM AD_User WHERE AD_User_ID = " + model.Login1Model.AD_User_ID);

            if (dsUser != null && dsUser.Tables[0].Rows.Count > 0)
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                string Token2FAKey         = Util.GetValueOfString(dsUser.Tables[0].Rows[0]["Value"]);
                int    ADUserID            = Util.GetValueOfInt(dsUser.Tables[0].Rows[0]["AD_User_ID"]);
                if (model.Login1Model.TokenKey2FA != null && model.Login1Model.TokenKey2FA != "")
                {
                    Token2FAKey = Token2FAKey.ToString() + ADUserID.ToString() + model.Login1Model.TokenKey2FA;
                }
                else if (Util.GetValueOfString(dsUser.Tables[0].Rows[0]["TokenKey2FA"]) != "")
                {
                    string decKey = Util.GetValueOfString(dsUser.Tables[0].Rows[0]["TokenKey2FA"]);
                    decKey      = SecureEngine.Decrypt(decKey);
                    Token2FAKey = Token2FAKey.ToString() + ADUserID.ToString() + decKey;
                }

                isValid = tfa.ValidateTwoFactorPIN(Token2FAKey, model.Login1Model.OTP2FA);
                if (isValid && Util.GetValueOfString(dsUser.Tables[0].Rows[0]["TokenKey2FA"]).Trim() == "")
                {
                    string encKey   = SecureEngine.Encrypt(model.Login1Model.TokenKey2FA);
                    int    countUpd = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE AD_USER SET TokenKey2FA = '" + encKey + @"' WHERE 
                                    AD_USER_ID = " + model.Login1Model.AD_User_ID));
                }
            }
            return(isValid);
        }
示例#4
0
        /// <summary>
        /// convert server side encrypted value to client side encrypted value
        /// - first decrypt value by server key , and then encrypt by client's key
        /// </summary>
        /// <param name="value">encrypted value(server)</param>
        /// <param name="key">client key</param>
        /// <returns>encrypted value(client)</returns>
        public static string EncryptFromSeverToClient(string value, string key)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }
            string val = value;

            if (SecureEngine.IsEncrypted(value))
            {
                val = SecureEngine.Decrypt(value);
            }
            return(SecureEngineH5.Encrypt(val, key, key));
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Name.Value))
            {
                return;
            }
            HttpRequest q    = Request;
            string      lang = q.QueryString["lang"];

            usernotSaved    = Msg.GetMsg(lang, "VIS_ErrorSavingUser");
            Button1.Enabled = false;
            int AD_Client_ID = 0;
            int AD_Org_ID    = 0;

            int     inviteID = Convert.ToInt32(SecureEngine.Decrypt(q.QueryString["inviteID"]));
            String  sql      = "SELECT * FROM AD_InviteUser WHERE AD_InviteUser_ID=" + inviteID;
            DataSet dsIUser  = DB.ExecuteDataset(sql);

            if (dsIUser != null && dsIUser.Tables[0].Rows.Count > 0)
            {
                AD_Org_ID    = Convert.ToInt32(dsIUser.Tables[0].Rows[0]["AD_Org_ID"]);
                AD_Client_ID = Convert.ToInt32(dsIUser.Tables[0].Rows[0]["AD_Client_ID"]);
            }

            sql = "SELECT AD_Role_ID FROM ad_inviteuser_role WHERE AD_InviteUser_ID= " + inviteID;
            DataSet ds = DB.ExecuteDataset(sql);



            Ctx ctx = new Ctx();

            ctx.SetAD_Client_ID(AD_Client_ID);
            ctx.SetAD_Org_ID(AD_Org_ID);


            MUser user = new MUser(ctx, 0, null);

            user.SetAD_Client_ID(AD_Client_ID);
            user.SetAD_Org_ID(AD_Org_ID);
            user.SetIsLoginUser(true);
            user.SetName(Name.Value);
            user.SetValue(userIDs.Value);
            user.SetEMail(email.Value);
            user.SetPassword(passwords.Value);
            user.SetMobile(mobile.Value);
            if (user.Save())
            {
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MUserRoles uRoles = new MUserRoles(ctx, user.GetAD_User_ID(), Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Role_ID"]), null);
                        uRoles.SetAD_Client_ID(AD_Client_ID);
                        uRoles.SetAD_Org_ID(AD_Org_ID);
                        uRoles.Save();
                    }
                }

                sendMail.Visible = true;
                Name.Value       = "";
                userIDs.Value    = "";
                email.Value      = "";
                passwords.Value  = "";
                mobile.Value     = "";
            }
            else
            {
                Button1.Enabled    = true;
                sendMail.InnerText = usernotSaved;
                sendMail.Visible   = true;
            }
        }
        //public ActionResult Index(string param )
        //{
        //   // FormCollection fc = null;
        //    if (!string.IsNullOrEmpty(param))
        //    {
        //     //   fc = new FormCollection();
        //        TempData["param"] =  param;
        //        RedirectToAction("Index");
        //    }
        //    return Home(null);
        //}

        //[MethodImpl(MethodImplOptions.Synchronized)]
        //[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        /// <summary>
        /// Entry Point of Framework
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public ActionResult Index(FormCollection form)
        {
            if (Request.QueryString.Count > 0)
            {
                // string user = Request.QueryString["U"];
                // string pwd = Request.QueryString["P"];
                // AccountController ac = new AccountController();
                // LoginModel md = new LoginModel();
                // md.Login1Model = new Login1Model();
                // md.Login1Model.UserValue = user;
                // md.Login1Model.Password = pwd;
                //JsonResult jr =  ac.JsonLogin(md, "");
                // ac.SetAuthCookie(md, Response); //AutoLogin if all passed
                // return RedirectToAction("Index");
            }

            //if (!User.Identity.IsAuthenticated)
            //{
            //    // Required to allow javascript redirection through to browser
            //    this.Response.TrySkipIisCustomErrors = true;
            //    this.Response.Status = "401 Unauthorized";
            //    this.Response.StatusCode = 401;
            //    // note that the following line is .NET 4.5 or later only
            //    // otherwise you have to suppress the return URL etc manually!
            //    this.Response.SuppressFormsAuthenticationRedirect = true;
            //    // If we got this far, something failed

            //}


            var url = CloudLogin.IsAllowedToLogin(Request.Url.ToString());

            if (!string.IsNullOrEmpty(url))
            {
                return(RedirectPermanent(url));
            }

            VAdvantage.DataBase.DBConn.SetConnectionString();//Init database conection
            Language.GetLanguages();
            LoginModel model = null;

            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString.Count > 0)     /* if has value */
                {
                    return(RedirectToAction("Index")); /*redirect to same url without querystring*/
                }
                try
                {
                    //var conf = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                    //  SessionStateSection section = (SessionStateSection) conf.GetSection("system.web/sessionState");
                    // int timeout = (int) section.Timeout.TotalMinutes;
                    Session.Timeout = 20; // ideal timout
                }
                catch
                {
                }


                //AccountController a = new AccountController();
                //a.LogOff();
                FormsIdentity ident = User.Identity as FormsIdentity;
                Ctx           ctx   = null;
                if (ident != null)
                {
                    FormsAuthenticationTicket ticket = ident.Ticket;
                    string       loginContextString  = ticket.UserData;// get login context string from Form Ticket
                    LoginContext lCtx = JsonHelper.Deserialize(loginContextString, typeof(LoginContext)) as LoginContext;
                    IDataReader  dr   = null;



                    //create class from string
                    string key = "";
                    if (Session["ctx"] != null)
                    {
                        ctx = Session["ctx"] as Ctx;

                        //Update Old Session
                        MSession session = MSession.Get(ctx, false);
                        if (session != null)
                        {
                            session.Logout();
                        }

                        key = ctx.GetSecureKey();

                        //if (Session.Timeout < 2)
                        //{
                        SessionEventHandler.SessionEnd(ctx);
                        Session.Timeout = 17;
                        //}
                        Session["ctx"] = null;
                    }
                    ctx = new Ctx(lCtx.ctxMap); //cretae new context

                    /* fix for User Value Null value */

                    if (string.IsNullOrEmpty(ctx.GetContext("##AD_User_Value")))
                    {
                        return(new AccountController().LogOff());
                    }

                    if (key != "")
                    {
                        ctx.SetSecureKey(key);
                    }
                    Session["ctx"] = ctx;

                    //get login Language object on server
                    var loginLang = ctx.GetAD_Language();

                    Language l = Language.GetLanguage(ctx.GetAD_Language()); //Language.GetLoginLanguage();
                    l = VAdvantage.Utility.Env.VerifyLanguage(ctx, l);

                    ctx.SetContext(VAdvantage.Utility.Env.LANGUAGE, l.GetAD_Language());
                    ctx.SetContext(VAdvantage.Utility.Env.ISRIGHTTOLEFT, VAdvantage.Utility.Env.IsRightToLeft(loginLang) ? "Y" : "N");
                    new VAdvantage.Login.LoginProcess(ctx).LoadSysConfig();
                    LoginHelper.SetSysConfigInContext(ctx);

                    ViewBag.culture   = ctx.GetAD_Language();
                    ViewBag.direction = ctx.GetIsRightToLeft() ? "rtl" : "ltr";

                    //Change Authentication
                    model                           = new LoginModel();
                    model.Login1Model               = new Login1Model();
                    model.Login2Model               = new Login2Model();
                    model.Login1Model.UserValue     = ctx.GetContext("##AD_User_Value");
                    model.Login1Model.DisplayName   = ctx.GetContext("##AD_User_Name");
                    model.Login1Model.LoginLanguage = ctx.GetAD_Language();

                    model.Login2Model.Role      = ctx.GetAD_Role_ID().ToString();
                    model.Login2Model.Client    = ctx.GetAD_Client_ID().ToString();
                    model.Login2Model.Org       = ctx.GetAD_Org_ID().ToString();
                    model.Login2Model.Warehouse = ctx.GetAD_Warehouse_ID().ToString();


                    var         RoleList      = new List <KeyNamePair>();
                    var         ClientList    = new List <KeyNamePair>();
                    var         OrgList       = new List <KeyNamePair>();
                    var         WareHouseList = new List <KeyNamePair>();
                    string      username      = "";
                    IDataReader drRoles       = LoginHelper.GetRoles(model.Login1Model.UserValue, false, false);
                    int         AD_User_ID    = 0;
                    if (drRoles.Read())
                    {
                        do  //	read all roles
                        {
                            AD_User_ID = Util.GetValueOfInt(drRoles[0].ToString());
                            int         AD_Role_ID = Util.GetValueOfInt(drRoles[1].ToString());
                            String      Name       = drRoles[2].ToString();
                            KeyNamePair p          = new KeyNamePair(AD_Role_ID, Name);
                            RoleList.Add(p);
                            username = Util.GetValueOfString(drRoles["username"].ToString());
                        }while (drRoles.Read());
                    }
                    drRoles.Close();

                    model.Login1Model.AD_User_ID  = AD_User_ID;
                    model.Login1Model.DisplayName = username;

                    //string diableMenu = ctx.GetContext("#DisableMenu");
                    Helpers.MenuHelper mnuHelper = new Helpers.MenuHelper(ctx); // inilitilize menu class

                    bool disableMenu = MRole.GetDefault(ctx).IsDisableMenu();
                    ctx.SetIsBasicDB(mnuHelper.GetIsBasicDB());


                    // If Home page not linked OR home page Linked BUT Menu is not disabled , then show home page.
                    // If Home is linked as well as menu is disabled then don't load Default Home Page Settings
                    if (MRole.GetDefault(ctx).GetHomePage_ID() == 0 || (MRole.GetDefault(ctx).GetHomePage_ID() > 0 && !disableMenu))
                    {
                        HomeModels hm = new HomeModels();
                        objHomeHelp     = new HomeHelper();
                        hm              = objHomeHelp.getLoginUserInfo(ctx, 32, 32);
                        ViewBag.UserPic = hm.UsrImage;
                    }
                    ViewBag.DisplayName = model.Login1Model.DisplayName;

                    if (!disableMenu) // if menu is not disabled, only then load menu.
                    {
                        //get current user info
                        ViewBag.Menu        = mnuHelper.GetMenuTree();    // create tree
                        Session["barNodes"] = ViewBag.Menu.GetBarNodes(); /* add is session to get it in favourite call */

                        ViewBag.TreeHtml = mnuHelper.GetMenuTreeUI(ViewBag.Menu.GetRootNode(), @Url.Content("~/"));
                    }

                    ViewBag.disableMenu = disableMenu;

                    mnuHelper.dispose();

                    //  LoginHelper.GetClients(id)

                    ClientList    = LoginHelper.GetClients(ctx.GetAD_Role_ID());                                          // .Add(new KeyNamePair(ctx.GetAD_Client_ID(), ctx.GetAD_Client_Name()));
                    OrgList       = LoginHelper.GetOrgs(ctx.GetAD_Role_ID(), ctx.GetAD_User_ID(), ctx.GetAD_Client_ID()); // .Add(new KeyNamePair(ctx.GetAD_Org_ID(), ctx.GetAD_Org_Name()));
                    WareHouseList = LoginHelper.GetWarehouse(ctx.GetAD_Org_ID());                                         // .Add(new KeyNamePair(ctx.GetAD_Warehouse_ID(), ctx.GetContext("#M_Warehouse_Name")));


                    ViewBag.RoleList      = RoleList;
                    ViewBag.ClientList    = ClientList;
                    ViewBag.OrgList       = OrgList;
                    ViewBag.WarehouseList = WareHouseList;
                    lock (_lock)    // Locked bundle Object and session Creation to handle concurrent requests.
                    {
                        //Cretae new Sessin
                        MSession sessionNew = MSession.Get(ctx, true, GetVisitorIPAddress(true));


                        var lst = VAdvantage.ModuleBundles.GetStyleBundles(); //Get All Style Bundle
                        foreach (var b in lst)
                        {
                            if (!BundleTable.Bundles.Contains(b))
                            {
                                BundleTable.Bundles.Add(b); //Add in Mvc Bundle Table
                            }
                        }

                        var lstRTLStyle = VAdvantage.ModuleBundles.GetRTLStyleBundles(); //Get All Script Bundle

                        foreach (var b in lstRTLStyle)
                        {
                            if (!BundleTable.Bundles.Contains(b))
                            {
                                BundleTable.Bundles.Add(b); //Add in Mvc Bundlw Table
                            }
                        }

                        var lstScript = VAdvantage.ModuleBundles.GetScriptBundles(); //Get All Script Bundle

                        foreach (var b in lstScript)
                        {
                            if (!BundleTable.Bundles.Contains(b))
                            {
                                BundleTable.Bundles.Add(b); //Add in Mvc Bundlw Table
                            }
                        }

                        ViewBag.LibSuffix   = "";
                        ViewBag.FrameSuffix = "_v1";
                        int libFound = 0;
                        foreach (Bundle b in BundleTable.Bundles)
                        {
                            if (b.Path.Contains("ViennaBase") && b.Path.Contains("_v") && ViewBag.LibSuffix == "")
                            {
                                ViewBag.LibSuffix = Util.GetValueOfInt(ctx.GetContext("#FRONTEND_LIB_VERSION")) > 2
                                                      ? "_v3" : "_v2";
                                libFound++;
                            }

                            if (b.Path.Contains("VIS") && b.Path.Contains("_v"))
                            {
                                ViewBag.FrameSuffix = Util.GetValueOfInt(ctx.GetContext("#FRAMEWORK_VERSION")) > 1
                                                      ? "_v2" : "_v1";
                                libFound++;
                            }
                            if (libFound >= 2)
                            {
                                break;
                            }
                        }
                        //check system setting// set to skipped lib
                    }
                }
            }

            else
            {
                model             = new LoginModel();
                model.Login1Model = new Login1Model();
                if (Request.QueryString.Count > 0) /* if query has values*/
                {
                    try
                    {
                        TempData["user"] = SecureEngine.Decrypt(Request.QueryString["U"]); //get uservalue
                        TempData["pwd"]  = SecureEngine.Decrypt(Request.QueryString["P"]); //get userpwd
                    }
                    catch
                    {
                        TempData.Clear();
                    }
                    return(RedirectToAction("Index")); // redirect to same url to remove cookie
                }

                if (TempData.ContainsKey("user"))
                {
                    model.Login1Model.UserValue = TempData["user"].ToString() + "^Y^" + TempData["pwd"].ToString();
                    // model.Login1Model.Password = TempData.Peek("pwd").ToString();
                }

                model.Login1Model.LoginLanguage = "en_US";
                model.Login2Model = new Login2Model();

                ViewBag.RoleList      = new List <KeyNamePair>();
                ViewBag.OrgList       = new List <KeyNamePair>();
                ViewBag.WarehouseList = new List <KeyNamePair>();
                ViewBag.ClientList    = new List <KeyNamePair>();

                ViewBag.Languages = Language.GetLanguages();

                Session["ctx"]    = null;
                ViewBag.direction = "ltr";

                ViewBag.LibSuffix = "";
                foreach (Bundle b in BundleTable.Bundles)
                {
                    if (b.Path.Contains("ViennaBase") && b.Path.Contains("_v"))
                    {
                        ViewBag.LibSuffix = "_v2";
                        break;
                    }
                }
            }
            return(View(model));
        }
        }       //	prepare

        /**
         *  Process
         *	@return info
         *	@throws Exception
         */
        protected override String DoIt()// throws Exception
        {
            log.Info("AD_Column_ID=" + p_AD_Column_ID
                     + ", IsEncrypted=" + p_IsEncrypted
                     + ", ChangeSetting=" + p_ChangeSetting
                     + ", MaxLength=" + p_MaxLength);
            MColumn column = new MColumn(GetCtx(), p_AD_Column_ID, Get_Trx());

            if (column.Get_ID() == 0 || column.Get_ID() != p_AD_Column_ID)
            {
                throw new Exception("@NotFound@ @AD_Column_ID@ - " + p_AD_Column_ID);
            }
            //
            String columnName = column.GetColumnName();
            int    dt         = column.GetAD_Reference_ID();

            //	Can it be enabled?
            if (column.IsKey() ||
                column.IsParent() ||
                column.IsStandardColumn() ||
                column.IsVirtualColumn() ||
                column.IsIdentifier() ||
                column.IsTranslated() ||
                DisplayType.IsLookup(dt) ||
                DisplayType.IsLOB(dt) ||
                "DocumentNo".Equals(column.GetColumnName(), StringComparison.OrdinalIgnoreCase) ||
                "Value".Equals(column.GetColumnName(), StringComparison.OrdinalIgnoreCase) ||
                "Name".Equals(column.GetColumnName(), StringComparison.OrdinalIgnoreCase))
            {
                if (column.IsEncrypted())
                {
                    column.SetIsEncrypted(false);
                    column.Save(Get_Trx());
                }
                return(columnName + ": cannot be encrypted");
            }

            //	Start
            AddLog(0, null, null, "Encryption Class = " + SecureEngine.GetClassName());
            bool error = false;

            //	Test Value
            if (p_TestValue != null && p_TestValue.Length > 0)
            {
                String encString = SecureEngine.Encrypt(p_TestValue);
                AddLog(0, null, null, "Encrypted Test Value=" + encString);
                String clearString = SecureEngine.Decrypt(encString);
                if (p_TestValue.Equals(clearString))
                {
                    AddLog(0, null, null, "Decrypted=" + clearString
                           + " (same as test value)");
                }
                else
                {
                    AddLog(0, null, null, "Decrypted=" + clearString
                           + " (NOT the same as test value - check algorithm)");
                    error = true;
                }
                int encLength = encString.Length;
                AddLog(0, null, null, "Test Length=" + p_TestValue.Length + " -> " + encLength);
                if (encLength <= column.GetFieldLength())
                {
                    AddLog(0, null, null, "Encrypted Length (" + encLength
                           + ") fits into field (" + column.GetFieldLength() + ")");
                }
                else
                {
                    AddLog(0, null, null, "Encrypted Length (" + encLength
                           + ") does NOT fit into field (" + column.GetFieldLength() + ") - resize field");
                    error = true;
                }
            }

            //	Length Test
            if (p_MaxLength != 0)
            {
                String testClear = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                while (testClear.Length < p_MaxLength)
                {
                    testClear += testClear;
                }
                testClear = testClear.Substring(0, p_MaxLength);
                log.Config("Test=" + testClear + " (" + p_MaxLength + ")");
                //
                String encString = SecureEngine.Encrypt(testClear);
                int    encLength = encString.Length;
                AddLog(0, null, null, "Test Max Length=" + testClear.Length + " -> " + encLength);
                if (encLength <= column.GetFieldLength())
                {
                    AddLog(0, null, null, "Encrypted Max Length (" + encLength
                           + ") fits into field (" + column.GetFieldLength() + ")");
                }
                else
                {
                    AddLog(0, null, null, "Encrypted Max Length (" + encLength
                           + ") does NOT fit into field (" + column.GetFieldLength() + ") - resize field");
                    error = true;
                }
            }

            if (p_IsEncrypted != column.IsEncrypted())
            {
                if (error || !p_ChangeSetting)
                {
                    AddLog(0, null, null, "Encryption NOT changed - Encryption=" + column.IsEncrypted());
                }
                else
                {
                    column.SetIsEncrypted(p_IsEncrypted);
                    if (column.Save(Get_Trx()))
                    {
                        AddLog(0, null, null, "Encryption CHANGED - Encryption=" + column.IsEncrypted());
                    }
                    else
                    {
                        AddLog(0, null, null, "Save Error");
                    }
                }
            }


            if (p_IsEncrypted == column.IsEncrypted() && !error)      // Done By Karan on 10-nov-2016, to encrypt/decrypt passwords according to settings.
            {
                //object colID = DB.ExecuteScalar("SELECT AD_Column_ID FROM AD_Column WHERE AD_Table_ID =(SELECT AD_Table_ID From AD_Table WHERE TableName='AD_User') AND ColumnName='Password'", null, Get_Trx());



                // if (colID != null && colID != DBNull.Value && Convert.ToInt32(colID) == column.GetAD_Column_ID())
                //{

                string tableName = MTable.GetTableName(GetCtx(), column.GetAD_Table_ID());

                DataSet ds = DB.ExecuteDataset("SELECT " + column.GetColumnName() + "," + tableName
                                               + "_ID FROM " + tableName, null, Get_Trx());
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    if (p_IsEncrypted)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i][column.GetColumnName()] != null && ds.Tables[0].Rows[i][column.GetColumnName()] != DBNull.Value &&
                                !SecureEngine.IsEncrypted(ds.Tables[0].Rows[i][column.GetColumnName()].ToString()))
                            {
                                //MUser user = new MUser(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i][MTable.GetTableName(GetCtx(), column.GetAD_Table_ID()) + "_ID"]), Get_Trx());
                                //user.SetPassword(SecureEngine.Encrypt(ds.Tables[0].Rows[i][column.GetColumnName()].ToString()));

                                int encLength = SecureEngine.Encrypt(ds.Tables[0].Rows[i][column.GetColumnName()].ToString()).Length;

                                if (encLength <= column.GetFieldLength())
                                {
                                    //PO tab = MTable.GetPO(GetCtx(), tableName,
                                    //    Util.GetValueOfInt(ds.Tables[0].Rows[i][tableName + "_ID"]), Get_Trx());

                                    //tab.Set_Value(column.GetColumnName(), (SecureEngine.Encrypt(ds.Tables[0].Rows[i][column.GetColumnName()].ToString())));
                                    //if (!tab.Save(Get_Trx()))
                                    //{
                                    //    Rollback();
                                    //    return "Encryption=" + false;
                                    //}
                                    string p_NewPassword = SecureEngine.Encrypt(ds.Tables[0].Rows[i][column.GetColumnName()].ToString());
                                    String sql           = "UPDATE " + tableName + " SET Updated=SYSDATE, UpdatedBy=" + GetAD_User_ID();
                                    if (!string.IsNullOrEmpty(p_NewPassword))
                                    {
                                        sql += ", " + column.GetColumnName() + "=" + GlobalVariable.TO_STRING(p_NewPassword);
                                    }
                                    sql += " WHERE " + tableName + "_ID=" + Util.GetValueOfInt(ds.Tables[0].Rows[i][tableName + "_ID"]);
                                    int iRes = DB.ExecuteQuery(sql, null, Get_Trx());
                                    if (iRes <= 0)
                                    {
                                        Rollback();
                                        return("Encryption=" + false);
                                    }
                                }
                                else
                                {
                                    Rollback();
                                    return("After Encryption some values may exceed the value of column length. Please exceed column Length.");
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i][column.GetColumnName()] != null && ds.Tables[0].Rows[i][column.GetColumnName()] != DBNull.Value &&
                                SecureEngine.IsEncrypted(ds.Tables[0].Rows[i][column.GetColumnName()].ToString()))
                            {
                                // MUser user = new MUser(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i][MTable.GetTableName(GetCtx(), column.GetAD_Table_ID())+"_ID"]), Get_Trx());

                                //PO tab = MTable.GetPO(GetCtx(), tableName,
                                //   Util.GetValueOfInt(ds.Tables[0].Rows[i][tableName + "_ID"]), Get_Trx());

                                //tab.Set_Value(column.GetColumnName(), (SecureEngine.Decrypt(ds.Tables[0].Rows[i][column.GetColumnName()].ToString())));
                                //if (!tab.Save(Get_Trx()))
                                //{
                                //    Rollback();
                                //    return "Encryption=" + false;
                                //}

                                string p_NewPassword = SecureEngine.Decrypt(ds.Tables[0].Rows[i][column.GetColumnName()].ToString());
                                String sql           = "UPDATE " + tableName + "  SET Updated=SYSDATE, UpdatedBy=" + GetAD_User_ID();
                                if (!string.IsNullOrEmpty(p_NewPassword))
                                {
                                    sql += ", " + column.GetColumnName() + "=" + GlobalVariable.TO_STRING(p_NewPassword);
                                }
                                sql += " WHERE " + tableName + "_ID  =" + Util.GetValueOfInt(ds.Tables[0].Rows[i][tableName + "_ID"]);
                                int iRes = DB.ExecuteQuery(sql, null, Get_Trx());
                                if (iRes <= 0)
                                {
                                    Rollback();
                                    return("Encryption=" + false);
                                }
                            }
                        }
                    }
                }
                //}
            }
            return("Encryption=" + column.IsEncrypted());
        }
        /// <summary>
        /// return is credential provide by user is right or not
        /// </summary>
        /// <param name="model">login model class</param>
        /// <param name="roles">out roles , has role list of user</param>
        /// <param name="ctx" ></param>
        /// <returns>true if athenicated</returns>
        public static bool Login(LoginModel model, out List <KeyNamePair> roles)
        {
            // loginModel = null;
            //bool isMatch = false;
            roles = null;
            SecureEngine.Encrypt("t"); //Initialize

            //	Cannot use encrypted password
            //if ())
            //{
            //    //log.warning("Cannot use Encrypted Password");
            //    return false;
            //}
            //	Authentification
            bool    authenticated = false;
            bool    isLDAP        = false;
            MSystem system        = MSystem.Get(new Ctx());
            string  output        = "";

            if (system != null && system.IsLDAP())
            {
                authenticated = system.IsLDAP(model.Login1Model.UserValue, model.Login1Model.Password, out output);

                isLDAP = true;
            }
            //Save Failed Login Count and Password validty in cache
            GetSysConfigForlogin();


            int fCount            = Util.GetValueOfInt(cache[Common.Failed_Login_Count_Key]);
            int passwordValidUpto = Util.GetValueOfInt(cache[Common.Password_Valid_Upto_Key]);

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@username", model.Login1Model.UserValue);



            DataSet dsUserInfo = DB.ExecuteDataset("SELECT AD_User_ID, Value, Password,IsLoginUser,FailedLoginCount, IsOnlyLDAP FROM AD_User WHERE Value=@username", param);

            if (dsUserInfo != null && dsUserInfo.Tables[0].Rows.Count > 0)
            {
                // skipped Login user check for SuperUser (100)
                if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue) &&
                    !dsUserInfo.Tables[0].Rows[0]["IsLoginUser"].ToString().Equals("Y"))
                {
                    throw new Exception("NotLoginUser");
                }

                // output length will be greater than 0 if there is any error while ldap auth.
                //output check is applied to becuase after first login, when user redriect to home page, this functioexecutes again and password is null on that time.
                // so ldap reject auth , but user is actually authenticated. so to avoid error, this check is used.
                if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue) && dsUserInfo.Tables[0].Rows[0]["IsOnlyLDAP"].ToString().Equals("Y") &&
                    isLDAP && !authenticated)
                {
                    throw new Exception(output);
                }
            }
            else
            {
                throw new Exception("UserNotFound");
            }

            //if authenticated by LDAP or password is null(Means request from home page)
            if (!authenticated && model.Login1Model.Password != null)
            {
                string sqlEnc      = "SELECT isencrypted FROM ad_column WHERE ad_table_id=(SELECT ad_table_id FROM ad_table WHERE tablename='AD_User') AND columnname='Password'";
                char   isEncrypted = Convert.ToChar(DB.ExecuteScalar(sqlEnc));
                string originalpwd = model.Login1Model.Password;
                if (isEncrypted == 'Y' && model.Login1Model.Password != null)
                {
                    model.Login1Model.Password = SecureEngine.Encrypt(model.Login1Model.Password);
                }

                //  DataSet dsUserInfo = DB.ExecuteDataset("SELECT AD_User_ID, Value, Password,IsLoginUser,FailedLoginCount FROM AD_User WHERE Value=@username", param);
                if (dsUserInfo != null && dsUserInfo.Tables[0].Rows.Count > 0)
                {
                    //if username or password is not matching
                    if ((!dsUserInfo.Tables[0].Rows[0]["Value"].Equals(model.Login1Model.UserValue) ||
                         !dsUserInfo.Tables[0].Rows[0]["Password"].Equals(model.Login1Model.Password)) ||
                        (originalpwd != null && SecureEngine.IsEncrypted(originalpwd)))
                    {
                        //if current user is Not superuser, then increase failed login count
                        if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue))
                        {
                            param[0] = new SqlParameter("@username", model.Login1Model.UserValue);
                            int count = DB.ExecuteQuery("UPDATE AD_User Set FAILEDLOGINCOUNT=FAILEDLOGINCOUNT+1 WHERE Value=@username ", param);

                            if (fCount > 0 && fCount <= Util.GetValueOfInt(dsUserInfo.Tables[0].Rows[0]["FailedLoginCount"]) + 1)
                            {
                                throw new Exception("MaxFailedLoginAttempts");
                            }
                        }

                        throw new Exception("UserPwdError");
                    }
                    else// if username and password matched, then check if account is locked or not
                    {
                        if (fCount > 0 && fCount <= Util.GetValueOfInt(dsUserInfo.Tables[0].Rows[0]["FailedLoginCount"]))
                        {
                            throw new Exception("MaxFailedLoginAttempts");
                        }
                    }
                }
            }

            IDataReader dr = GetRoles(model.Login1Model.UserValue, authenticated, isLDAP);

            if (!dr.Read())             //	no record found, then return msaage that role not found.
            {
                dr.Close();
                throw new Exception("RoleNotDefined");
            }

            // if user logged in successfully, then set failed login count to 0
            DB.ExecuteQuery("UPDATE AD_User SET FailedLoginCount=0 WHERE Value=@username", param);

            int AD_User_ID = Util.GetValueOfInt(dr[0].ToString()); //User Id

            if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue))
            {
                String Token2FAKey = Util.GetValueOfString(dr["TokenKey2FA"]);
                bool   enable2FA   = Util.GetValueOfString(dr["Is2FAEnabled"]) == "Y";
                if (enable2FA)
                {
                    model.Login1Model.QRFirstTime = false;
                    TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                    SetupCode setupInfo        = null;
                    string    userSKey         = Util.GetValueOfString(dr["Value"]);
                    int       ADUserID         = Util.GetValueOfInt(dr["AD_User_ID"]);
                    // if token key don't exist for user, then create new
                    if (Token2FAKey.Trim() == "")
                    {
                        model.Login1Model.QRFirstTime = true;
                        Token2FAKey = userSKey;
                        // get Random Number
                        model.Login1Model.TokenKey2FA = GetRndNum();
                        // create Token key based on Value, UserID and Random Number
                        Token2FAKey = userSKey + ADUserID.ToString() + model.Login1Model.TokenKey2FA;
                    }
                    else
                    {
                        // Decrypt token key saved in database
                        string decKey = SecureEngine.Decrypt(Token2FAKey);
                        Token2FAKey = userSKey + ADUserID.ToString() + decKey;
                    }

                    string url = Util.GetValueOfString(HttpContext.Current.Request.Url.AbsoluteUri).Replace("VIS/Account/JsonLogin", "").Replace("https://", "").Replace("http://", "");

                    setupInfo = tfa.GenerateSetupCode("VA ", url + " " + userSKey, Token2FAKey, 150, 150);
                    model.Login1Model.QRCodeURL = setupInfo.QrCodeSetupImageUrl;
                }

                model.Login1Model.Is2FAEnabled = enable2FA;
            }


            if (!authenticated)
            {
                DateTime?pwdExpireDate = Util.GetValueOfDateTime(dr["PasswordExpireOn"]);
                if (pwdExpireDate == null || (passwordValidUpto > 0 && (DateTime.Compare(DateTime.Now, Convert.ToDateTime(pwdExpireDate)) > 0)))
                {
                    model.Login1Model.ResetPwd = true;
                    //if (SecureEngine.IsEncrypted(model.Login1Model.Password))
                    //    model.Login1Model.Password = SecureEngine.Decrypt(model.Login1Model.Password);
                }
            }

            roles = new List <KeyNamePair>(); //roles

            List <int> usersRoles = new List <int>();
            string     username   = "";

            do  //	read all roles
            {
                AD_User_ID = Util.GetValueOfInt(dr[0].ToString());
                int AD_Role_ID = Util.GetValueOfInt(dr[1].ToString());

                String      Name = dr[2].ToString();
                KeyNamePair p    = new KeyNamePair(AD_Role_ID, Name);
                username = Util.GetValueOfString(dr["username"].ToString());
                roles.Add(p);

                usersRoles.Add(AD_Role_ID);
            }while (dr.Read());

            dr.Close();
            model.Login1Model.AD_User_ID  = AD_User_ID;
            model.Login1Model.DisplayName = username;

            IDataReader drLogin = null;

            if (model.Login2Model == null)
            {
                try
                {
                    //* Change sub query into ineer join */

                    drLogin = DB.ExecuteReader(" SELECT l.AD_Role_ID," +
                                               " (SELECT r.Name FROM AD_ROLE r WHERE r.AD_Role_ID=l.AD_ROLE_ID) as RoleName," +

                                               " l.AD_Org_ID," +
                                               " (SELECT o.Name FROM AD_Org o WHERE o.AD_Org_ID=l.AD_Org_ID) as OrgName," +
                                               " l.AD_Client_ID," +
                                               " (SELECT c.Name FROM AD_Client c WHERE c.AD_Client_ID=l.AD_Client_ID) as ClientName," +
                                               " l.M_Warehouse_ID," +
                                               " (SELECT m.Name FROM M_Warehouse m WHERE m.M_Warehouse_Id = l.M_Warehouse_ID) as WarehouseName" +
                                               " FROM AD_LoginSetting l WHERE l.IsActive = 'Y' AND l.AD_User_ID=" + AD_User_ID);
                    if (drLogin.Read())
                    {
                        bool deleteRecord = false;

                        //Delete Login Setting
                        if (deleteRecord)
                        {
                            DB.ExecuteQuery("DELETE FROM AD_LoginSetting WHERE AD_User_ID = " + AD_User_ID);
                        }
                        else
                        {
                            model.Login2Model               = new Login2Model();
                            model.Login2Model.Role          = drLogin[0].ToString();
                            model.Login2Model.RoleName      = drLogin[1].ToString();
                            model.Login2Model.Org           = drLogin[2].ToString();
                            model.Login2Model.OrgName       = drLogin[3].ToString();
                            model.Login2Model.Client        = drLogin[4].ToString();
                            model.Login2Model.ClientName    = drLogin[5].ToString();
                            model.Login2Model.Warehouse     = drLogin[6].ToString();
                            model.Login2Model.WarehouseName = drLogin[7].ToString();
                            model.Login2Model.Date          = System.DateTime.Now.Date;
                        }
                    }
                    drLogin.Close();
                }
                catch
                {
                    if (drLogin != null)
                    {
                        drLogin.Close();
                    }
                }
            }
            return(true);
        }