Skip to content

Commit

Permalink
Merge pull request #693 from JohnDuprey/dev
Browse files Browse the repository at this point in the history
Get-Tenants update
  • Loading branch information
JohnDuprey authored Mar 25, 2024
2 parents c86c4da + 757f778 commit 5a9461f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 48 deletions.
4 changes: 2 additions & 2 deletions Modules/CIPPCore/Public/GraphHelper/Get-ClassicAPIToken.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ function Get-ClassicAPIToken($tenantID, $Resource) {
#>
$TokenKey = '{0}-{1}' -f $TenantID, $Resource
if ($script:classictoken.$TokenKey -and [int](Get-Date -UFormat %s -Millisecond 0) -lt $script:classictoken.$TokenKey.expires_on) {
Write-Host 'Classic: cached token'
#Write-Host 'Classic: cached token'
return $script:classictoken.$TokenKey
} else {
Write-Host 'Using classic'
#Write-Host 'Using classic'
$uri = "https://login.microsoftonline.com/$($TenantID)/oauth2/token"
$Body = @{
client_id = $env:ApplicationID
Expand Down
4 changes: 2 additions & 2 deletions Modules/CIPPCore/Public/GraphHelper/Get-GraphToken.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ function Get-GraphToken($tenantid, $scope, $AsApp, $AppID, $refreshToken, $Retur

try {
if ($script:AccessTokens.$TokenKey -and [int](Get-Date -UFormat %s -Millisecond 0) -lt $script:AccessTokens.$TokenKey.expires_on -and $SkipCache -ne $true) {
Write-Host 'Graph: cached token'
#Write-Host 'Graph: cached token'
$AccessToken = $script:AccessTokens.$TokenKey
} else {
Write-Host 'Graph: new token'
#Write-Host 'Graph: new token'
$AccessToken = (Invoke-RestMethod -Method post -Uri "https://login.microsoftonline.com/$($tenantid)/oauth2/v2.0/token" -Body $Authbody -ErrorAction Stop)
$ExpiresOn = [int](Get-Date -UFormat %s -Millisecond 0) + $AccessToken.expires_in
Add-Member -InputObject $AccessToken -NotePropertyName 'expires_on' -NotePropertyValue $ExpiresOn
Expand Down
87 changes: 43 additions & 44 deletions Modules/CIPPCore/Public/GraphHelper/Get-Tenants.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -36,41 +36,54 @@ function Get-Tenants {
$LastRefresh = $false
}
if (!$LastRefresh -or $LastRefresh -lt (Get-Date).Addhours(-24).ToUniversalTime()) {
try {
Write-Host "Renewing. Cache not hit. $LastRefresh"
$TenantList = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/managedTenants/tenants?`$top=999" -tenantid $env:TenantID ) | Select-Object id, @{l = 'customerId'; e = { $_.tenantId } }, @{l = 'DefaultdomainName'; e = { [string]($_.contract.defaultDomainName) } } , @{l = 'MigratedToNewTenantAPI'; e = { $true } }, DisplayName, domains, @{n = 'delegatedPrivilegeStatus'; exp = { $_.tenantStatusInformation.delegatedPrivilegeStatus } } | Where-Object { $_.defaultDomainName -NotIn $SkipListCache.defaultDomainName -and $_.defaultDomainName -ne $null }

} catch {
Write-Host "Get-Tenants - Lighthouse Error, using contract/delegatedAdminRelationship calls. Error: $($_.Exception.Message)"
[System.Collections.Generic.List[PSCustomObject]]$BulkRequests = @(
@{
id = 'Contracts'
method = 'GET'
url = "/contracts?`$top=999"
},
@{
id = 'GDAPRelationships'
method = 'GET'
url = '/tenantRelationships/delegatedAdminRelationships'
}
)

$BulkResults = New-GraphBulkRequest -Requests $BulkRequests -tenantid $TenantFilter -NoAuthCheck:$true
$Contracts = Get-GraphBulkResultByID -Results $BulkResults -ID 'Contracts' -Value
$GDAPRelationships = Get-GraphBulkResultByID -Results $BulkResults -ID 'GDAPRelationships' -Value
# Query for active relationships
$GDAPRelationships = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships?`$filter=status eq 'active'&`$select=customer,autoExtendDuration,endDateTime"

$ContractList = $Contracts | Select-Object id, customerId, DefaultdomainName, DisplayName, domains, @{l = 'MigratedToNewTenantAPI'; e = { $true } }, @{ n = 'delegatedPrivilegeStatus'; exp = { $CustomerId = $_.customerId; if (($GDAPRelationships | Where-Object { $_.customer.tenantId -EQ $CustomerId -and $_.status -EQ 'active' } | Measure-Object).Count -gt 0) { 'delegatedAndGranularDelegetedAdminPrivileges' } else { 'delegatedAdminPrivileges' } } } | Where-Object -Property defaultDomainName -NotIn $SkipListCache.defaultDomainName
# Flatten gdap relationship
$GDAPList = foreach ($Relationship in $GDAPRelationships) {
[PSCustomObject]@{
customerId = $Relationship.customer.tenantId
displayName = $Relationship.customer.displayName
autoExtend = ($Relationship.autoExtendDuration -ne 'PT0S')
relationshipEnd = $Relationship.endDateTime
}
}

$GDAPOnlyList = $GDAPRelationships | Where-Object { $_.status -eq 'active' -and $Contracts.customerId -notcontains $_.customer.tenantId } | Select-Object id, @{l = 'customerId'; e = { $($_.customer.tenantId) } }, @{l = 'defaultDomainName'; e = { (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/findTenantInformationByTenantId(tenantId='$($_.customer.tenantId)')" -noauthcheck $true -asApp:$true -tenant $env:TenantId).defaultDomainName } }, @{l = 'MigratedToNewTenantAPI'; e = { $true } }, @{n = 'displayName'; exp = { $_.customer.displayName } }, domains, @{n = 'delegatedPrivilegeStatus'; exp = { 'granularDelegatedAdminPrivileges' } } | Where-Object { $_.defaultDomainName -NotIn $SkipListCache.defaultDomainName -and $_.defaultDomainName -ne $null } | Sort-Object -Property customerId -Unique
# Group relationships, build object for adding to tables
$ActiveRelationships = $GDAPList | Where-Object { $_.customerId -notin $SkipListCache.customerId }
$TenantList = $ActiveRelationships | Group-Object -Property customerId | ForEach-Object -Parallel {
Import-Module .\Modules\CIPPCore
$LatestRelationship = $_.Group | Sort-Object -Property relationshipEnd | Select-Object -Last 1
$AutoExtend = ($_.Group | Where-Object { $_.autoExtend -eq $true } | Measure-Object).Count -gt 0

$TenantList = @($ContractList) + @($GDAPOnlyList)
# Query domains to get default/initial
$Domains = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains' -tenantid $LatestRelationship.customerId -NoAuthCheck:$true
[PSCustomObject]@{
PartitionKey = 'Tenants'
RowKey = $_.Name
customerId = $_.Name
displayName = $LatestRelationship.displayName
relationshipEnd = $LatestRelationship.relationshipEnd
relationshipCount = $_.Count
defaultDomainName = ($Domains | Where-Object { $_.isDefault -eq $true }).id
initialDomainName = ($Domains | Where-Object { $_.isInitial -eq $true }).id
hasAutoExtend = $AutoExtend
delegatedPrivilegeStatus = 'granularDelegatedAdminPrivileges'
domains = ''
Excluded = $false
ExcludeUser = ''
ExcludeDate = ''
GraphErrorCount = 0
LastGraphError = ''
LastRefresh = (Get-Date).ToUniversalTime()
}
}
<#if (!$TenantList.customerId) {
$TenantList = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/contracts?`$top=999" -tenantid $env:TenantID ) | Select-Object id, customerId, DefaultdomainName, DisplayName, domains | Where-Object -Property defaultDomainName -NotIn $SkipListCache.defaultDomainName
}#>
$IncludedTenantsCache = [system.collections.generic.list[hashtable]]::new()

$IncludedTenantsCache = [system.collections.generic.list[object]]::new()
if ($env:PartnerTenantAvailable) {
$IncludedTenantsCache.Add(@{
# Add partner tenant if env is set
$IncludedTenantsCache.Add([PSCustomObject]@{
RowKey = $env:TenantID
PartitionKey = 'Tenants'
customerId = $env:TenantID
Expand All @@ -87,21 +100,7 @@ function Get-Tenants {
}
foreach ($Tenant in $TenantList) {
if ($Tenant.defaultDomainName -eq 'Invalid' -or !$Tenant.defaultDomainName) { continue }
$IncludedTenantsCache.Add(@{
RowKey = [string]$Tenant.customerId
PartitionKey = 'Tenants'
customerId = [string]$Tenant.customerId
defaultDomainName = [string]$Tenant.defaultDomainName
displayName = [string]$Tenant.DisplayName
delegatedPrivilegeStatus = [string]$Tenant.delegatedPrivilegeStatus
domains = ''
Excluded = $false
ExcludeUser = ''
ExcludeDate = ''
GraphErrorCount = 0
LastGraphError = ''
LastRefresh = (Get-Date).ToUniversalTime()
}) | Out-Null
$IncludedTenantsCache.Add($Tenant) | Out-Null
}

if ($IncludedTenantsCache) {
Expand Down

0 comments on commit 5a9461f

Please sign in to comment.