Question

Checking to see if user is part of an active direcory group..

Asked by: rhawk

I am trying to check and see if the user running the program is a member of a group in Active Directory.
Using the units ActiveDs_TLB and adshelp I have come up with a function that does check if a user is in a group. The probem is that the user must be directly in the group. If the user is part of another group thatis part of the group then the user is not found. I realize I need to locate all groups under the main group and check them for users AND more groups, but the problem is I cannot seem to figure out how.

Here is the routine I have so far (there is a showmessage in it that displays the users names it finds for debugging)., Pardon it being a bit sloppy but it is a work in progress.

(This question continues so I can post 1 more code example)

function GroupMember(sGroup: String): Boolean;
var
   sUser,
   	sCall	: string;
   oUser		: IADsGroup;//IADsContainer;
   grp 		: IAdsUser;
   grps 		: IAdsMembers;
   Enum		: IEnumVariant;
   varGroup : OleVariant;
   Temp 		: LongWord;
   bMatch	: boolean;
 
begin
   sUser := ReplaceText(getUserNameEx(2), 'ste\', '');
	sCall := 'WinNT://ste/' + sGroup + ',group';
	ADsGetObject(sCall, IADsGroup, oUser);
   grps:=oUser.Members;
   bMatch := false;
     Enum := grps._NewEnum as IEnumVariant;
 
  if Enum <> nil then
    while (NOT bMatch) AND (Enum.Next(1,varGroup, Temp) = S_OK) do begin
      grp := IDispatch(varGroup) as IAdsUser;
      bMatch :=  SameText(grp.Name, sUser);
      showmessage(grp.Name);
      VariantClear(varGroup);
    end;
  result:=bM
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-04-04 at 10:23:11ID23296730
Tags

Delphi

Topics

Delphi Programming

,

Microsoft Programming

Participating Experts
1
Points
0
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. progress bar
    How can I activate progress bar while deleting file? For a nicer look,he,he....
  2. showmessage
    I am using showmessage to help me develop a program. However, I am now showing a string which is very large... The parts of the string that I want to look at are off the page and I can not get to them? Is there a scrollable version of Showmessage? If not how best can I see th...
  3. showmessage()
    hi i wanna write a message in 2 lines in Showmessage() how can i do that
  4. Tapi3 .dll won't convert to .tlb
    I am attempting to convert a Tapi3 COM .dll to a .tlb & run it as a COM Interop from C#. However, TlbImp objects to the .dll, claiming it is not a valid type library. I am using MS Visual Studio .NET Enterprise Architect running under Windows XP Pro. The Tapi3 samples I ...
  5. Difficulty using showmessage in Threads.
    I want to use Showmessage from within a Thread and, when the program arrives to execute the showmessage dialog it gives an Exception Notification with a message “ Canvas does not allow drawing” and stops the process. The showmessage does not appear. I'm using DELPHI 7. on WIN...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: rhawkPosted on 2008-04-04 at 10:25:20ID: 21283843

With the question asked, here is a vbs script that DOES do what I want, but I seem to not be able to properly convert it to a Delphi function...

Another difference is that the code here uses LDAP not NT.

' EnumGroup.vbs
' VBScript program to document members of a group.
' Reveals nested group and primary group membership.
'
' ----------------------------------------------------------------------
' Copyright (c) 2002 Richard L. Mueller
' Hilltop Lab web site - http://www.rlmueller.net
' Version 1.0 - December 10, 2002
' Version 1.1 - January 24, 2003 - Include users whose Primary Group is
'                                  any nested group.
' Version 1.2 - February 19, 2003 - Standardize Hungarian notation.
' Version 1.3 - March 11, 2003 - Remove SearchScope property.
' Version 1.4 - April 30, 2003 - Use GetInfoEx to retrieve group
'                                primaryGroupToken.
' Version 1.5 - January 25, 2004 - Modify error trapping.
'
' You have a royalty-free right to use, modify, reproduce, and
' distribute this script file in any way you find useful, provided that
' you agree that the copyright owner above has no warranty, obligations,
' or liability for such use.
 
Option Explicit
 
Dim objGroup, strDN, objMemberList
Dim adoConnection, adoCommand, objRootDSE, strDNSDomain
 
' Dictionary object to track group membership.
Set objMemberList = CreateObject("Scripting.Dictionary")
objMemberList.CompareMode = vbTextCompare
 
' Check for required argument.
If (Wscript.Arguments.Count < 1) Then
    Wscript.Echo "Required argument <Distinguished Name> " _
        & "of group missing."
    Wscript.Echo "For example:" & vbCrLf _
        & "cscript //nologo EnumGroup.vbs " _
        & """cn=Test Group,ou=Sales,dc=MyDomain,dc=com"""
    Wscript.Quit(0)
End If
 
' Bind to the group object with the LDAP provider.
strDN = Wscript.Arguments(0)
On Error Resume Next
Set objGroup = GetObject("LDAP://" & strDN)
If (Err.Number <> 0) Then
    On Error GoTo 0
    Wscript.Echo "Group not found" & vbCrLf & strDN
    Wscript.Quit(1)
End If
On Error GoTo 0
 
' Retrieve DNS domain name from RootDSE.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
Wscript.Echo "DNSDomain:" & strDNSDomain
 
' Setup ADO.
Set adoConnection = CreateObject("ADODB.Connection")
Set adoCommand = CreateObject("ADODB.Command")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
 
' Enumerate group membership.
Wscript.Echo "Members of group " & objGroup.sAMAccountName
Call EnumGroup(objGroup, "  ")
 
' Clean Up.
adoConnection.Close
Set objGroup = Nothing
Set objRootDSE = Nothing
Set adoCommand = Nothing
Set adoConnection = Nothing
 
Sub EnumGroup(ByVal objADGroup, ByVal strOffset)
    ' Recursive subroutine to enumerate group membership.
    ' objMemberList is a dictionary object with global scope.
    ' objADGroup is a group object bound with the LDAP provider.
    ' This subroutine outputs a list of group members, one member
    ' per line. Nested group members are included. Users are also
    ' included if their primary group is objADGroup. objMemberList
    ' prevents an infinite loop if nested groups are circular.
 
    Dim strFilter, strAttributes, adoRecordset, intGroupToken
    Dim objMember, strQuery, strNTName
 
    ' Retrieve "primaryGroupToken" of group.
    objADGroup.GetInfoEx Array("primaryGroupToken"), 0
    intGroupToken = objADGroup.Get("primaryGroupToken")
 
    ' Use ADO to search for users whose "primaryGroupID" matches the
    ' group "primaryGroupToken".
    strFilter = "(primaryGroupID=" & intGroupToken & ")"
    strAttributes = "sAMAccountName"
    strQuery = "<LDAP://" & strDNSDomain & ">;" & strFilter & ";" _
        & strAttributes & ";subtree"
Wscript.Echo strQuery
    adoCommand.CommandText = strQuery
    Set adoRecordset = adoCommand.Execute
    Do Until adoRecordset.EOF
        strNTName = adoRecordset.Fields("sAMAccountName").Value
        If (objMemberList.Exists(strNTName) = False) Then
            objMemberList.Add strNTName, True
            Wscript.Echo strOffset & strNTName & " (Primary)"
        Else
            Wscript.Echo strOffset & strNTName & " (Primary, Duplicate)"
        End If
        adoRecordset.MoveNext
    Loop
    adoRecordset.Close
 
    For Each objMember In objADGroup.Members
        If (objMemberList.Exists(objMember.sAMAccountName) = False) Then
            objMemberList.Add objMember.sAMAccountName, True
            If (UCase(Left(objMember.objectCategory, 8)) = "CN=GROUP") Then
                Wscript.Echo strOffset & objMember.sAMAccountName & " (Group)"
                Call EnumGroup(objMember, strOffset & "  ")
            Else
                Wscript.Echo strOffset & objMember.sAMAccountName & ": " & objMember.objectCategory
            End If
        Else
            Wscript.Echo strOffset & objMember.sAMAccountName & " (Duplicate)"
        End If
    Next
    Set objMember = Nothing
    Set adoRecordset = Nothing
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:

Select allOpen in new window

 

by: JohnjcesPosted on 2008-04-04 at 13:12:18ID: 21285279

Here is a link to a zip folder with a good example of using AD in Delphi. Checks users and other stuff.

ftp://jcitssystems.com/pub/ActiveDirectory.zip

It is all in Delphi and does in fact check users etc.

Maybe it will help!

John

PS. It takes a minute to connect so be patient.

 

by: rhawkPosted on 2008-04-04 at 15:04:44ID: 21285954

Hi Johnjces,
Not any more usefull than what I already have. In fact some of the original souce I got my start from mayhave been from that. :)
Have you done anything in AD in delphi?

