/// <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);
        }
Пример #2
0
        }       //	SaveProperties

        /// <summary>
        /// Set Property
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        public static void SetProperty(string key, string value)
        {
            if (s_prop == null)
            {
                s_prop = new VAdvantage.Utility.Properties();
            }
            if (key.Equals(P_WARNING))
            {
                s_prop.SetProperty(key, value);
            }
            else if (!IsClient())
            {
                s_prop.SetProperty(key, SecureEngineUtility.Secure.CLEARVALUE_START + value + SecureEngineUtility.Secure.CLEARVALUE_END);
            }
            else
            {
                if (value == null)
                {
                    s_prop.SetProperty(key, "");
                }
                else
                {
                    String eValue = SecureEngine.Encrypt(value);
                    if (eValue == null)
                    {
                        s_prop.SetProperty(key, "");
                    }
                    else
                    {
                        s_prop.SetProperty(key, eValue);
                    }
                }
            }
        }
        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;
            }
        }
Пример #4
0
        /// <summary>
        ///  If validity is unknown but context  available, then get from context
        ///  if validity and context, both are unknown, the go with static values
        ///  Otherwise supply password validity
        /// </summary>
        /// <param name="newPwd"></param>
        /// <param name="AD_User_ID"></param>
        /// <param name="UpdatedBy"></param>
        /// <param name="passwordValidity"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static bool UpdatePasswordAndValidity(string newPwd, int AD_User_ID, int UpdatedBy, int passwordValidity = -1, Ctx ctx = null)
        {
            //If validity is unknow but context  available, then get from context
            if (passwordValidity == -1 && ctx != null)
            {
                passwordValidity = ctx.GetContextAsInt("#" + Common.Password_Valid_Upto_Key);
            }

            else if (passwordValidity == -1 && ctx == null)// if validity and context, both are unknown, the go with static values
            {
                passwordValidity = GetPassword_Valid_Upto;
            }
            //ELSE
            // Password validity is supllied.
            //


            //Check if User's pwd is to be encrypted or not
            if (DB.ExecuteScalar("SELECT IsEncrypted from AD_Column WHERE AD_Column_ID=" + 417).ToString().Equals("Y"))
            {
                newPwd = SecureEngine.Encrypt(newPwd);
            }

            string newpwdExpireDate = GlobalVariable.TO_DATE(DateTime.Now.AddMonths(passwordValidity), true);

            string sql   = "UPDATE AD_User set Updated=Sysdate,UpdatedBy=" + UpdatedBy + ",PasswordExpireOn=" + newpwdExpireDate + ",password='******' WHERE AD_User_ID=" + AD_User_ID;
            int    count = DB.ExecuteQuery(sql);

            if (count > 0)
            {
                return(true);
            }
            return(false);
        }
Пример #5
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);
        }
        /// <summary>
        /// encrypt Clent side encrytion to Server Side Encryption
        /// - first decrypt client side encrypted by client key , then encrypt that value by server key;
        /// </summary>
        /// <param name="value">encrypted value(client)</param>
        /// <param name="key">client key</param>
        /// <returns>encrypted value (server side)</returns>
        public static string EncryptFromClientToServer(string value, string key)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }
            string val = SecureEngineH5.Decrypt(value, key, key);

            return(SecureEngine.Encrypt(val));
        }
