Virginia N (previously) needed to maintain some authentication logic. The actual rules for authentication weren't actually documented, so her choices were to either copy/paste some authentication code from a different project, or try and refactor the authentication method in this one.

It was a hard choice. We'll dump the whole block of code, but I want to pull out a few highlights, starting with the opening condition:

if (LDAP == "O" && txtPassword.Text.ToUpper() != "MASTER PASSWORD. ABSOLUTELY SECRET, SAFE AND SECURE")

Oh yeah, hard-coded passwords in the application source. We're off to a good start. And that condition gets repeated:

if (LDAP != "O" || txtPassword.Text.ToUpper() == "MASTER PASSWORD. ABSOLUTELY SECRET, SAFE AND SECURE" || user == null)

Or wait, what if they actually supplied a user password, maybe?

if ( LDAP != "O" && System.Text.Encoding.ASCII.GetString(user.USR_PWD) == Encryption.Encrypt(txtPassword.Text) || txtPassword.Text.ToUpper() == "MASTER PASSWORD. ABSOLUTELY SECRET, SAFE AND SECURE" || sMDPass != null && sMDPass.Length > 0 && sMDPass == Encryption.Encrypt(txtPassword.Text) || isLoginAuto && txtUserName.Text.ToUpper().Equals(username.ToUpper()) && txtPassword.Text.Length == 0 || ldapauth)

Indenting from the original. At least they store passwords encrypted, I suppose. Just, y'know, not the master password. Also note the blend of &&s and ||s- I'm not 100% sure what this is supposed to do, but I hope the order of operations is correct.

frmBaseMessageBox.Show(new MLangue().GetLibelle(11649), MessageBoxButtons.OK, MessageBoxIcon.Stop);

I "love" when application logic and showing message boxes gets mixed together. It really gives you a sense of what the developer was going through, in a stream-of-consciousness fashion. There is no separation of concerns. There are a bunch of similar lines.

Now, those are a few ugly highlights, but the real fun is in seeing the whole thing. It's about three hundred lines of nested ifs with gigantic conditions, loads of different paths for attempting to handle logins, all implemented as a click event handler. Like a mountain, you can't really appreciate its scale till you stand back and see it all in context.

