IanN1990

Input Username Validation - Prevent non-allowed use

4 posts in this topic

#1 ·  Posted (edited)

Good Evening, 

I am writing this posting at 11:55pm while behind on other projects despite having spent almost 60 hours this week working :)

I provide the code as "As is". Perhaps once my projects are over i will come back and turn it into a UDF, if people find it useful but no promises :)

The main reason i am providing this is since i have joined i have never giving the community anything meaning full but this function is truly amazing, so i am sharing it.

It is written for AD use but if your good with databases you could replace that AD aspect with your own database.

 

#NoTrayIcon
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#Include <AD.au3>
#include <Misc.au3>
#include <GuiComboBox.au3>
#Include <String.au3>


#Region GUI
   $Form2 = GUICreate("Username Input Validation", 366, 150) ;If you change $Form2, you will need to change it in the UDF as well
      ;ADExample()
      DatabaseExample()
   $Button2 = GUICtrlCreateButton("Click for Options", 8, 40, 349, 28)
      GUICtrlSetFont(-1, 14, 400, 0, "Arial")
   $Button3 = GUICtrlCreateButton("Request Update", 8, 74, 350, 25)
      GUICtrlSetFont(-1, 14, 400, 0, "Arial")
   GUISetState()
#EndRegion GUI

   While 1
      $nMsg = GUIGetMsg()
         Switch $nMsg
            Case $GUI_EVENT_CLOSE
               Exit
         EndSwitch
   WEnd


   Func ADExample()
      _AD_Open() ;<<--This Part is just to find an OU for the Example, Set your own OU for each OU location you want users from
      $sFQDN = _AD_SamAccountNameToFQDN()
      $iPos = StringInStr($sFQDN, ",")
      Global $sOU = StringMid($sFQDN, $iPos + 1)
      _AD_Close()

      Global $ADArray = [$sOU]
      _GUICtrlCreateComboValidated("", 8, 8, 350, 21, "", "", 1, 2)
   EndFunc

   Func DatabaseExample()
      Global $ADResults = ["Randell Rucker","Josue Jetton","German Goldblatt","Kasey Khan","Antwan Alligood","Bobbie Buffaloe","Arnold Aschenbrenner","Walker Wiley","Ezequiel Esterly","Antione Aldinger","Nelson Nagata","Thanh Tomes","Bradford Blakeman","Nathanael Northway","Jewel Jumper","Warren Wixom","Rocky Relyea","Cleveland Celaya","Wilmer Welden","Luther Legere","Arden Araya","Jonathon Jarmon","Arnulfo Ashbrook","Jeremiah Jaworski","Edwin Easterwood","Adam Alvord","Kory Koch","Winston Witzke","Lane Logue","Louie Largent","Whitney Wayt","Hung Hardiman","Hoyt Honea","Louis Lovvorn","Emmitt Elswick","Romeo Russum","Oliver Oberlander","Quintin Quesinberry","Wiley Wadman","Dick Dow","Shon Sibley","Wayne Walling","Fredric French","Pierre Pigford","Ashley Antunez","Marc Mcfarren","Vicente Vermeulen","Hector Heckel","Neil Nova","Scottie Sayegh","Stan Searight","Tyrell Tamez","Damion Duropan","Arnold Ardis","Derrick Dudash","Olin Odwyer","Alton Altman","Russel Rebelo","Keven Kenney","Alexis Axley","Glen Glickman","Herman Hodgkinson","Harley Hruby","Patricia Pellegrini","Simon Sheppard","Drew Defelice","Scott Spurr","Tobias Thurmond","Titus Tietjen","Hubert Huffer","Virgil Valasquez","Joel Junkins","Federico Frankel","Delmer Duden","Everett Eades","Marcellus Mccree","Edgar Ellender","Randal Rozell","Delmar Denver","Alberto Araujo","Milton Mehl","Jackson Jernigan","Guadalupe Gularte","Lindsay Laughter","Clifford Coca","Heriberto Hamblin","Man Mccants","Rene Rathbone","Jeramy Janke","Jerome Jines","Robby Rossbach","James Jenkins","Myron Miura","Darell Drago","Anibal Ambler","Devin Dieguez","Larry Lady","Damon Disanto","Gus Guy","Carl Cantero","Orval Ohearn","Kendrick Kendricks","Stuart Surratt","Marcelino Munyon","Augustus Atwood","Morris Mallet","Emerson Engelking","Drew Dice","Otha Ortmann","Rico Rowles","Xavier Xiong","Willie Westlund","Nickolas Navas","Damion Dancy","Bob Blasko","Herbert Hempel","Dylan Doverspike","Billy Boggs","Val Vanzant","Corey Cookson","Fidel Fentress","Parker Pennypacker","Stephan Siers","Ivan Imes","Gale Gundlach","Wilbert Wirt","Fredric Fawley","Ira Inouye","Franklyn Fambro","Luke Lauffer","Nick Nagao","Philip Pero","Erik Erdmann","Al Adkisson","Vaughn Verge","Billie Brewster","Delmer Dambrosia","Kory Knecht","Alejandro Arner","Renaldo Raske","Joshua Janzen","Samuel Su","Chadwick Croyle","Mitch Mcilvain","Jonathan Janusz","Tommy Trafton","Antone Ayres","Emory Esses","Bruno Bovee","Mike Munday","Twana Trowbridge","Myrta Mcneece","Maida Mikus","Maudie Morphew","Laraine Loya","Yuonne Yeadon","Tonette Ton","Kathryn Klutts","Jessika Jobe","Ernestina Eury","Sarah Spano","Mechelle Monge","Arcelia Abate","Sanjuanita Spoto","Chasidy Craghead","Yasmine Young","Elna Espino","Fabiola Fravel","Versie Vore","Monica Martino","Sherilyn Santacruz","Bev Binns","Jama Jacox","Julee Juhasz","Bethel Brigmond","Kiara Kalinowski","Liberty Leong","Tajuana Tyrell","Earlean Eleby","Mathilde Maday","Hoa Heap","Brigida Butz","Karina Kingsland","Ardella Altman","Ellamae Esses","Leeanne Leonhardt","Yang Yost","Clarita Crosland","Tiana Tomasi","Elanor Eddington","Dora Deshon","Wonda Wix","Nidia Niccum","Gena Gorder","Haydee Higuchi","My Morning","Lasandra Larrimore","Birdie Bueche","Denyse Desper","Mabel Matlock","Lili Lunceford","Bronwyn Blume","Shay Sundquist","Serena Soule","Selma Seng","Penney Peavler","Francine Frailey","Fredda Foreman","Latesha Luster","Lakenya Lierman","Oleta Omalley","Janett Jarman","Cristy Cortese","Ulrike Uribe","Beckie Barclay","Mora Mckey","Ellen Eldred","Deloise Dynes","Teresita Thorsen","Sona Santibanez","Jerri Jernigan","Jenna Jimerson","Angelita Axel","Londa Langworthy","Crissy Clermont","Adeline Adan","Daphine Degreenia","Jeanie Jutras","Shira Spargo","Lizette Landaverde","Sharri Streicher","Adria Austin","Deneen Draper","Andree Ahlers","Mitsue Mcmickle","Rachel Rittenhouse","Brandee Bermejo","Johnetta Jacobson","Taneka Truesdale","Joni Jinks","Georgia Grimsley","Melodi Martello","Dorotha Darnell","Vanna Vierra","Le Lewison","Eufemia Eaves","Sachiko Satterfield","Mindi Mccoin","Margareta Manns"]
      _ArraySort($ADResults)
       _GUICtrlCreateComboValidated("", 8, 8, 350, 21, "", 0)
   EndFunc