Trying a new route as well I see I can run queries on the SQL Server. I would rather not do this on the sql server, but I suppose I could make the routine use an ado connection and do it there. Still, I rather know how to modify the delphi code I posted to show me groups under a group.

 

by: JohnjcesPosted on 2008-04-04 at 15:58:59ID: 21286257

Have not messed with AD much at all. Never had the need. Had the code laying around "just in case". I figured if a User was listed in AD he had rights to do whatever and those I could limit at an application level. But, I created my own application login stuff. Figured it was easier! :)

What user groups do you need to check?

Is this for SQL Server access? Or do you have users setup in SQL Server? A little confused by "run queries on the SQL Server".

John

 

by: rhawkPosted on 2008-04-07 at 06:34:03ID: 21296676

Johnjces,
I have an app that I will assign the ability to add information, update information, update some information, read only and able to generate reports, depending on the groups they belong to.
I can use MY code above to get a list of users in a group, but it is only users directly in the group. If I have a group named "GroupA" and another called "GroupB" and A has Tom, Mike, Jim and GroupB in it and B has Carol, Jane and Frank, my code only finds Tom, Mike and Jim. It wont even tell me GroupB is in GroupA, which would also solve my issue.

That VBS code I also posted will do the trick, but I have not been able to convert it to Delphi. :(

In the end if someone could just tell me how to use the NT:// and get a list of Groups within a Group my work will all come together.

 

by: JohnjcesPosted on 2008-04-07 at 19:58:30ID: 21302235

Not much help to you here. Sorry.

John

 

by: rhawkPosted on 2008-04-08 at 10:51:17ID: 21307762

I worked out how to do it with ADO and LDAP. I would rather have used ADSI and ADsGetObject call with WinNT://, but I did not want to spend any more time on this issue. Since I have come across other similiar questions to mine with no resolution, I will post my routine here. I am sure someone can write it better and tighter, and if so I am always happy for you to post your version in the thread as well. If anyone here does figure out how to do this with ADsGetObject PLEASE post it.

function GroupMember(sGroup: String;bAdminAccess: Boolean=false): Boolean;
var
  	sUser	: string;
	slGroups: TStringList; // used to prevent circular references in groups
   cnn: OleVariant;
   bFoundUser : boolean;
 	rs: OleVariant;
 
	procedure UserInGroup(sUser, sGroup: string);
   var
   	rs: OleVariant;
      i: integer;
      bc: boolean;
   begin
      // have we searched this group yet?
      if (slGroups.IndexOf(sGroup)<0) then begin
         //no, add the group to the list
         slGroups.Add(sGroup);
         rs := CreateOleObject('adodb.Recordset');
         rs := cnn.Execute('SELECT objectCategory, sAMAccountName FROM ''LDAP://OU=***,DC=****,DC=**,DC=***'' WHERE memberOf=''CN=' + sGroup + ',OU=Users,OU=***,DC=*****,DC=**,DC=***''');
         bc:=not rs.EOF;
      	if NOT rs.EOF then
            Repeat
               if SameText(rs.Fields['sAMAccountName'].Value, sUser) then
                  bFoundUser:= true
               else
                  if SameText(LeftStr(rs.Fields['objectCategory'].Value,8),'cn=group') then
                     // have a subgroup here, go check it out
                     UserInGroup(sUser, rs.Fields['sAMAccountName'].Value);
               rs.moveNext;
            Until bFoundUser OR rs.EOF;
         if bc then rs.close;
      end;
   end;
begin
   bFoundUser := false;
	sUser:= getUserNameEx(12);
   cnn := CreateOleObject('adodb.connection');
   cnn.Provider := 'ADSDSOObject';
   cnn.Open('ADs Provider');
   // verify the group even exists
   rs := CreateOleObject('adodb.Recordset');
   rs := cnn.Execute('SELECT objectCategory, sAMAccountName FROM ''LDAP://OU=***,DC=*****,DC=**,DC=***WHERE memberOf=''CN=' + sGroup + ',OU=Users,OU=***,DC=*****,DC=**,DC=***);
   if not rs.EOF then begin
      slGroups:= tStringList.Create;
      slGroups.Clear;
      slGroups.CaseSensitive:=false;
 
      if bAdminAccess then
            UserInGroup(sUser, '***********'); // put your admin group here
      if not bFoundUser then
         UserInGroup(sUser, sGroup);
      slGroups.Free;
      Result := bFoundUser;
   end
   else
   	rs.close;
	cnn.Close;
end;

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...