Пример #7
0
        public static string IsAllowedToLogin(string url)
        {
            string retUrl = "";

            ModelLibrary.CloudService.ServiceSoapClient cloud = null;

            try
            {
                cloud = VAdvantage.Classes.ServerEndPoint.GetCloudClient();

                if (cloud == null || cloud.ToString() == "")
                {
                    //Response.Redirect("http://demo.viennaadvantage.com",true);
                    retUrl = GenerateUrl(url);
                    return(retUrl);
                }
            }
            catch
            {
            }
            //string result = "";
            try
            {
                //System.Net.ServicePointManager.Expect100Continue = false;
                try
                {
                    System.Net.ServicePointManager.Expect100Continue = false;
                    retUrl = cloud.isAllowedToContinue(url, SecureEngine.Encrypt(System.Web.Configuration.WebConfigurationManager.AppSettings["accesskey"].ToString()));
                }
                catch
                {
                }
                cloud.Close();
                try
                {
                    if (retUrl != "True")
                    {
                        return(retUrl);
                    }
                    else
                    {
                        retUrl = GenerateUrl(url);
                    }
                }
                catch
                {
                }
            }
            catch
            {
                return(retUrl);
            }
            return(retUrl);
        }
        //public static CloudSchedularService.CloudSchedularServiceSoapClient GetRemoteServerClient(string RemoteServerURL)
        //{
        //    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
        //    {
        //        CloseTimeout = new TimeSpan(00, 20, 00),
        //        SendTimeout = new TimeSpan(00, 20, 00),
        //        OpenTimeout = new TimeSpan(00, 20, 00),
        //        ReceiveTimeout = new TimeSpan(00, 20, 00),
        //        MaxReceivedMessageSize = int.MaxValue,
        //        MaxBufferSize = int.MaxValue
        //    };

        //    if (RemoteServerURL.IndexOf("https://", StringComparison.OrdinalIgnoreCase) != -1)
        //    {
        //        binding.Security.Mode = BasicHttpSecurityMode.Transport;

        //    }

        //    return new CloudSchedularService.CloudSchedularServiceSoapClient(binding, new EndpointAddress(RemoteServerURL));

        //}


        //public static CloudService.ServiceSoapClient GetOnLineHelpClient()
        //{
        //    object key = System.Configuration.ConfigurationSettings.AppSettings["OnlineHelpURL"];
        //    if (key != null && key.ToString() !="")
        //    {
        //        string url = key.ToString() + "Service.asmx";

        //        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
        //        {
        //            CloseTimeout = new TimeSpan(00, 10, 00),
        //            SendTimeout = new TimeSpan(00, 10, 00),
        //            OpenTimeout = new TimeSpan(00, 10, 00),
        //            ReceiveTimeout = new TimeSpan(00, 10, 00),
        //            MaxReceivedMessageSize = int.MaxValue,
        //            MaxBufferSize = int.MaxValue,
        //            ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
        //            {
        //              MaxArrayLength = int.MaxValue,
        //              MaxStringContentLength = int.MaxValue,
        //              MaxDepth = int.MaxValue,
        //              MaxBytesPerRead = int.MaxValue,
        //              MaxNameTableCharCount= int.MaxValue
        //            }
        //        };
        //        return new CloudService.ServiceSoapClient(binding, new EndpointAddress(url));
        //    }
        //    return null;

        //}

        //public static SpeechService.SpeechServiceClient GetSpeechClient()
        //{
        //    object key = System.Configuration.ConfigurationSettings.AppSettings["SpeechServicehURL"];
        //    if (key != null && key.ToString() != "")
        //    {
        //        string url = key.ToString();

        //        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None)
        //        {
        //            CloseTimeout = new TimeSpan(00, 10, 00),
        //            SendTimeout = new TimeSpan(00, 10, 00),
        //            OpenTimeout = new TimeSpan(00, 10, 00),
        //            ReceiveTimeout = new TimeSpan(00, 10, 00),
        //            MaxReceivedMessageSize = int.MaxValue,
        //            MaxBufferSize = int.MaxValue,
        //            ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxArrayLength = int.MaxValue, MaxStringContentLength = int.MaxValue, MaxDepth = int.MaxValue, MaxBytesPerRead = int.MaxValue }
        //        };
        //        return new SpeechService.SpeechServiceClient(binding, new EndpointAddress(url));
        //    }
        //    return null;
        //}

        /// <summary>
        /// Get Access key
        /// </summary>
        /// <returns>path</returns>
        public static string GetAccesskey()
        {
            string url = "";

            try
            {
                url = SecureEngine.Encrypt(System.Configuration.ConfigurationManager.AppSettings["accesskey"].ToString());
            }
            catch { }
            return(url);
        }
Пример #9
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));
        }
Пример #10
0
        }   //  setProperty

        /// <summary>
        /// Load property and set to default, if not existing
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="defaultValue">Default value</param>
        /// <returns>Property</returns>
        private static String CheckProperty(String key, String defaultValue)
        {
            String result = null;

            if (key.Equals(P_WARNING))
            {
                result = defaultValue;
            }
            else if (!IsClient())
            {
                result = s_prop.GetProperty(key, SecureEngineUtility.Secure.CLEARVALUE_START + defaultValue + SecureEngineUtility.Secure.CLEARVALUE_END);
            }
            else
            {
                result = s_prop.GetProperty(key, SecureEngine.Encrypt(defaultValue));
            }
            s_prop.SetProperty(key, result);
            return(result);
        }       //	checkProperty