#Region UDF
   Func _GUICtrlCreateComboValidated($Text, $Left, $Top, $Width, $Height, $Style=BitOR($CBS_SIMPLE,$CBS_AUTOHSCROLL, $CBS_SORT), $ExStyle=-1, $DatabaseType=0, $ADType=3)
      Global $LastUser, $InputText, $NoRepeat = 0, $Exact = 0, $hDLL = DllOpen("user32.dll"), $CheckType = $ADType

      Global $Input1 = GUICtrlCreateCombo($Text, $Left, $Top, $Width, $Height, $Style, $ExStyle)
      Global $Input1Handle = GUICtrlGetHandle($Input1)
      Global $Control = ControlGetPos($Form2, "", $Input1)

      If $DatabaseType = 1 Then ; Set up ADStuff
         Global $ADResults[0], $ADDomain=""
         Global $ADDomain = CheckFastestADConnection() ;Finds the fastest AD Connection to make input more responsive
         If Not _AD_Open("", "", "", $ADDomain, "") Then Exit 0*MsgBox(0, "Error", "AD Connection failed")*_AD_Close() ;Ensures Connection is made
      EndIf

      GUIRegisterMsg($WM_COMMAND, "WM_COMMAND")
      AdlibRegister("Test1", 10)
   EndFunc

   Func CheckFastestADConnection()
      _AD_Open()
      $aDC = _AD_ListDomainControllers()
      Global $ADDomainArray[ubound($aDC)]
      For $i = 1 to ubound($ADDomainArray)-1
         $ADDomainArray[$i] = $aDC[$i][2]
      Next
      _AD_close()

      Dim $FastestADConnection = 1000
         For $i=1 to ubound($ADDomainArray)-1
            $ADConnectionTest = TimerInit()
            _AD_Open("", "", "DC=office,DC=local", $ADDomainArray[$i], "CN=Configuration,DC=office,DC=local")
            _AD_Close()

            $TimerDiff = Timerdiff($ADConnectionTest)
            If $TimerDiff < 25 then Return $ADDomainArray[$i]
            If $FastestADConnection > $TimerDiff then
               $FastestADConnection = $TimerDiff
               $TempADDomainArray = $ADDomainArray[$i]
            EndIf
         Next
      Return $TempADDomainArray
   EndFunc

   Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
      Switch $lParam
         Case $Input1Handle
            Switch BitShift($wParam, 16)
               Case $CBN_EDITUPDATE
                  If GUICtrlRead($Input1) = "" or _IsPressed("2E", $hDLL) Then
                     Do
                     Until _GUICtrlComboBox_DeleteString($Input1, 0) = -1
                  ElseIf StringLeft(GUICtrlRead($Input1), 1) = ">" Then
                  ElseIf GUICtrlRead($Input1) = " " then ; or StringRegExp(Stringleft(guictrlread($Input1), 1), "([^a-zA-Z])") Then Optional
                     ControlSetText($Form2, "", $Input1, "")
                  ElseIf _IsPressed(08, $hDLL) then
                     If $Exact <> -1 Then
                        $Exact = -ControlSend($Form2, "", $Input1, "{Space}")
                     Else
                        ControlSend($Form2, "", $Input1, "{backspace}")
                     EndIf
                  ElseIf $NoRepeat = 0 Then
                     If StringLen(GUICtrlRead($Input1)) = 1 And _GUICtrlComboBox_GetCount($Input1) = 0 Then UpdateComboBox()
                     $InputName = Clipget()
                     If StringInStr($InputName, @CR) Then $InputName = stringsplit(Clipget(), @CR, 1)[1]
                     If GUICtrlRead($Input1) = $InputName and _GUICtrlComboBox_GetCount($Input1)=0 then
                           Do
                           Until _GUICtrlComboBox_DeleteString($Input1, 0) = -1
                              If StringInStr(GUICtrlRead($Input1), $InputName, 0, 1, 1, StringLen($InputName)) = 0 Then
                                 Return ControlSetText($Form2, "", $Input1, "")
                              Else
                                 $InputName = _StringProper(StringStripWS($InputName, 3))
                                 ControlSetText($Form2, "", $Input1, $InputName)
                                 UpdateComboBox($InputName)
                              EndIf
                     ElseIf GUICtrlRead($Input1) = $InputText & $InputName then
                           ControlSetText($Form2, "", $Input1, $InputText)
                     ElseIf ControlGetText($Form2, "", $Input1) = $LastUser & $InputName then
                           ControlSetText($Form2, "", $Input1, $LastUser)
                        EndIf

                     If _GUICtrlComboBox_FindString($input1, ControlGetText($Form2, "", $Input1)) <> -1 Then
                        $Exact = _GUICtrlComboBox_FindStringExact($input1, GUICtrlRead($Input1))
                        $InputText = GUICtrlRead($Input1)
                     EndIf
                     __GUICtrlComboBox_AutoComplete()
                     If _GUICtrlComboBox_FindString($input1, ControlGetText($Form2, "", $Input1)) <> -1 Then $LastUser = GUICtrlRead($Input1)
                     If _GUICtrlComboBox_FindStringExact($Input1, ControlGetText($Form2, "", $Input1)) = -1 Then
                        ControlSend($Form2, "", $Input1, "{backspace}")
                        If ControlGetText($Form2, "", $Input1) = "" then $NoRepeat = 1
                     EndIf
                  Elseif $NoRepeat = 1 Then
                     $NoRepeat = _GUICtrlComboBox_AutoComplete($Input1)
                  EndIf
               Case $CBN_KILLFOCUS
                  ControlSend($Form2, "", $Input1, "{End}")
                  $InputText = GUICtrlRead($Input1)
                  AdlibRegister("LoadSettingsExit", 1)
                  AdlibUnRegister("Test1")
               Case $CBN_SETFOCUS
                  $Exact = -ControlSend($Form2, "", $Input1, "{End}")
                  AdlibRegister("Test1", 10)
               Case $CBN_SELCHANGE
                  $Exact = ControlSend($Form2, "", $Input1, "{End}")
                  If $LastUser = GUICtrlRead($Input1) Then
                     If _IsPressed(26, $hDLL) then ControlSend($Form2, "", $Input1, "{Up}")
                     If _IsPressed(28, $hDLL) then ControlSend($Form2, "", $Input1, "{Down}")
                     ControlSend($Form2, "", $Input1, "{End}")
                  EndIf
                  $LastUser = GUICtrlRead($Input1)
            EndSwitch
      EndSwitch
   EndFunc

   Func UpdateComboBox($PasteCheck="")
      If  $CheckType< 3 Then ;Not doing a AD Search
            Global $ADResults[0]
            For $i = 0 to UBound($ADArray)-1
               If $CheckType = 0 then _ArrayConcatenate($ADResults, _AD_GetObjectsInOU($ADArray[$i], "(&(&(samAccountType=805306368)(name=" & stringleft(GUICtrlRead($Input1), 1) & "*)(!UserAccountControl=514))(|(accountExpires=0)(accountExpires>=13148437849)))", 2, "name", ""), 1) ;Enabled or Not Expired
               If $CheckType = 1 then _ArrayConcatenate($ADResults, _AD_GetObjectsInOU($ADArray[$i], "(&(&(samAccountType=805306368)(name=" & stringleft(GUICtrlRead($Input1), 1) & "*)(!accountExpires=0))(|(UserAccountControl=514)(accountExpires<=13148437849)))", 2, "name", ""), 1) ;Disabled or Expired
               If $CheckType = 2 then _ArrayConcatenate($ADResults, _AD_GetObjectsInOU($ADArray[$i], "(&(samAccountType=805306368)(name=" & stringleft(GUICtrlRead($Input1), 1) & "*))", 2, "name", ""), 1) ;ALL
            Next

               ;*Extra Filter to remove non-people
               For $i=ubound($ADResults)-1 to 1 step -1
               If StringLen(StringRegExpReplace($ADResults[$i], "[^0-9]", "")) > 1 And _ArrayDelete($ADResults, $i) Then
               ElseIf Not Stringinstr($ADResults[$i], " ") And _ArrayDelete($ADResults, $i) Then
               ElseIf Not StringIsUpper(stringleft($ADResults[$i], 1)) And _ArrayDelete($ADResults, $i) Then
               ElseIf StringIsUpper(stringleft($ADResults[$i], 3)) And _ArrayDelete($ADResults, $i) Then
               ElseIf StringRegExp($ADResults[$i], "(?i)(Consultant|User|Support|Security|Admin|Test|_|Operations|Mail|Management|Cache)", 0) And _ArrayDelete($ADResults, $i) Then
               EndIf
            Next

            For $i=1 to ubound($ADResults)-1
               _GUICtrlComboBox_AddString($Input1, $ADResults[$i])
            Next
      Else
         $CheckValue = stringleft(GUICtrlRead($Input1), 1)
         For $i=1 to ubound($ADResults)-1
            If StringInStr($ADResults[$i], $CheckValue, 2, 1, 1, 1) Then _GUICtrlComboBox_AddString($Input1, $ADResults[$i])
         Next
      EndIf

            If $PasteCheck then
               For $i=0 to StringLen($PasteCheck)
                  If _GUICtrlComboBox_FindString($Input1, StringTrimRight($PasteCheck, $i)) <> -1 then ExitLoop
               Next

               If $i = StringLen($PasteCheck) Then
                  Do
                  Until _GUICtrlComboBox_DeleteString ($Input1, 0) = -1
                  Return $LineClear = GUICtrlSetState($Input3, $GUI_DISABLE)/GUICtrlSetData($Input3, "Ext")/ControlSetText($Form2, "", $Input1, "")/GUICtrlSetState($MenuUnlock, $GUI_DISABLE)
               Else
                  ControlSetText($Form2, "", $Input1, StringTrimRight($PasteCheck, $i))
               EndIf
            EndIf
      _ArraySort($ADResults)
   EndFunc

   Func __GUICtrlComboBox_AutoComplete($AutoComplete=1)
      If $AutoComplete then _GUICtrlComboBox_AutoComplete($Input1)
      $ExtachExt = _GUICtrlComboBox_FindStringExact($Input1, GUICtrlRead($Input1)) + 1
   EndFunc

   Func Test1()
      If _IsPressed("2E", $hDLL) And GUICtrlRead($Input1) <> "" And ControlSetText($Form2, "", $Input1, "") Then
         Do
         Until _GUICtrlComboBox_DeleteString ($Input1, 0) = -1
      ElseIf StringLeft(GUICtrlRead($Input1), 1) = ">" Then
      ElseIf _IsPressed(24, $hDLL) or _IsPressed(25, $hDLL) or _IsPressed(27, $hDLL) or _IsPressed(23, $hDLL) And ControlSend($Form2, "", $Input1, "{end}") Then
         $InputText = GUICtrlRead($Input1)
      ElseIf _IsPressed(01, $hDLL) Then
         If Not WinActive($Form2, "") then Return

         Local $GUI = wingetpos($Form2, ""), $MouseX = MouseGetPos(0), $MouseY = MouseGetPos(1)
            If $MouseX > $GUI[0]+$Control[0]-5 And $MouseX < $GUI[0]+$Control[0]+$Control[2]+30 And ($MouseY > $GUI[1]+$Control[1]+20 And $MouseY < $GUI[1]+$Control[1]+$Control[3]+30) then
               MouseDown("Left")
               Do
               Until sleep(10) And _IsPressed(01, $hDLL) = False
               If ControlCommand($Form2, "", $Input1, "GetSelected") <> GUICtrlRead($Input1) or ControlCommand($Form2, "", $Input1, "GetSelected") = "0" then ControlSend($Form2, "", $Input1, "{end}")
            EndIf
      EndIf
   EndFunc
