/// <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); }
} // 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); } } } }
/// <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); }
/// <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)); }
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); }
} // 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
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@"); } }
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())); }
/// <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()); }
/// <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); }
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(); }
} // 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()); }
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@"); } }
/// <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); }