Skip to content

Commit 5c5d0d3

Browse files
authored
Merge pull request #253 from KelvinTegelaar/dev
[pull] dev from KelvinTegelaar:dev
2 parents 7cee017 + 1947b31 commit 5c5d0d3

File tree

4 files changed

+134
-5
lines changed

4 files changed

+134
-5
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
using namespace System.Net
2+
3+
Function Invoke-ExecAddTenant {
4+
<#
5+
.FUNCTIONALITY
6+
Entrypoint,AnyTenant
7+
.ROLE
8+
CIPP.AppSettings.ReadWrite.
9+
#>
10+
[CmdletBinding()]
11+
param($Request, $TriggerMetadata)
12+
13+
try {
14+
# Get the tenant ID from the request body
15+
$tenantId = $Request.body.tenantId
16+
$displayName = $Request.body.displayName
17+
$defaultDomainName = $Request.body.defaultDomainName
18+
19+
# Get the Tenants table
20+
$TenantsTable = Get-CippTable -tablename 'Tenants'
21+
22+
# Check if tenant already exists
23+
$ExistingTenant = Get-CIPPAzDataTableEntity @TenantsTable -Filter "PartitionKey eq 'Tenants' and RowKey eq '$tenantId'"
24+
25+
if ($ExistingTenant) {
26+
# Update existing tenant
27+
$ExistingTenant.delegatedPrivilegeStatus = 'directTenant'
28+
Add-CIPPAzDataTableEntity @TenantsTable -Entity $ExistingTenant -Force | Out-Null
29+
$Results = @{'message' = 'Successfully updated tenant.'; 'severity' = 'success' }
30+
} else {
31+
# Create new tenant entry
32+
try {
33+
# Get organization info
34+
$Organization = New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/organization' -tenantid $tenantId -NoAuthCheck:$true -ErrorAction Stop
35+
36+
if (-not $displayName) {
37+
$displayName = $Organization[0].displayName
38+
}
39+
40+
if (-not $defaultDomainName) {
41+
# Try to get domains
42+
try {
43+
$Domains = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains?$top=999' -tenantid $tenantId -NoAuthCheck:$true -ErrorAction Stop
44+
$defaultDomainName = ($Domains | Where-Object { $_.isDefault -eq $true }).id
45+
$initialDomainName = ($Domains | Where-Object { $_.isInitial -eq $true }).id
46+
} catch {
47+
# If we can't get domains, use verified domains from organization
48+
$defaultDomainName = ($Organization[0].verifiedDomains | Where-Object { $_.isDefault -eq $true }).name
49+
$initialDomainName = ($Organization[0].verifiedDomains | Where-Object { $_.isInitial -eq $true }).name
50+
}
51+
}
52+
} catch {
53+
Write-LogMessage -API 'Add-Tenant' -message "Failed to get information for tenant $tenantId - $($_.Exception.Message)" -Sev 'Critical'
54+
throw "Failed to get information for tenant $tenantId. Make sure the tenant is properly authenticated."
55+
}
56+
57+
# Create new tenant object
58+
$NewTenant = [PSCustomObject]@{
59+
PartitionKey = 'Tenants'
60+
RowKey = $tenantId
61+
customerId = $tenantId
62+
displayName = $displayName
63+
defaultDomainName = $defaultDomainName
64+
initialDomainName = $initialDomainName
65+
delegatedPrivilegeStatus = 'directTenant'
66+
domains = ''
67+
Excluded = $false
68+
ExcludeUser = ''
69+
ExcludeDate = ''
70+
GraphErrorCount = 0
71+
LastGraphError = ''
72+
RequiresRefresh = $false
73+
LastRefresh = (Get-Date).ToUniversalTime()
74+
}
75+
76+
# Add tenant to table
77+
Add-CIPPAzDataTableEntity @TenantsTable -Entity $NewTenant -Force | Out-Null
78+
$Results = @{'message' = "Successfully added tenant $tenantId to the tenant list with directTenant status."; 'severity' = 'success' }
79+
}
80+
} catch {
81+
$Results = @{'message' = "Failed to add tenant: $($_.Exception.Message)"; 'state' = 'error'; 'severity' = 'error' }
82+
}
83+
84+
# Associate values to output bindings by calling 'Push-OutputBinding'.
85+
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
86+
StatusCode = [HttpStatusCode]::OK
87+
Body = $Results
88+
})
89+
}

Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Setup/Invoke-ExecUpdateRefreshToken.ps1

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,25 @@ Function Invoke-ExecUpdateRefreshToken {
2424
$Secret.RefreshToken = $Request.body.RefreshToken
2525
} else {
2626
Write-Host "$($env:Applicationid) does not match $($Request.body.tenantId)"
27-
$secret | Add-Member -MemberType NoteProperty -Name $($Request.body.tenantId) -Value $Request.body.refreshtoken -Force
27+
$name = $Request.body.tenantId -replace '-', '_'
28+
$secret | Add-Member -MemberType NoteProperty -Name $name -Value $Request.body.refreshtoken -Force
2829
}
2930
Add-CIPPAzDataTableEntity @DevSecretsTable -Entity $Secret -Force
3031
} else {
3132
if ($env:ApplicationId -eq $Request.body.tenantId) {
3233
Set-AzKeyVaultSecret -VaultName $kv -Name 'RefreshToken' -SecretValue (ConvertTo-SecureString -String $Request.body.refreshtoken -AsPlainText -Force)
3334
} else {
34-
Set-AzKeyVaultSecret -VaultName $kv -Name $Request.body.tenantId -SecretValue (ConvertTo-SecureString -String $Request.body.refreshtoken -AsPlainText -Force)
35+
$name = $Request.body.tenantId -replace '-', '_'
36+
Set-AzKeyVaultSecret -VaultName $kv -Name $name -SecretValue (ConvertTo-SecureString -String $Request.body.refreshtoken -AsPlainText -Force)
3537
}
3638
}
3739
$InstanceId = Start-UpdatePermissionsOrchestrator #start the CPV refresh immediately while wizard still runs.
38-
$Results = @{'message' = "Successfully updated your stored authentication for $($request.body.tenantId)."; severity = 'success' }
40+
41+
42+
$Results = @{
43+
'message' = "Successfully updated your stored authentication for $($request.body.tenantId)."
44+
'tenantId' = $Request.body.tenantId
45+
}
3946
} catch {
4047
$Results = [pscustomobject]@{'Results' = "Failed. $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.message)"; severity = 'failed' }
4148
}