#EndRegion

Ta-Daa...! Remember to be gentle all. I know format isn't the best :)

Description 

1. Only allows names that match entrys in AD (or if you make a database) into the Input. Anything that doesn't match is rejected.

2. Allows you to paste names into the Inputbox, it will also do its best to correct incorrect pastes matching closest it can find.

3. Override validation if it starts with >

Enjoy

 

**Disclaimer Names provided have been generated randomly via another website.

Edited by IanN1990

Share this post


Link to post
Share on other sites



9 hours ago, IanN1990 said:

Ta-Daa...! Remember to be gentle all. I know format isn't the best :)

looks like a lot of work but it would help us (and yourself in a couple of weeks/months) to write some inline comments/documentation what the code does. ;)

Jos


Visit the SciTE4AutoIt3 Download page for the latest versions        Beta files                                                          Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Updated Code

Now includes two Examples 

1. One for AD

1. One for Non-AD 

Edited by IanN1990

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Your code still need fixes:

>Running AU3Check (3.3.15.0)  from:C:\Program Files (x86)\AutoIt3  input:C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(197,37) : warning: $LineClear: possibly used before declaration.
                  Return $LineClear =
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(197,62) : warning: $Input3: possibly used before declaration.
                  Return $LineClear = GUICtrlSetState($Input3,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(197,176) : warning: $MenuUnlock: possibly used before declaration.
                  Return $LineClear = GUICtrlSetState($Input3, $GUI_DISABLE)/GUICtrlSetData($Input3, "Ext")/ControlSetText($Form2, "", $Input1, "")/GUICtrlSetState($MenuUnlock,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(197,37) : error: $LineClear: undeclared global variable.
                  Return $LineClear =
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(197,62) : error: $Input3: undeclared global variable.
                  Return $LineClear = GUICtrlSetState($Input3,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(197,176) : error: $MenuUnlock: undeclared global variable.
                  Return $LineClear = GUICtrlSetState($Input3, $GUI_DISABLE)/GUICtrlSetData($Input3, "Ext")/ControlSetText($Form2, "", $Input1, "")/GUICtrlSetState($MenuUnlock,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
"C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3"(143,54) : error: LoadSettingsExit(): undefined function.
                  AdlibRegister("LoadSettingsExit", 1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Users\supersonic\Desktop\AutoIt v3 Script (neu).au3 - 4 error(s), 3 warning(s)

 

Edited by supersonic

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now