Пример #11
0
        public JavaScriptResult Application()
        {
            //var s = Codec.DecryptStringAES();
            StringBuilder sb = new StringBuilder();

            Ctx ctx = Session["ctx"] as Ctx;

            if (ctx.GetSecureKey() == "")
            {
                ctx.SetSecureKey(SecureEngineBridge.GetRandomKey());
            }

            //  ctx.SetApplicationUrl(@Url.Content("~/"));
            ctx.SetIsSSL(Request.Url.Scheme == Uri.UriSchemeHttps);

            //lakhwinder
            string fullUrl = Request.Url.AbsoluteUri.Remove(Request.Url.AbsoluteUri.LastIndexOf('/'));

            //fullUrl = fullUrl.Remove(fullUrl.LastIndexOf('/'));
            //fullUrl = fullUrl.Remove(fullUrl.LastIndexOf('/'));
            fullUrl = fullUrl.Remove(fullUrl.IndexOf("VIS/Resource"));
            ctx.SetApplicationUrl(fullUrl);

            SecureEngine.Encrypt("a");

            CCache <string, string> msgs = Msg.Get().GetMsgMap(ctx.GetAD_Language());

            sb.Append("; var VIS = {");
            sb.Append("Application: {contextUrl:'").Append(@Url.Content("~/")).Append("',").Append(" contextFullUrl:'").Append(fullUrl).Append("',")
            .Append("isMobile:").Append(Request.Browser.IsMobileDevice ? "1" : "0")
            .Append(", isRTL:").Append(ctx.GetIsRightToLeft() ? "1" : "0")
            .Append(", isBasicDB:").Append(ctx.GetIsBasicDB() ? "1" : "0")
            .Append(", isSSL:").Append((Request.Url.Scheme != Uri.UriSchemeHttps ? "0" :"1"))           //TODO
            .Append("},");

            sb.Append("I18N: { }, context: { }");
            sb.Append("};");

            sb.Append("VIS.Consts={");
            /* Table */
            sb.Append("'ACCESSLEVEL_Organization' : '1','ACCESSLEVEL_ClientOnly' : '2','ACCESSLEVEL_ClientPlusOrganization' : '3' ,'ACCESSLEVEL_SystemOnly' : '4'");
            sb.Append(", 'ACCESSLEVEL_SystemPlusClient' : '6','ACCESSLEVEL_All' : '7'");
            sb.Append(", 'ACCESSTYPERULE_Accessing' : 'A', 'ACCESSTYPERULE_Exporting' : 'E' , 'ACCESSTYPERULE_Reporting' : 'R'");
            sb.Append("};");

            /* USER */
            sb.Append(" VIS.MUser = {");
            sb.Append("'isAdministrator':'" + MUser.Get(ctx).IsAdministrator() + "', 'isUserEmployee':'" + MUser.GetIsEmployee(ctx, ctx.GetAD_User_ID()) + "' }; ");

            /* ROLE */
            sb.Append(" VIS.MRole =  {");
            sb.Append(" 'vo' : " + Newtonsoft.Json.JsonConvert.SerializeObject(VIS.Helpers.RoleHelper.GetRole(VAdvantage.Model.MRole.GetDefault(ctx, false))) + " , ");
            sb.Append(" 'SQL_RW' : true, 'SQL_RO' : false, 'SQL_FULLYQUALIFIED' : true, 'SQL_NOTQUALIFIED' : false,'SUPERUSER_USER_ID' : 100, 'SYSTEM_USER_ID' : 0 ");
            sb.Append(", 'PREFERENCETYPE_Client':'C', 'PREFERENCETYPE_None':'N', 'PREFERENCETYPE_Organization':'O', 'PREFERENCETYPE_User':'******'");

            sb.Append(", columnSynonym : { 'AD_User_ID': 'SalesRep_ID','C_ElementValue_ID':'Account_ID'}");
            sb.Append("};");

            /* CTX */
            SetLoginContext(ctx);
            sb.Append(" VIS.context.ctx = ").Append(Newtonsoft.Json.JsonConvert.SerializeObject(ctx.GetMap())).Append("; ");

            /* Message */
            sb.Append(" VIS.I18N.labels = { ");
            if (msgs != null)
            {
                int total = msgs.Keys.Count;
                foreach (var key in msgs.Keys)
                {
                    --total;
                    //if (key.Contains('\n') || key.Contains('\'')
                    //   || key.Contains('\"') || key.StartsWith("SC_") || key.Contains('\r'))
                    //{
                    //    continue;
                    //}
                    //if (msgs.Get(key).ToString().Contains('\n') || msgs.Get(key).ToString().Contains('\'')
                    //    || msgs.Get(key).ToString().Contains('\"') || msgs.Get(key).ToString().Contains('\r'))
                    //{
                    //    continue;
                    //}
                    string msg = (string)msgs.Get(key) ?? "";
                    msg = msg.Replace("\n", " ").Replace("\r", " ").Replace("\"", "'");

                    if (total == 0)
                    {
                        sb.Append("\"").Append(key).Append("\": ").Append("\"").Append(msg).Append("\"");
                    }
                    else
                    {
                        sb.Append("\"").Append(key).Append("\": ").Append("\"").Append(msg).Append("\", ");
                    }
                }
            }
            sb.Append("};");
            // sb.Append(" console.log(VIS.I18N.labels)");
            //return View();
            //System.Web.Optimization.JsMinify d = new System.Web.Optimization.JsMinify();
            //d.Process(


            //Update Login Time

            var r = new ResourceManager(fullUrl, ctx.GetAD_Client_ID());

            r.RunAsync();
            r = null;

            return(JavaScript(sb.ToString()));
        }
        protected override string DoIt()
        {
            VLogger log = VLogger.GetVLogger(this.GetType().FullName);

            log.Log(Level.SEVERE, "UserPassword Change Log=>" + Convert.ToString(p_AD_User_ID));
            if (p_AD_User_ID == -1)
            {
                p_AD_User_ID = GetAD_User_ID();
            }

            MUser user    = MUser.Get(GetCtx(), p_AD_User_ID);
            MUser current = MUser.Get(GetCtx(), GetAD_User_ID());


            if (!current.IsAdministrator() && p_AD_User_ID != GetAD_User_ID() && user.HasRole())
            {
                throw new ArgumentException("@UserCannotUpdate@");
            }

            // SuperUser and System passwords can only be updated by themselves
            if (user.IsSystemAdministrator() && p_AD_User_ID != GetAD_User_ID())
            {
                throw new ArgumentException("@UserCannotUpdate@");
            }

            log.Log(Level.SEVERE, "UserPassword Change Log Step Check for valid user=>" + Convert.ToString(p_AD_User_ID));
            if (string.IsNullOrEmpty(p_CurrentPassword))
            {
                if (string.IsNullOrEmpty(p_OldPassword))
                {
                    throw new ArgumentException("@OldPasswordMandatory@");
                }
                else if (!p_OldPassword.Equals(user.GetPassword()))
                {
                    if (!SecureEngine.Encrypt(p_OldPassword).Equals(user.GetPassword()))
                    {
                        throw new ArgumentException("@OldPasswordNoMatch@");
                    }
                }
            }

            else if (!p_CurrentPassword.Equals(current.GetPassword()))
            {
                throw new ArgumentException("@OldPasswordNoMatch@");
            }
            log.Log(Level.SEVERE, "UserPassword Change Log Step Password Change=>" + Convert.ToString(p_AD_User_ID));
            String originalPwd = p_NewPassword;

            String sql = "UPDATE AD_User SET Updated=SYSDATE, UpdatedBy=" + GetAD_User_ID();

            if (!string.IsNullOrEmpty(p_NewPassword))
            {
                MColumn column = MColumn.Get(GetCtx(), 417); // Password Column
                if (column.IsEncrypted())
                {
                    p_NewPassword = SecureEngine.Encrypt(p_NewPassword);
                }
                sql += ", Password="******", Email=" + GlobalVariable.TO_STRING(p_NewEMail);
            }
            if (!string.IsNullOrEmpty(p_NewEMailUser))
            {
                sql += ", EmailUser="******", EmailUserPW=" + GlobalVariable.TO_STRING(p_NewEMailUserPW);
            }
            sql += " WHERE AD_User_ID=" + p_AD_User_ID;
            log.Log(Level.SEVERE, "UserPassword Change Log=>" + sql);
            int iRes = DB.ExecuteQuery(sql, null, Get_Trx());

            if (iRes > 0)
            {
                bool error = false;
                //Check for yellowFin user password change if BI user is true..................
                object ModuleId = DB.ExecuteScalar("select ad_moduleinfo_id from ad_moduleinfo where prefix='VA037_' and IsActive = 'Y'"); // is active check by vinay bhatt on 18 oct 2018
                if (ModuleId != null && ModuleId != DBNull.Value)
                {
                    if (user.IsVA037_BIUser())
                    {
                        var  Dll              = Assembly.Load("VA037");
                        var  BIUser           = Dll.GetType("VA037.BIProcess.BIUsers");
                        var  objBIUser        = Activator.CreateInstance(BIUser);
                        var  ChangeBIPassword = BIUser.GetMethod("ChangeBIPassword");
                        bool value            = (bool)ChangeBIPassword.Invoke(objBIUser, new object[] { GetCtx(), GetAD_Client_ID(), Convert.ToString(user.GetVA037_BIUserName()), originalPwd });
                        if (value)
                        {
                            //user.SetPassword(p_NewPassword);
                            error = false;
                            user.SetPassword(originalPwd);
                            //return "OK";
                        }
                        else
                        {
                            error = true;
                            // return "@Error@";
                        }
                    }
                    else
                    {
                        error = false;
                        user.SetPassword(originalPwd);
                        // return "OK";
                    }
                }
                ModuleId = DB.ExecuteScalar("select ad_moduleinfo_id from ad_moduleinfo where prefix='VA039_' and IsActive = 'Y'"); // is active check by vinay bhatt
                if (ModuleId != null && ModuleId != DBNull.Value)
                {
                    MUser obj = new MUser(GetCtx(), p_AD_User_ID, null);
                    if (obj.IsVA039_IsJasperUser() == true)
                    {
                        var      Dll           = Assembly.Load("VA039");
                        var      JasperUser    = Dll.GetType("VA039.Classes.Users");
                        var      objJasperUser = Activator.CreateInstance(JasperUser);
                        var      BICreateUser  = JasperUser.GetMethod("ModifyUserPassword");
                        object[] args          = new object[] { GetCtx(), originalPwd };
                        bool     value         = (bool)BICreateUser.Invoke(objJasperUser, args);
                        if (value)
                        {
                            error = false;
                            user.SetPassword(originalPwd);

                            //return "@Error@";
                        }
                        else
                        {
                            error = true;
                            goto PasswordError;
                            // return "OK";
                        }
                    }
                }
                else
                {
                    error = false;
                    user.SetPassword(originalPwd);
                    // return "OK";
                }
PasswordError:
                if (error)
                {
                    return("@Error@");
                }
                else
                {
                    return("OK");
                }
            }
            else
            {
                return("@Error@");
            }
        }
        protected override string DoIt()
        {
            VLogger log = VLogger.GetVLogger(this.GetType().FullName);

            log.Log(Level.SEVERE, "UserPassword Change Log=>" + Convert.ToString(p_AD_User_ID));
            if (p_AD_User_ID == -1)
            {
                p_AD_User_ID = GetAD_User_ID();
            }

            MUser user    = MUser.Get(GetCtx(), p_AD_User_ID);
            MUser current = MUser.Get(GetCtx(), GetAD_User_ID());


            if (!current.IsAdministrator() && p_AD_User_ID != GetAD_User_ID() && user.HasRole())
            {
                throw new ArgumentException("@UserCannotUpdate@");
            }

            // SuperUser and System passwords can only be updated by themselves
            if (user.IsSystemAdministrator() && p_AD_User_ID != GetAD_User_ID() && GetAD_User_ID() != 100)
            {
                throw new ArgumentException("@UserCannotUpdate@");
            }

            log.Log(Level.SEVERE, "UserPassword Change Log Step Check for valid user=>" + Convert.ToString(p_AD_User_ID));
            if (string.IsNullOrEmpty(p_CurrentPassword))
            {
                if (string.IsNullOrEmpty(p_OldPassword))
                {
                    throw new ArgumentException("@OldPasswordMandatory@");
                }
                else if (!p_OldPassword.Equals(user.GetPassword()))
                {
                    if (!SecureEngine.Encrypt(p_OldPassword).Equals(user.GetPassword()))
                    {
                        throw new ArgumentException("@OldPasswordNoMatch@");
                    }
                }
            }

            else if (!p_CurrentPassword.Equals(current.GetPassword()))
            {
                throw new ArgumentException("@OldPasswordNoMatch@");
            }

            string validatePwd = Common.Common.ValidatePassword(null, p_NewPassword, p_NewPassword);

            if (validatePwd.Length > 0)
            {
                throw new ArgumentException(Msg.GetMsg(GetCtx(), validatePwd));
            }

            log.Log(Level.SEVERE, "UserPassword Change Log Step Password Change=>" + Convert.ToString(p_AD_User_ID));
            String originalPwd = p_NewPassword;

            String sql = "UPDATE AD_User SET Updated=SYSDATE,FailedloginCount=0, UpdatedBy=" + GetAD_User_ID();

            if (user.GetAD_User_ID() == current.GetAD_User_ID())
            {
                Common.Common.UpdatePasswordAndValidity(p_NewPassword, p_AD_User_ID, GetAD_User_ID(), -1, GetCtx());
            }
            else
            {
                sql += ",  PasswordExpireOn = null";
            }


            if (!string.IsNullOrEmpty(p_NewPassword))
            {
                MColumn column = MColumn.Get(GetCtx(), 417); // Password Column
                if (column.IsEncrypted())
                {
                    p_NewPassword = SecureEngine.Encrypt(p_NewPassword);
                }
                sql += ", Password="******", Email=" + GlobalVariable.TO_STRING(p_NewEMail);
            }
            if (!string.IsNullOrEmpty(p_NewEMailUser))
            {
                sql += ", EmailUser="******", EmailUserPW=" + GlobalVariable.TO_STRING(p_NewEMailUserPW);
            }
            sql += " WHERE AD_User_ID=" + p_AD_User_ID;
            log.Log(Level.SEVERE, "UserPassword Change Log=>" + sql);
            int iRes = DB.ExecuteQuery(sql, null, Get_Trx());

            if (iRes > 0)
            {
                return("@OK@");
            }
            else
            {
                return("@Error@");
            }
        }