Modules/CIPPCore/Public/Get-CIPPAuthentication.ps1

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,18 @@ function Get-CIPPAuthentication {
1919
}
2020
}
2121
Write-Host "Got secrets from dev storage. ApplicationID: $env:ApplicationID"
22+
#Get list of tenants that have 'directTenant' set to true
23+
$tenants = Get-Tenants | Where-Object -Property delegatedPrivilegeStatus -EQ 'directTenant'
24+
if ($tenants) {
25+
Write-Host "Found $($tenants.Count) tenants with directTenant set to true"
26+
$tenants | ForEach-Object {
27+
$name = $_.customerId -replace '-', '_'
28+
if ($secret.$name) {
29+
$name = $_.customerId
30+
Set-Item -Path env:$name -Value $secret.$name -Force
31+
}
32+
}
33+
}
2234
} else {
2335
Write-Information 'Connecting to Azure'
2436
Connect-AzAccount -Identity
@@ -37,6 +49,19 @@ function Get-CIPPAuthentication {
3749
}
3850

3951
$keyvaultname = ($env:WEBSITE_DEPLOYMENT_ID -split '-')[0]
52+
#Get list of tenants that have 'directTenant' set to true
53+
$tenants = Get-Tenants | Where-Object -Property delegatedPrivilegeStatus -EQ 'directTenant'
54+
if ($tenants) {
55+
$tenants | ForEach-Object {
56+
$name = $_.tenantId -replace '-', '_'
57+
$secret = Get-AzKeyVaultSecret -VaultName $keyvaultname -Name $name -AsPlainText -ErrorAction Stop
58+
if ($secret) {
59+
#set the name back to the original tenantId
60+
$name = $_.customerId
61+
Set-Item -Path env:$name -Value $secret -Force
62+
}
63+
}
64+
}
4065
$Variables | ForEach-Object {
4166
Set-Item -Path env:$_ -Value (Get-AzKeyVaultSecret -VaultName $keyvaultname -Name $_ -AsPlainText -ErrorAction Stop) -Force
4267
}

Modules/CIPPCore/Public/GraphHelper/Get-GraphToken.ps1

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,19 @@ function Get-GraphToken($tenantid, $scope, $AsApp, $AppID, $AppSecret, $refreshT
55
#>
66
if (!$scope) { $scope = 'https://graph.microsoft.com/.default' }
77
if (!$env:SetFromProfile) { $CIPPAuth = Get-CIPPAuthentication; Write-Host 'Could not get Refreshtoken from environment variable. Reloading token.' }
8+
#If the $env:<$tenantid> is set, use that instead of the refreshtoken for all tenants.
9+
$ClientRefreshToken = Get-Item env:$tenantid -ErrorAction SilentlyContinue
10+
if ($ClientRefreshToken) {
11+
$refreshToken = $ClientRefreshToken
12+
} else {
13+
$refreshToken = $env:RefreshToken
14+
}
15+
816
$AuthBody = @{
917
client_id = $env:ApplicationID
1018
client_secret = $env:ApplicationSecret
1119
scope = $Scope
12-
refresh_token = $env:RefreshToken
20+
refresh_token = $refreshToken
1321
grant_type = 'refresh_token'
1422
}
1523
if ($asApp -eq $true) {
@@ -24,7 +32,7 @@ function Get-GraphToken($tenantid, $scope, $AsApp, $AppID, $AppSecret, $refreshT
2432
if ($null -ne $AppID -and $null -ne $refreshToken) {
2533
$AuthBody = @{
2634
client_id = $appid
27-
refresh_token = $RefreshToken
35+
refresh_token = $refreshToken
2836
scope = $Scope
2937
grant_type = 'refresh_token'
3038
}

0 commit comments

Comments
 (0)