Imports System
Imports System.Text
Imports System.Collections
Imports System.DirectoryServices

Namespace Auth
    Public Class LdapAuthentication

        Public Shared Function GetGroups(ByVal username As String) As String
            Dim entry As DirectoryEntry = New DirectoryEntry(ConfigurationManager.AppSettings("ADServerName"), ConfigurationManager.AppSettings("ADGenericUser"), ConfigurationManager.AppSettings("ADGenericPassword"))
            Try
                Dim obj As Object = entry.NativeObject

                Dim search As DirectorySearcher = New DirectorySearcher(entry)
                Dim groupNames As StringBuilder = New StringBuilder()
                search.Filter = "(SAMAccountName=" + Replace(username, "CHTR\", "") + ")"
                search.PropertiesToLoad.Add("memberOf")
                Dim result As SearchResult = search.FindOne()
                If (result Is Nothing) Then
                    Return Nothing
                Else
                    Dim propertyCount As Integer = result.Properties("memberOf").Count
                    Dim dn As String
                    Dim equalsIndex, commaIndex As Integer

                    For propertyCounter As Integer = 0 To propertyCount - 1
                        dn = CStr(result.Properties("memberOf")(propertyCounter))
                        equalsIndex = dn.IndexOf("=", 1)
                        commaIndex = dn.IndexOf(",", 1)
                        If (-1 = equalsIndex) Then
                            Return Nothing
                        End If
                        groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).ToUpper)
                        groupNames.Append("|")
                    Next
                    Return groupNames.ToString
                End If
            Catch ex As Exception
                Throw New Exception("Error authenticating user. " + ex.Message)
            End Try
            Return True
        End Function
    End Class
End Namespace