Пример #14
0
        /// <summary>
        /// Invite New Users by sending mail.
        /// </summary>
        /// <param name="email"></param>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string InviteUsers(string email, List <RolesInfo> infos)
        {
            if (string.IsNullOrEmpty(email))
            {
                return("");
            }

            EMail  objMail       = new EMail(ctx, "", "", "", "", "", "", true, false);
            string isConfigExist = objMail.IsConfigurationExist(ctx);

            if (isConfigExist != "OK")
            {
                return(isConfigExist);
            }



            X_AD_InviteUser iuser = new X_AD_InviteUser(ctx, 0, null);

            if (iuser.Save())
            {
                for (int i = 0; i < infos.Count; i++)
                {
                    X_AD_InviteUser_Role userRole = new X_AD_InviteUser_Role(ctx, 0, null);
                    userRole.SetAD_InviteUser_ID(iuser.GetAD_InviteUser_ID());
                    userRole.SetAD_Role_ID(infos[i].AD_Role_ID);
                    userRole.Save();
                }
            }
            else
            {
                return(Msg.GetMsg(ctx, "VIS_InviteUsernotSaved"));
            }

            var emails = email.Split(';');

            string url     = (HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.Url.AbsolutePath).Substring(0, (HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.Url.AbsolutePath).LastIndexOf("/"));
            string hostUrl = url.Substring(0, url.LastIndexOf("/"));

            if (hostUrl.IndexOf("http") == -1)
            {
                hostUrl = HttpContext.Current.Request.Url.Scheme + "://" + hostUrl;
            }
            if (HttpContext.Current.Request.Url.Port > 0 && HttpContext.Current.Request.Url.Port != 80)
            {
                url      = url.Substring(0, url.LastIndexOf("/")) + ":" + HttpContext.Current.Request.Url.Port.ToString() + "/Areas/VIS/WebPages/CreateUser.aspx";
                hostUrl += ":" + HttpContext.Current.Request.Url.Port.ToString();
            }
            else
            {
                url = url.Substring(0, url.LastIndexOf("/")) + "/Areas/VIS/WebPages/CreateUser.aspx";
            }
            string queryString = "?inviteID=" + SecureEngine.Encrypt(iuser.GetAD_InviteUser_ID().ToString()) + "&URL=" + hostUrl + "&lang=" + ctx.GetAD_Language();

            if (emails.Length == 1)
            {
                queryString += "&mailID=" + SecureEngine.Encrypt(emails[0].ToString());
            }
            else
            {
                queryString += "&mailID=0";
            }

            objMail.SetSubject(Msg.GetMsg(ctx, "VIS_CreateUser"));
            //<label >Hello</label><br>" +
            //                    "<label >Please Click to create user with vienna Advantage</label>>

            string html = " <html><body> " + Msg.GetMsg(ctx, "VIS_InviteMailMessage") + "   <br>" +
                          "<a href='http://" + url + queryString + "'>click here </a> </body></html>  ";

            objMail.SetMessageHTML(html);

            for (int i = 0; i < emails.Count(); i++)
            {
                objMail.AddTo(emails[i], "");
            }

            string        res1 = objMail.Send();
            StringBuilder res  = new StringBuilder();

            if (res1 != "OK")           // if mail not sent....
            {
                if (res1 == "AuthenticationFailed.")
                {
                    res.Append("AuthenticationFailed");
                    return(res.ToString());
                }
                else if (res1 == "ConfigurationIncompleteOrNotFound")
                {
                    res.Append("ConfigurationIncompleteOrNotFound");
                    return(res.ToString());
                }
                else
                {
                    res.Append(" " + Msg.GetMsg(ctx, "MailNotSentTo") + ": " + email);
                }
            }
            else
            {
                {
                    if (!res.ToString().Contains("MailSent"))
                    {
                        res.Append("MailSent");
                    }
                }
            }

            return(res.ToString());
        }
