modGetMyGroups.bas

Attribute VB_Name = "modGetMyGroups"
' ============================================================
' Copyright (c) 2025-2026 Peter Bryant (Corylus Business Systems)
'                    and  Andrew Richards (The IT Service Ltd)
' Part of VBAuth - https://vbauth.com
' Licensed under the MIT Licence - see LICENCE.txt
' This copyright notice must not be removed or altered.
' ============================================================

' ============================================================
' modGetMyGroups - VBAuth example: Get current user's AAD group memberships
' ============================================================
' Demonstrates the standard VBAuth call pattern for a GET request
' returning a paged collection of objects.
'
' Admin table record required: AppID = 5
'   Verb:        GET
'   URLPart1:    https://graph.microsoft.com/v1.0/me/memberOf
'   ScopeClaims: GroupMember.Read.All
'
' Note: returns all AAD groups (Security, Microsoft 365, Distribution)
' of which the authenticated user is a direct member.
' Handles Graph API paging automatically via @odata.nextLink.
' ============================================================

' ------------------------------------------------------------
' DEPENDENCIES - required modules in any target database:
'   modVBAuthGlobalConstants  (globals, SetEntraAPPIdValues,
'                              AcquireBearerToken)
'   JSONConverter              (Tim Hall VBA-JSON parser)
' ------------------------------------------------------------
' CALLING EXAMPLE (3 lines - no auth code required):
'   Dim strGroups As String
'   Dim lngCount  As Long
'   If GetMyGroups(strGroups, lngCount) Then
'       ' strGroups contains newline-delimited group names
'   End If

Option Compare Database
Option Explicit

Public Function GetMyGroups(ByRef strGroupList As String, _
                            ByRef lngGroupCount As Long) As Boolean
Dim http            As Object
Dim strResponse     As String
Dim objJson         As Object
Dim objGroups       As Object
Dim objGroup        As Object
Dim strNextLink     As String
Dim strURL          As String

    GetMyGroups = False
    strGroupList = ""
    lngGroupCount = 0

    On Error GoTo ErrorHandler

    intAppID = 5
    blnResult = SetEntraAPPIdValues(False, False)
    If blnResult = False Then
        'note the called function will feedback the error situation via strMessage
        Exit Function
    End If

    blnResult = AcquireBearerToken(strClientID, strTenantID, strScopeRequested)
    If blnResult = False Then
        'note the called function will feedback the error situation via strMessage
        Debug.Print "AcquireBearerToken failed: " & strMessage
        Exit Function
    End If

    ' Graph API pages results - loop through all pages via @odata.nextLink
    strURL = strGraphAPI_URL
    Do
        Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
        http.Open strGraphAPI_Verb, strURL, False
        http.setRequestHeader "Authorization", "Bearer " & strBearerToken
        http.setRequestHeader "Accept", "application/json"
        http.setTimeouts lngHTTPTimeout, lngHTTPTimeout, lngHTTPTimeout, lngHTTPTimeout
        http.Send

        Debug.Print "HTTP Status: " & http.status
        strResponse = http.ResponseText
        Debug.Print strResponse

        If http.status <> 200 Then
            strGroupList = "HTTP " & http.status & ": " & http.ResponseText
            strMessage = strGroupList
            Exit Function
        End If

        Set objJson = JSONConverter.ParseJson(strResponse)
        Set objGroups = objJson("value")

        ' Extract display name from each group object
        For Each objGroup In objGroups
            ' Only include groups that have a displayName
            If Not IsNull(objGroup("displayName")) Then
                strGroupList = strGroupList & objGroup("displayName") & vbCrLf
                lngGroupCount = lngGroupCount + 1
            End If
        Next objGroup

        ' Check for next page
        strNextLink = ""
        On Error Resume Next
        strNextLink = objJson("@odata.nextLink")
        On Error GoTo ErrorHandler

        strURL = strNextLink

    Loop While strNextLink <> ""

    ' Sort the list alphabetically for readability
    strGroupList = SortGroupList(strGroupList)

    ' Trim trailing line break
    If Len(strGroupList) > 0 Then
        strGroupList = Left(strGroupList, Len(strGroupList) - 2)
    End If

    GetMyGroups = True
    Exit Function

ErrorHandler:
    If Err.Number = -2147012894 Then
        strMessage = "The request to Microsoft Graph timed out after " & _
                     lngHTTPTimeout / 1000 & " seconds. " & _
                     "Please check your network connection and try again."
    Else
        strMessage = "Request failed: " & Err.Number & " - " & Err.Description
    End If
    MsgBox strMessage, vbCritical, "Get My Groups"
End Function

' ============================================================
' SortGroupList
' Sorts a newline-delimited list of group name strings into
' ascending alphabetical order using a simple bubble sort.
' Returns the sorted list as a single newline-delimited string.
' ============================================================
Private Function SortGroupList(strList As String) As String
' Sorts a vbCrLf-delimited list of strings alphabetically
Dim arrGroups()     As String
Dim strTemp         As String
Dim i               As Integer
Dim j               As Integer
Dim strResult       As String

    If Trim(strList) = "" Then
        SortGroupList = ""
        Exit Function
    End If

    ' Split into array, removing empty entries from trailing CrLf
    arrGroups = Split(Left(strList, Len(strList) - 2), vbCrLf)

    ' Bubble sort - acceptable for typical group counts
    For i = 0 To UBound(arrGroups) - 1
        For j = 0 To UBound(arrGroups) - 1 - i
            If StrComp(arrGroups(j), arrGroups(j + 1), vbTextCompare) > 0 Then
                strTemp = arrGroups(j)
                arrGroups(j) = arrGroups(j + 1)
                arrGroups(j + 1) = strTemp
            End If
        Next j
    Next i

    ' Reassemble
    For i = 0 To UBound(arrGroups)
        strResult = strResult & arrGroups(i) & vbCrLf
    Next i

    SortGroupList = strResult

End Function


Code language: PHP (php)
Updated on April 4, 2026