public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { if (compilationSection.Debug) { if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs"))) { Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs")); } using (FileStream filestream = new FileStream((System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs/DebugLogs.txt")), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { StreamWriter sWriter = new StreamWriter(filestream); sWriter.WriteLine("Inside method OnAuthorization"); sWriter.Close(); sWriter.Dispose(); filestream.Close(); filestream.Dispose(); } } var request = filterContext.HttpContext.Request; // Only validate POSTs if (request.HttpMethod == WebRequestMethods.Http.Post) { if (compilationSection.Debug) { using (FileStream filestream = new FileStream((System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs/DebugLogs.txt")), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { StreamWriter sWriter = new StreamWriter(filestream); sWriter.WriteLine("Inside POST"); sWriter.Close(); sWriter.Dispose(); filestream.Close(); filestream.Dispose(); } } DataSecurity objDataSecurity = new DataSecurity(); if (compilationSection.Debug) { if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs"))) { Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs")); } using (FileStream filestream = new FileStream((System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs/DebugLogs.txt")), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { StreamWriter sWriter = new StreamWriter(filestream); sWriter.WriteLine("request.Form[sCalledFrom]" + request.Form["sCalledFrom"]); sWriter.WriteLine("objDataSecurity.CreateHash" + objDataSecurity.CreateHash(string.Format(Common.ConstEnum.s_SSO, Convert.ToString(DateTime.Now.Year)), Common.ConstEnum.User_Password_Encryption_Key)); sWriter.Close(); sWriter.Dispose(); filestream.Close(); filestream.Dispose(); } } string formField = null; string sCompanyName = null; foreach (String key in filterContext.HttpContext.Request.Form.AllKeys) { if (key == "sCompanyName") { sCompanyName = Convert.ToString(filterContext.HttpContext.Request.Form["sCompanyName"]); } } foreach (String key in filterContext.HttpContext.Request.Form.AllKeys) { if (key == "FormID") { formField = Convert.ToString(filterContext.HttpContext.Request.Form["FormID"]); HttpContext.Current.Session["formField"] = formField; } } if (request.Form["sCalledFrom"] != objDataSecurity.CreateHash(string.Format(Common.ConstEnum.s_SSO, Convert.ToString(DateTime.Now.Year)), Common.ConstEnum.User_Password_Encryption_Key)) { if (formField == null) { new ValidateAntiForgeryTokenAttribute() .OnAuthorization(filterContext); } } } }
/// <summary> /// AuthenticateUser /// </summary> /// <param name="domain"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="LdapPath"></param> /// <param name="Errmsg"></param> /// <returns></returns> public Dictionary <string, object> AuthenticateUser(string domain, string username, string password, string LdapPath, out string Errmsg, out Dictionary <string, object> DictDetails) { CompanyDTO objSelectedCompany = null; UserInfoDTO ObjuserDTO = null; UserPrincipal userPrincipal = null; Errmsg = ""; string domainAndUsername = domain + @"\" + username; DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password); DictDetails = new Dictionary <string, object>(); try { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { userPrincipal = UserPrincipal.FindByIdentity(ctx, username); if (compilationSection.Debug) { Common.Common.WriteLogToFile("ConnectedServer " + ctx.ConnectedServer + "Container " + ctx.Container + "ContextType " + ctx.ContextType + "Name " + ctx.Name + "Options " + ctx.Options + "UserName " + ctx.UserName, null); if (userPrincipal == null) { Common.Common.WriteLogToFile("userPrincipal null ", null); } } if (userPrincipal != null) { using (LoginUserDetails objLoginUserDetails = new LoginUserDetails()) { using (SSOSL objSSOSL = new SSOSL()) { using (DataSecurity objDataSecurity = new DataSecurity()) { // Bind to the native AdsObject to force authentication. Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (result == null) { //return false; DictDetails = null; return(DictDetails); } // Update the new path to the user in the directory LdapPath = result.Path; string _filterAttribute = (String)result.Properties["cn"][0]; objSelectedCompany = new CompanyDTO(); objSelectedCompany = objSSOSL.getSingleCompanies(InsiderTradingSSO.Common.Common.getSystemConnectionString(), ConfigurationManager.AppSettings["DBName"].ToString()); objLoginUserDetails.CompanyDBConnectionString = objSelectedCompany.CompanyConnectionString; Hashtable ht_Param = new Hashtable(); if (username != null && !username.Length.Equals(0)) { ht_Param.Add("EmployeeId", username); } if (compilationSection.Debug) { Common.Common.WriteLogToFile("Get EmployeeID as " + userPrincipal.EmployeeId, null); } else { ht_Param.Add("EmployeeId", null); } ht_Param.Add("EmailId", userPrincipal.EmailAddress); if (compilationSection.Debug) { Common.Common.WriteLogToFile("Get EmailID as " + userPrincipal.EmailAddress, null); } ObjuserDTO = objSSOSL.LoginSSOUserInfo(objLoginUserDetails.CompanyDBConnectionString, ht_Param); DictDetails.Add("sUserName", ObjuserDTO.LoginID); DictDetails.Add("sPassword", ObjuserDTO.Password); DictDetails.Add("sCompanyName", objSelectedCompany.sCompanyDatabaseName); DictDetails.Add("sCalledFrom", objDataSecurity.CreateHash(string.Format(Common.ConstEnum.s_SSO, Convert.ToString(DateTime.Now.Year)), Common.ConstEnum.User_Password_Encryption_Key)); if (compilationSection.Debug) { if (DictDetails.Count >= 0) { Common.Common.WriteLogToFile("Diction object with all details ", null); } } return(DictDetails); } } } } } } catch (Exception ex) { Errmsg = ex.Message; if (compilationSection.Debug) { Common.Common.WriteLogToFile("Exception occurred (AuthenticateUser failed ", ex); } DictDetails = null; throw new Exception("Error authenticating user." + ex.Message); } return(DictDetails); }
public async Task <ActionResult> Login(UserDetailsModel model) { LoginUserDetails objLoginUserDetails = null; InsiderTradingEncryption.DataSecurity objPwdHash = null; CompanyDTO objSelectedCompany = null; DataSecurity objDataSecurity = new DataSecurity(); PasswordConfigDTO objPasswordConfig = null; int loginCount = 0; Common.Common.WriteLogToFile("Start Method", System.Reflection.MethodBase.GetCurrentMethod()); bool IsEmailOTPActive = false; try { Session["UserCaptchaText"] = (model.sCaptchaText == null) ? string.Empty : model.sCaptchaText; TempData["ShowDupTransPopUp"] = 1; objLoginUserDetails = new LoginUserDetails(); string formUsername = string.Empty; string formPassword = string.Empty; string formEncryptedUsername = string.Empty; string formEncryptedPassword = string.Empty; string sPasswordHash = string.Empty; string javascriptEncryptionKey = Common.ConstEnum.Javascript_Encryption_Key; string userPasswordHashSalt = Common.ConstEnum.User_Password_Encryption_Key; string EncryptedRandomNo = string.Empty; if (model.sCalledFrom != objDataSecurity.CreateHash(string.Format(Common.ConstEnum.s_SSO, Convert.ToString(DateTime.Now.Year)), userPasswordHashSalt)) { objPwdHash = new InsiderTradingEncryption.DataSecurity(); formEncryptedUsername = model.sUserName; formEncryptedPassword = model.sPassword; formEncryptedUsername = DecryptStringAES(formEncryptedUsername, javascriptEncryptionKey, javascriptEncryptionKey); formEncryptedPassword = DecryptStringAES(formEncryptedPassword, javascriptEncryptionKey, javascriptEncryptionKey); EncryptedRandomNo = formEncryptedUsername.Split('~')[1].ToString(); if (EncryptedRandomNo != Convert.ToString(Session["randomNumber"])) { throw new System.Web.HttpException(401, "Unauthorized access"); } formUsername = formEncryptedUsername.Split('~')[0].ToString(); formPassword = formEncryptedPassword.Split('~')[0].ToString(); } else { Session["IsSSOActivated"] = "1"; formUsername = model.sUserName; sPasswordHash = string.IsNullOrEmpty(model.sPassword) ? "" : model.sPassword; } using (CompaniesSL objCompanySL = new CompaniesSL()) { if (System.Configuration.ConfigurationManager.AppSettings["CompanyType"] == "Textbox") { Dictionary <string, string> objCompaniesDictionary = null; objCompaniesDictionary = new Dictionary <string, string>(); foreach (InsiderTradingDAL.CompanyDTO objCompanyDTO in objCompanySL.getAllCompanies(Common.Common.getSystemConnectionString())) { objCompaniesDictionary.Add(objCompanyDTO.sCompanyDatabaseName, objCompanyDTO.sCompanyName); } if (objCompaniesDictionary.ContainsValue(model.sCompanyName.ToLower())) { model.sCompanyName = (from entry in objCompaniesDictionary where entry.Value.ToLower() == model.sCompanyName.ToLower() select entry.Key).FirstOrDefault(); } else { objLoginUserDetails.ErrorMessage = "Invalid company name"; objLoginUserDetails.IsAccountValidated = false; Common.Common.SetSessionValue(ConstEnum.SessionValue.UserDetails, objLoginUserDetails); Common.Common.WriteLogToFile("Invalid company name"); Session["IsSSOActivated"] = null; return(RedirectToAction("Login", "Account")); } } objSelectedCompany = objCompanySL.getSingleCompanies(Common.Common.getSystemConnectionString(), model.sCompanyName); if (model.sCalledFrom != objDataSecurity.CreateHash(string.Format(Common.ConstEnum.s_SSO, Convert.ToString(DateTime.Now.Year)), userPasswordHashSalt)) { string saltValue = string.Empty; string calledFrom = "Login"; using (UserInfoSL ObjUserInfoSL = new UserInfoSL()) { List <AuthenticationDTO> lstUserDetails = ObjUserInfoSL.GetUserLoginDetails(objSelectedCompany.CompanyConnectionString, formUsername, calledFrom); foreach (var UserDetails in lstUserDetails) { saltValue = UserDetails.SaltValue; } } using (TwoFactorAuthSL objIsOTPEnable = new TwoFactorAuthSL()) { IsEmailOTPActive = objIsOTPEnable.CheckIsOTPActived(objSelectedCompany.CompanyConnectionString, formUsername); } string usrSaltValue = (saltValue == null || saltValue == string.Empty) ? userPasswordHashSalt : saltValue; if (saltValue != null && saltValue != "") { sPasswordHash = objPwdHash.CreateHashToVerify(formPassword, usrSaltValue); } else { sPasswordHash = objPwdHash.CreateHash(formPassword, usrSaltValue); } } objLoginUserDetails.UserName = formUsername; objLoginUserDetails.Password = sPasswordHash; objLoginUserDetails.CompanyDBConnectionString = objSelectedCompany.CompanyConnectionString; objLoginUserDetails.CompanyName = model.sCompanyName; objLoginUserDetails.IsUserLogin = false; //this flag indicate that user is not yet login sucessfully Common.Common.SetSessionValue(ConstEnum.SessionValue.UserDetails, objLoginUserDetails); using (var objPassConfigSL = new PasswordConfigSL()) { objPasswordConfig = objPassConfigSL.GetPasswordConfigDetails(objSelectedCompany.CompanyConnectionString); loginCount = (Session["UserLgnCount"] == null) ? 0 : Convert.ToInt32(Session["UserLgnCount"].ToString()); TempData["ShowCaptcha"] = false; if (loginCount >= (objPasswordConfig.LoginAttempts - 1)) { TempData["ShowCaptcha"] = true; Session["DisplayCaptcha"] = true; } if ((loginCount >= objPasswordConfig.LoginAttempts && model.sCaptchaText == "") || loginCount >= objPasswordConfig.LoginAttempts && model.sCaptchaText != Session["CaptchaValue"].ToString()) { TempData["ShowCaptcha"] = true; TempData["ErrorMessage"] = "Please provide valid text"; } } } } catch (Exception exp) { //If User is trying to login with a loginID which is being logged-in into the system. Then show the message and don't allow to login. string sErrMessage = exp.Message; objLoginUserDetails.ErrorMessage = sErrMessage; objLoginUserDetails.IsAccountValidated = false; Common.Common.SetSessionValue(ConstEnum.SessionValue.UserDetails, objLoginUserDetails); Common.Common.WriteLogToFile("Exception occurred ", System.Reflection.MethodBase.GetCurrentMethod(), exp); Session["IsSSOActivated"] = null; ClearAllSessions(); return(RedirectToAction("Login", "Account")); } finally { objLoginUserDetails = null; objPwdHash = null; objSelectedCompany = null; } if (IsEmailOTPActive) { Common.Common.WriteLogToFile("End Method", System.Reflection.MethodBase.GetCurrentMethod()); Session["TwoFactor"] = 1; Session["IsOTPAuthPage"] = "TwoFactorAuthentication"; return(RedirectToAction("Index", "TwoFactorAuth", new { acid = Convert.ToString(0), calledFrom = "" })); } else { Common.Common.WriteLogToFile("End Method", System.Reflection.MethodBase.GetCurrentMethod()); Session["loginStatus"] = 1; return(RedirectToAction("Index", "Home", new { acid = Convert.ToString(0), calledFrom = "Login" })); } }
public ActionResult Index() { LoginUserDetails objLoginUserDetails = null; SSOSL objSSOSL = null; UserInfoDTO ObjuserDTO = null; CompanyDTO objSelectedCompany = null; DataSecurity objDataSecurity = null; UserPrincipal userPrincipal = null; string s_debugInfo = string.Empty; string PrompSSOCredentials = "1"; try { if (PrompSSOCredentials == (ConfigurationManager.AppSettings["PromptSSOCredentials"].ToString())) { Dictionary <string, string> objCompaniesDictionary = null; List <InsiderTradingDAL.CompanyDTO> lstCompanies = null; using (CompaniesSL objCompaniesSL = new CompaniesSL()) { lstCompanies = objCompaniesSL.getAllCompanies(Common.Common.getSystemConnectionString()); objCompaniesDictionary = new Dictionary <string, string>(); objCompaniesDictionary.Add("", "Select Company"); foreach (InsiderTradingDAL.CompanyDTO objCompanyDTO in lstCompanies) { objCompaniesDictionary.Add(objCompanyDTO.sCompanyDatabaseName, objCompanyDTO.sCompanyName); } } ViewBag.JavascriptEncryptionKey = Common.ConstEnum.Javascript_Encryption_Key; ViewBag.CompaniesDropDown = objCompaniesDictionary; return(View("SSOLogin")); //return View("AuthenticationFailed"); } else { //Login with Directory Credentials using (DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.UserDomainName)) { string s_CurrentLoggedInUser = Request.ServerVariables["LOGON_USER"].ToUpper(); s_debugInfo = "# Domain Name - " + Environment.UserDomainName + "# Request Server Variables (LOGON_USER) - " + s_CurrentLoggedInUser; if (string.IsNullOrEmpty(s_CurrentLoggedInUser)) { s_CurrentLoggedInUser = System.Web.HttpContext.Current.User.Identity.Name; s_debugInfo += "# System.Web.HttpContext.Current.User.Identity.Name - " + s_CurrentLoggedInUser; } if (string.IsNullOrEmpty(s_CurrentLoggedInUser)) { s_CurrentLoggedInUser = User.Identity.Name; s_debugInfo += "# User.Identity.Name - " + User.Identity.Name; } foreach (DirectoryEntry item in dirEntry.Children) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { userPrincipal = UserPrincipal.FindByIdentity(ctx, Request.ServerVariables["LOGON_USER"].Replace(Environment.UserDomainName + @"\", string.Empty)); if (userPrincipal != null) { if (s_CurrentLoggedInUser.Equals((Environment.UserDomainName + @"\" + userPrincipal.SamAccountName).ToUpper())) { s_debugInfo += "# User Principal Given Name - " + userPrincipal.GivenName + "# User Principal EmployeeId - " + userPrincipal.EmployeeId + "# User Principal EmailAddress - " + userPrincipal.EmailAddress; using (objSSOSL = new SSOSL()) { objLoginUserDetails = new LoginUserDetails(); objSelectedCompany = new CompanyDTO(); objSelectedCompany = objSSOSL.getSingleCompanies(InsiderTradingSSO.Common.Common.getSystemConnectionString(), ConfigurationManager.AppSettings["DBName"].ToString()); objLoginUserDetails.CompanyDBConnectionString = objSelectedCompany.CompanyConnectionString; Hashtable ht_Param = new Hashtable(); if (userPrincipal.EmployeeId != null && !userPrincipal.EmployeeId.Length.Equals(0)) { ht_Param.Add("EmployeeId", userPrincipal.EmployeeId); } else { ht_Param.Add("EmailId", userPrincipal.EmailAddress); } ObjuserDTO = objSSOSL.LoginSSOUserInfo(objLoginUserDetails.CompanyDBConnectionString, ht_Param); objDataSecurity = new DataSecurity(); Dictionary <string, object> dictUserDetails = new Dictionary <string, object>(); dictUserDetails.Add("sUserName", ObjuserDTO.LoginID); dictUserDetails.Add("sPassword", ObjuserDTO.Password); dictUserDetails.Add("sCompanyName", objSelectedCompany.sCompanyDatabaseName); dictUserDetails.Add("sCalledFrom", objDataSecurity.CreateHash(string.Format(Common.ConstEnum.s_SSO, Convert.ToString(DateTime.Now.Year)), Common.ConstEnum.User_Password_Encryption_Key)); return(this.RedirectAndPost(ConfigurationManager.AppSettings["VigilanteURL"].ToString(), dictUserDetails)); } } } } } } } } catch { s_debugInfo += "# Login Failed. "; return(View("AuthenticationFailed")); } finally { if (compilationSection.Debug) { if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs"))) { Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs")); } using (FileStream filestream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/DebugLogs/SSODebugLogs.txt"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { StreamWriter sWriter = new StreamWriter(filestream); sWriter.WriteLine(" SSO Login - " + DateTime.Now); string[] arr_debugInfo = s_debugInfo.Split('#'); foreach (string debugInfo in arr_debugInfo) { sWriter.WriteLine(debugInfo); } sWriter.WriteLine("--------------------------------------------------------------------"); sWriter.Close(); sWriter.Dispose(); filestream.Close(); filestream.Dispose(); } } } return(View()); }