Пример #15
0
        /// <summary>
        /// Get Roles for the user with email in client with the web store.
        /// If the user does not have roles and the web store has a default role, it will return that.
        /// </summary>
        /// <param name="eMail">email add</param>
        /// <param name="password">password</param>
        /// <param name="W_Store_ID">web store</param>
        /// <returns></returns>
        private KeyNamePair[] GetRolesByEmail(String eMail, String password, int W_Store_ID)
        {
            long start = CommonFunctions.CurrentTimeMillis();

            if (eMail == null || eMail.Length == 0 ||
                password == null || password.Length == 0 ||
                W_Store_ID == 0)
            {
                return(null);
            }
            //	Cannot use encrypted password
            if (SecureEngine.IsEncrypted(password))
            {
                return(null);
            }

            KeyNamePair[]      retValue = null;
            List <KeyNamePair> list     = new List <KeyNamePair>();
            //
            String sql = "SELECT u.AD_User_ID, r.AD_Role_ID, u.Name "
                         + "FROM AD_User u"
                         + " INNER JOIN W_Store ws ON (u.AD_Client_ID=ws.AD_Client_ID) "
                         + " INNER JOIN AD_Role r ON (ws.AD_Role_ID=r.AD_Role_ID) "
                         + "WHERE u.EMail='" + eMail + "'"
                         + " AND (u.Password='******' OR u.Password='******')"
                         + " AND ws.W_Store_ID='" + W_Store_ID + "'"
                         + " AND (r.IsActive='Y' OR r.IsActive IS NULL)"
                         + " AND u.isActive='Y' AND ws.IsActive='Y'"
                         + " AND u.AD_Client_ID=ws.AD_Client_ID "
                         + "ORDER BY r.Name";

            m_roles.Clear();
            m_users.Clear();
            IDataReader dr = null;

            try
            {
                //	execute a query
                dr = DataBase.DB.ExecuteReader(sql);

                if (!dr.Read())
                {
                    dr.Close();
                    return(null);
                }

                int AD_User_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                m_ctx.SetAD_User_ID(AD_User_ID);
                m_user = new KeyNamePair(AD_User_ID, eMail);
                m_users.Add(AD_User_ID);        //	for role
                //
                int AD_Role_ID = Utility.Util.GetValueOfInt(dr[1].ToString());
                m_ctx.SetAD_Role_ID(AD_Role_ID);
                String Name = dr[2].ToString();
                m_ctx.SetContext("##AD_User_Name", Name);
                if (AD_Role_ID == 0)    //	User is a Sys Admin
                {
                    m_ctx.SetContext("#SysAdmin", "Y");
                }
                KeyNamePair p = new KeyNamePair(AD_Role_ID, Name);
                m_roles.Add(p);
                list.Add(p);

                dr.Close();
                //
                retValue = new KeyNamePair[list.Count];
                retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
                retValue = null;
                m_ctx.SetContext("##AD_User_Name", eMail);
            }

            return(retValue);
        }
        //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));
        }
        /// <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)
        {
            roles = null;
            // loginModel = null;
            //bool isMatch = false;

            SecureEngine.Encrypt("t"); //Initialize

            //	Cannot use encrypted password
            if (model.Login1Model.Password != null && SecureEngine.IsEncrypted(model.Login1Model.Password))
            {
                //log.warning("Cannot use Encrypted Password");
                return(false);
            }
            //	Authentification
            bool    authenticated = false;
            bool    isLDAP        = false;
            MSystem system        = MSystem.Get(new Ctx());

            if (system != null && system.IsLDAP())
            {
                authenticated = system.IsLDAP(model.Login1Model.UserName, model.Login1Model.Password);
                if (authenticated)
                {
                    model.Login1Model.Password = null;
                }
                isLDAP = true;
                // if not authenticated, use AD_User as backup
            }



            StringBuilder sql = new StringBuilder("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name,")
                                .Append(" u.ConnectionProfile, u.Password ") //	4,5
                                .Append("FROM AD_User u")
                                .Append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')")
                                .Append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') ");

            //.Append("WHERE COALESCE(u.LDAPUser,u.Name)=@username")		//	#1
            if (isLDAP && authenticated)
            {
                sql.Append(" WHERE (COALESCE(u.LDAPUser,u.Value)=@username)");
            }
            else if (isLDAP && !authenticated && model.Login1Model.Password == null)// If user not authenicated using LDAP, then if LDAP user is available
            {
                sql.Append(" WHERE (u.LDAPUser=@username OR u.Name=@username OR u.Value=@username)");
            }
            else
            {
                sql.Append(" WHERE (u.Name=@username OR u.Value=@username)");
            }

            sql.Append(" AND u.IsActive='Y' ")
            .Append(" AND u.IsLoginUser='******' ")
            .Append(" AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')")
            .Append(" AND EXISTS (SELECT * FROM AD_Client c WHERE r.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')");
            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));

            if (model.Login1Model.Password != null)
            {
                if (isEncrypted == 'Y')
                {
                    sql.Append(" AND (u.Password='******')"); //  #2/3
                }
                else
                {
                    sql.Append(" AND (u.Password='******')");       //  #2/3
                }
            }
            sql.Append(" ORDER BY r.Name");
            IDataReader dr = null;

            //try
            //{
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@username", model.Login1Model.UserName);
            //	execute a query
            dr = DB.ExecuteReader(sql.ToString(), param);

            if (!dr.Read())             //	no record found
            {
                dr.Close();
                return(false);
            }

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

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

            List <int> usersRoles = new List <int>();


            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);

                roles.Add(p);

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

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


            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;
                        //1 firt check  - Check role exist
                        //if (usersRoles.Contains(Util.GetValueOfInt(drLogin[0])))
                        //{
                        //    //check for Org Access Setting
                        //    bool isUseUserOrgAccess = Util.GetValueOfString(DB.ExecuteScalar("SELECT IsUseUserOrgAccess FROM AD_ROLE WHERE AD_ROLE_ID = " + drLogin[0].ToString())) == "Y";
                        //    if (isUseUserOrgAccess) //User User Org
                        //    {
                        //        if (Convert.ToInt32(DB.ExecuteScalar("SELECT Count(1) FROM AD_User_OrgAccess WHERE AD_User_ID = " + AD_User_ID + " AND AD_ORG_ID= " + drLogin[2].ToString() + " AND IsActive='Y'")) < 1)
                        //        {
                        //            deleteRecord = true;
                        //        }
                        //    }
                        //    else //User Role Org Access
                        //    {
                        //        if (Convert.ToInt32(DB.ExecuteScalar("SELECT Count(1) FROM AD_Role_OrgAccess WHERE AD_Role_ID = " + drLogin[0] + " AND AD_ORG_ID= " + drLogin[2].ToString() + " AND IsActive='Y'")) < 1)
                        //        {
                        //            deleteRecord = true;
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    deleteRecord = true;
                        //}

                        //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);
        }
        }       //	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());
        }
        private static void CreateShortcut(IDataReader dr, List <ShortcutItemModel> lst, Ctx ctx, bool isSetting = false)
        {
            while (dr.Read())
            {
                ShortcutItemModel itm = new ShortcutItemModel();

                itm.ShortcutName  = Util.GetValueOfString(dr["Name2"]);
                itm.Action        = Util.GetValueOfString(dr["Action"]);
                itm.ActionID      = Util.GetValueOfInt(dr["ActionID"]);
                itm.SpecialAction = Util.GetValueOfString(dr["ClassName"]);
                itm.ActionName    = Util.GetValueOfString(dr["Name"]);
                if (!isSetting)
                {
                    itm.HasChild = "Y".Equals(Util.GetValueOfString(dr["HasChild"]));
                }

                if (!string.IsNullOrEmpty(itm.SpecialAction))
                {
                    string className = itm.SpecialAction;
                    string prefix    = "";
                    string nSpace    = "";

                    try
                    {
                        //  Tuple<String, String> aInfo = null;
                        if (Env.GetModulePrefix(itm.ActionName, out prefix, out nSpace))
                        {
                            className = className.Replace(nSpace, prefix.Substring(0, prefix.Length - 1));
                        }
                        else
                        {
                            if (prefix.Length == 0)
                            {
                                prefix = "VIS_";
                            }


                            nSpace = "VAdvantage";
                            if (className.Contains(nSpace))
                            {
                                className = className.Replace(nSpace, prefix.Substring(0, prefix.Length - 1));
                            }
                            nSpace = "ViennaAdvantage";
                            if (className.Contains(nSpace))
                            {
                                className = className.Replace(nSpace, prefix.Substring(0, prefix.Length - 1));
                            }
                        }
                    }
                    catch
                    {
                        // blank
                    }
                    itm.SpecialAction = className;
                }



                StringBuilder builder = new StringBuilder();

                if (Util.GetValueOfInt(dr["HASPARA"]) > 0)
                {
                    string      strSql = "SELECT parametername, parametervalue,ISENCRYPTED FROM AD_ShortCutParameter WHERE IsActive='Y' AND AD_ShortCut_ID=" + Util.GetValueOfInt(dr["AD_SHORTCUT_ID"]);
                    IDataReader drPara = null;
                    try
                    {
                        drPara = DB.ExecuteReader(strSql, null);
                        while (drPara.Read())
                        {
                            if (drPara["PARAMETERVALUE"] != null && drPara["PARAMETERVALUE"].ToString() != "")
                            {
                                string variableName = drPara["PARAMETERVALUE"].ToString();
                                String columnName   = string.Empty;
                                string env          = string.Empty;
                                if (variableName.Contains("@"))
                                {
                                    int index = variableName.IndexOf("@");
                                    columnName = variableName.Substring(index + 1);
                                    index      = columnName.IndexOf("@");
                                    if (index == -1)
                                    {
                                        break;
                                    }
                                    columnName = columnName.Substring(0, index);
                                    env        = ctx.GetContext(columnName);
                                }
                                else
                                {
                                    if (drPara["PARAMETERNAME"] != null && drPara["PARAMETERNAME"].ToString() != "")
                                    {
                                        columnName = drPara["PARAMETERNAME"].ToString();
                                    }
                                    env = variableName;
                                }

                                if (env.Length == 0)
                                {
                                    break;
                                }

                                if (drPara["ISENCRYPTED"].ToString().Equals("Y", StringComparison.OrdinalIgnoreCase))
                                {
                                    env = SecureEngine.Encrypt(env);
                                }
                                if (columnName.StartsWith("#"))
                                {
                                    while (columnName.StartsWith("#"))
                                    {
                                        columnName = columnName.Substring(1);
                                    }
                                }
                                builder.Append(columnName).Append("=").Append(env).Append('&');
                            }
                        }
                        builder.ToString().TrimEnd('&');
                        if (drPara != null)
                        {
                            drPara.Close();
                            drPara = null;
                        }
                    }
                    catch
                    {
                        if (drPara != null)
                        {
                            drPara.Close();
                            drPara = null;
                        }
                    }
                }

                if ((builder.ToString().Length > 0))
                {
                    itm.Url = Util.GetValueOfString(dr["Url"]) + builder.ToString();
                }
                else
                {
                    itm.Url = Util.GetValueOfString(dr["Url"]);
                }

                itm.KeyID = Util.GetValueOfInt(dr["ID"]);
                int AD_Image_ID = Util.GetValueOfInt(dr["AD_Image_ID"]);
                if (AD_Image_ID > 0)
                {
                    var img = new VAdvantage.Model.MImage(ctx, AD_Image_ID, null);

                    if (img.GetFontName() != null && img.GetFontName().Length > 0)
                    {
                        itm.HasImage         = true;
                        itm.IsImageByteArray = false;
                        itm.IconUrl          = img.GetFontName();
                    }
                    else if (img.GetImageURL() != null && img.GetImageURL().Length > 0)
                    {
                        itm.HasImage         = true;
                        itm.IsImageByteArray = false;
                        itm.IconUrl          = img.GetImageURL();
                    }
                    else if (img.GetBinaryData() != null)
                    {
                        itm.HasImage         = true;
                        itm.IsImageByteArray = true;
                        itm.IconBytes        = img.GetBinaryData();
                    }
                }
                lst.Add(itm);
            }
            dr.Close();
        }
        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;
            }
        }
        /// <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);
        }