private void cmdOK_Click(object sender, EventArgs e) { Config.TraceOut.WriteLine("TimeTest:cmdOK_Click start:" + DateTime.Now.ToString("HH:mm:ss")); bool exiting = false; bool UserNbIncremented = false; try { Cursor = Cursors.WaitCursor; pictureBox1.Cursor = Cursors.WaitCursor; Refresh(); string connectionName = SetConnInfo(); string filePathOrURL = txtLAN.Text; if (filePathOrURL.Length == 0) filePathOrURL = Application.StartupPath; string LDAP = Param.GetParametre("LDAP"); bool ldapauth = false; SUSERSInfo user = null; if (LDAP == "O" && txtPassword.Text.ToUpper() != "MASTER PASSWORD. ABSOLUTELY SECRET, SAFE AND SECURE") { Config.TraceOut.WriteLogLine("before LDAP auth"); bool isaldapauth = false; if (txtPassword.Text.Length == 0) { isaldapauth = false; } else { DirectoryEntry entry = null; SearchResult sr = null; isaldapauth = LDAPAuthenticate(txtUserName.Text, txtPassword.Text, ref entry, ref sr); Trace.Write("after LDAP auth "); } Config.TraceOut.WriteLogLine(isaldapauth ? "ok" : "not ok"); if (isaldapauth) { IRelationPredicateBucket filter = new RelationPredicateBucket(); filter.PredicateExpression.Add(PredicateFactory.CompareValue(BIGTABLEWITHANYKINDOFDATAYOUDONTKNOWWHERETOSAVEFieldIndex.COD_TYPE, ComparisonOperator.Equal, 194)); filter.PredicateExpression.Add(PredicateFactory.CompareValue(BIGTABLEWITHANYKINDOFDATAYOUDONTKNOWWHERETOSAVEFieldIndex.COD_ID, ComparisonOperator.Equal, 0)); object objdeslong = BLFunctions.GetFieldValue(EntityFieldFactory.Create(BIGTABLEWITHANYKINDOFDATAYOUDONTKNOWWHERETOSAVEFieldIndex.COD_DESLONG), filter); if (!BLFunctions.IsNull(objdeslong) && objdeslong.ToString().IndexOf("|") > 0 && objdeslong.ToString().Substring(0, objdeslong.ToString().IndexOf("|")).Trim() == "O") { MAJUserFromLDAP(txtUserName.Text, txtPassword.Text); user = new ApplicationLogic().AuthenticateUser(filePathOrURL, connectionName, txtUserName.Text.Trim(), txtPassword.Text, true); } else { user = new ApplicationLogic().AuthenticateUser(filePathOrURL, connectionName, txtUserName.Text.Trim(), txtPassword.Text, true); Trace.Write("after db auth"); Config.TraceOut.WriteLogLine(user != null ? "ok" : "not ok"); } ldapauth = user != null; } } if (LDAP != "O" || txtPassword.Text.ToUpper() == "MASTER PASSWORD. ABSOLUTELY SECRET, SAFE AND SECURE" || user == null) { user = new ApplicationLogic().AuthenticateUser(filePathOrURL, connectionName, txtUserName.Text.Trim(), txtPassword.Text, isLoginAuto && txtUserName.Text.Equals(username)); } ACCESCODE_NBRESSAI acces = new ACCESCODE_NBRESSAI(""); ApplicationLogic applogic = new ApplicationLogic(); if (user != null) { if (!CheckUserAccess(user.USR_ID,applogic, ref acces)) { Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; Refresh(); SUSERSEntity userent= GetUserEnt(user.USR_ID); int nbmin = 0; if (userent != null) { nbmin =Convert.ToInt32(Math.Floor( (userent.USR_DATINVALID.AddMinutes(acces.Temps) - DateTime.Now).TotalMinutes)); } frmBaseMessageBox.Show(new MLangue().GetLibelle(12397).Replace("%%", nbmin.ToString()), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } if (null != user && !(isLoginAuto && txtUserName.Text.Equals(username) && !isInDom)) { IRelationPredicateBucket filter = new RelationPredicateBucket(); string sMDPass = Param.GetParametre("MDPASS"); if ( LDAP != "O" && System.Text.Encoding.ASCII.GetString(user.USR_PWD) == Encryption.Encrypt(txtPassword.Text) || txtPassword.Text.ToUpper() == "MASTER PASSWORD. ABSOLUTELY SECRET, SAFE AND SECURE" || sMDPass != null && sMDPass.Length > 0 && sMDPass == Encryption.Encrypt(txtPassword.Text) || isLoginAuto && txtUserName.Text.ToUpper().Equals(username.ToUpper()) && txtPassword.Text.Length == 0 || ldapauth) { ResetNbEssai(user.USR_ID, applogic); if (!CheckUserSign(user.SDEM_SIGN)) return; ApplicationMainConnection.DbConnectionName = connectionName; MLangue.LangID = ApplicationLogic.User.USR_LANGID; MLangue.LoadAllLibellesFromDB(); AppSettings.SaveConfig(txtUserName.Text, optLAN.Checked ? ConnectionType.LAN : ConnectionType.WS, txtLAN.Text, "", DatabaseServerType.SqlServer, cboConnection.Text, Convert.ToString(cboLang.Value), AppSettings.LastDate); if (RightsManager.UserNotActivated()) { Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; Refresh(); frmBaseMessageBox.Show(new MLangue().GetLibelle(4089), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } else { DbVersionInfo dbvers = new ApplicationLogic().GetCurrentBDVersion(); if (dbvers == null) { Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; Refresh(); frmBaseMessageBox.Show(new MLangue().GetLibelle(11649), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } if (!VersionSync()) { Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; Refresh(); frmBaseMessageBox.Show(new MLangue().GetLibelle(9653), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } else { if (!ChangeMDP(user.USR_ID, applogic,new MLangue())) { DialogResult = DialogResult.Cancel; ThreadAutoResetEvent.Set(); // Signaling to the main thread to continue return; } IEntityField2 field = EntityFieldFactory.Create(V_MODIFCODFieldIndex.ID); field.AggregateFunctionToApply = AggregateFunction.CountDistinct; IRelationPredicateBucket filter1 = new RelationPredicateBucket(); filter1.PredicateExpression.Add( PredicateFactory.CompareValue(V_MODIFCODFieldIndex.TRT_EXEC, ComparisonOperator.Equal, "N")); filter1.PredicateExpression.Add( PredicateFactory.CompareValue(V_MODIFCODFieldIndex.CONST_DISABLE, ComparisonOperator.Equal, "O")); object obj = BLFunctions.GetFieldValue(field, filter1); int count = 0; if (!BLFunctions.IsNull(obj)) count = Convert.ToInt32(obj); if (count > 0) { Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; Refresh(); frmBaseMessageBox.Show(new MLangue().GetLibelle(10572), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } dbCodeLibelle.SDEM_DBCODLIBELLE = BLFunctions.GetDemandeurForUser().SDEM_DBCODLIBELLE; cmdOK.Enabled = false; cmdCancel.Enabled = false; Cursor = Cursors.WaitCursor; pictureBox1.Cursor = Cursors.WaitCursor; exiting = true; Refresh(); DialogResult = DialogResult.OK; ThreadAutoResetEvent.Set(); // Signaling to the main thread to continue } } } else { SUSERSEntity userentity = null; IncrementNbEssai(user.USR_ID, applogic, acces, ref userentity); UserNbIncremented = true; if (userentity.USR_NBR == 0) { frmBaseMessageBox.Show(new MLangue().GetLibelle(12396), MessageBoxButtons.OK, MessageBoxIcon.Error); CloseApp(); } else { if (LDAP == "O" && !ldapauth) frmBaseMessageBox.Show(new MLangue().GetLibelle(9978), MessageBoxButtons.OK, MessageBoxIcon.Error); else frmBaseMessageBox.Show(sMessageInvalidPass, MessageBoxButtons.OK, MessageBoxIcon.Error); } Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; txtUserName.Focus(); } } else { Cursor = Cursors.Default; pictureBox1.Cursor = Cursors.Default; SUSERSEntity userentity = null; if(user!=null) IncrementNbEssai(user.USR_ID, applogic, acces, ref userentity); UserNbIncremented = true; if (userentity!=null&&userentity.USR_NBR == 0) { frmBaseMessageBox.Show(new MLangue().GetLibelle(12396), MessageBoxButtons.OK, MessageBoxIcon.Error); CloseApp(); } else { if (LDAP == "O" && !ldapauth) { frmBaseMessageBox.Show(new MLangue().GetLibelle(9978), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { if (!(isLoginAuto && isLoginAutoA && isInDom)) frmBaseMessageBox.Show(new MLangue().GetLibelle(7478) + " !", MessageBoxButtons.OK, MessageBoxIcon.Error); } } isLoginAutoA = false; txtUserName.Focus(); } if (++tries > 3 && !UserNbIncremented) { CloseApp(); } } catch (Exception e1) { if (e1.InnerException.InnerException != null && e1.InnerException.InnerException.Message.IndexOf("None of the factories") >= 0) { frmBaseMessageBox.Show( "Suite à la mise à jour du fichier de configuration, veuillez relancer l'application afin de prendre en compte les modifications"); Cursor = Cursors.Default; DialogResult = DialogResult.Cancel; } else { Cursor = Cursors.Default; DialogResult = DialogResult.Cancel; new MyCompanyUICommonFunctions().HandleError(e1, this); } } finally { if (!exiting) { Cursor = Cursors.Default; } else { CaptureScreen(); UICommonApplicationManager.ShowSplash(memoryImage, cboLang.Value); } } }

Virginia opted to refactor this instead of copy/pasting from another project. The other project was written in VB.Net, and while the code was slightly better organized, it was in VB.Net. By preference, Virginia opted to stick with even this C#. And honestly, given the organization this comes from, I can't imagine that the VB.Net was much cleaner.