Skip to content

Commit

Permalink
Merge pull request #939 from JohnDuprey/dev
Browse files Browse the repository at this point in the history
Sharepoint functions and misc tweaks
  • Loading branch information
JohnDuprey authored Jul 5, 2024
2 parents 988c08c + b323911 commit d9495df
Show file tree
Hide file tree
Showing 11 changed files with 281 additions and 19 deletions.
6 changes: 3 additions & 3 deletions Durable_BECRun/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Write-Host "Working on $UserName"
try {
$startDate = (Get-Date).AddDays(-7)
$endDate = (Get-Date)
$auditLog = (New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Get-AdminAuditLogConfig').UnifiedAuditLogIngestionEnabled
$auditLog = (New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Get-AdminAuditLogConfig').UnifiedAuditLogIngestionEnabled
$7dayslog = if ($auditLog -eq $false) {
$ExtractResult = 'AuditLog is disabled. Cannot perform full analysis'
} else {
Expand Down Expand Up @@ -40,10 +40,10 @@ try {
Write-Host "Retrieved $($logsTenant.count) logs" -ForegroundColor Yellow
$logsTenant
} while ($LogsTenant.count % 5000 -eq 0 -and $LogsTenant.count -ne 0)
$ExtractResult = 'Succesfully extracted logs from auditlog'
$ExtractResult = 'Successfully extracted logs from auditlog'
}
Try {
$URI = "https://graph.microsoft.com/beta/auditLogs/signIns?`$filter=(userId eq '$SuspectUser')&`$top=1&`$orderby=createdDateTime desc"
$URI = "https://graph.microsoft.com/beta/auditLogs/signIns?`$filter=(userId eq '$SuspectUser')&`$top=1&`$orderby=createdDateTime desc"
$LastSignIn = New-GraphGetRequest -uri $URI -tenantid $TenantFilter -noPagination $true -verbose | Select-Object @{ Name = 'CreatedDateTime'; Expression = { $(($_.createdDateTime | Out-String) -replace '\r\n') } },
id,
@{ Name = 'AppDisplayName'; Expression = { $_.resourceDisplayName } },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Function Invoke-ExecRestoreBackup {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Created backup' -Sev 'Debug'

$body = [pscustomobject]@{
'Results' = 'Succesfully restored backup.'
'Results' = 'Successfully restored backup.'
}
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup: $($_.Exception.Message)" -Sev 'Error'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Function Invoke-ExecOffboardTenant {

$BulkResults = New-GraphBulkRequest -Requests $BulkRequests -tenantid $TenantFilter

$results.Add('Succesfully removed guest users')
$results.Add('Successfully removed guest users')
Write-LogMessage -user $ExecutingUser -API $APIName -message "CSP Guest users were removed" -Sev "Info" -tenant $TenantFilter
} else {
$results.Add('No guest users found to remove')
Expand Down Expand Up @@ -83,7 +83,7 @@ Function Invoke-ExecOffboardTenant {

try {
New-GraphPostRequest -type PATCH -body $patchContactBody -Uri "https://graph.microsoft.com/v1.0/organization/$($orgContacts.id)" -tenantid $Tenantfilter -ContentType "application/json"
$results.Add("Succesfully removed notification contacts from $($property): $(($propertyContacts | Where-Object { $domains -contains $_.Split("@")[1] }))")
$results.Add("Successfully removed notification contacts from $($property): $(($propertyContacts | Where-Object { $domains -contains $_.Split("@")[1] }))")
Write-LogMessage -user $ExecutingUser -API $APIName -message "Contacts were removed from $($property)" -Sev "Info" -tenant $TenantFilter
} catch {
$errors.Add("Failed to update property $($property): $($_.Exception.message)")
Expand All @@ -100,7 +100,7 @@ Function Invoke-ExecOffboardTenant {
$request.body.RemoveVendorApps | ForEach-Object {
try {
$delete = (New-GraphPostRequest -type 'DELETE' -Uri "https://graph.microsoft.com/v1.0/serviceprincipals/$($_.value)" -tenantid $Tenantfilter)
$results.Add("Succesfully removed app $($_.label)")
$results.Add("Successfully removed app $($_.label)")
Write-LogMessage -user $ExecutingUser -API $APIName -message "App $($_.label) was removed" -Sev "Info" -tenant $TenantFilter
} catch {
#$results.Add("Failed to removed app $($_.displayName)")
Expand All @@ -118,7 +118,7 @@ Function Invoke-ExecOffboardTenant {
$sortedArray | ForEach-Object {
try {
$delete = (New-GraphPostRequest -type 'DELETE' -Uri "https://graph.microsoft.com/v1.0/serviceprincipals/$($_.id)" -tenantid $Tenantfilter)
$results.Add("Succesfully removed app $($_.displayName)")
$results.Add("Successfully removed app $($_.displayName)")
Write-LogMessage -user $ExecutingUser -API $APIName -message "App $($_.displayName) was removed" -Sev "Info" -tenant $TenantFilter
} catch {
#$results.Add("Failed to removed app $($_.displayName)")
Expand All @@ -141,7 +141,7 @@ Function Invoke-ExecOffboardTenant {
$delegatedAdminRelationships | ForEach-Object {
try {
$terminate = (New-GraphPostRequest -type 'POST' -Uri "https://graph.microsoft.com/v1.0/tenantRelationships/delegatedAdminRelationships/$($_.id)/requests" -body '{"action":"terminate"}' -ContentType 'application/json' -tenantid $env:TenantID)
$results.Add("Succesfully terminated GDAP relationship $($_.displayName) from tenant $TenantFilter")
$results.Add("Successfully terminated GDAP relationship $($_.displayName) from tenant $TenantFilter")
Write-LogMessage -user $ExecutingUser -API $APIName -message "GDAP Relationship $($_.displayName) has been terminated" -Sev "Info" -tenant $TenantFilter
} catch {
$($_.Exception.message)
Expand All @@ -160,7 +160,7 @@ Function Invoke-ExecOffboardTenant {
# Terminate contract relationship
try {
$terminate = (New-GraphPostRequest -type 'PATCH' -body '{ "relationshipToPartner": "none" }' -Uri "https://api.partnercenter.microsoft.com/v1/customers/$TenantFilter" -ContentType 'application/json' -scope 'https://api.partnercenter.microsoft.com/user_impersonation' -tenantid $env:TenantID)
$results.Add('Succesfully terminated contract relationship')
$results.Add('Successfully terminated contract relationship')
Write-LogMessage -user $ExecutingUser -API $APIName -message "Contract relationship terminated" -Sev "Info" -tenant $TenantFilter
} catch {
#$results.Add("Failed to terminate contract relationship: $($_.Exception.message)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Function Invoke-ExecUpdateSecureScore {
}
try {
$GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/security/secureScoreControlProfiles/$($Request.body.ControlName)" -tenantid $Request.body.TenantFilter -type PATCH -Body $($Body | ConvertTo-Json -Compress)
$Results = [pscustomobject]@{'Results' = "Succesfully set control to $($body.state) " }
$Results = [pscustomobject]@{'Results' = "Successfully set control to $($body.state) " }
} catch {
$Results = [pscustomobject]@{'Results' = "Failed to set Control to $($body.state) $($_.Exception.Message)" }
}
Expand Down
27 changes: 27 additions & 0 deletions Modules/CIPPCore/Public/Get-CIPPSPOTenant.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
function Get-CIPPSPOTenant {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$TenantFilter,
[string]$SharepointPrefix
)

if (!$SharepointPrefix) {
# get sharepoint admin site
$tenantName = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/sites/root' -asApp $true -tenantid $TenantFilter).id.Split('.')[0]
} else {
$tenantName = $SharepointPrefix
}
$AdminUrl = "https://$($tenantName)-admin.sharepoint.com"

# Query tenant settings
$XML = @'
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="SharePoint Online PowerShell (16.0.24908.0)" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="106" ObjectPathId="105" /><Query Id="107" ObjectPathId="105"><Query SelectAllProperties="true"><Properties /></Query></Query></Actions><ObjectPaths><Constructor Id="105" TypeId="{268004ae-ef6b-4e9b-8425-127220d84719}" /></ObjectPaths></Request>
'@
$AdditionalHeaders = @{
'Accept' = 'application/json;odata=verbose'
}
$Results = New-GraphPostRequest -scope "$AdminURL/.default" -tenantid $TenantFilter -Uri "$AdminURL/_vti_bin/client.svc/ProcessQuery" -Type POST -Body $XML -ContentType 'text/xml' -AddedHeaders $AdditionalHeaders

$Results | Select-Object -Last 1 *, @{n = 'SharepointPrefix'; e = { $tenantName } }, @{n = 'TenantFilter'; e = { $TenantFilter } }
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ function New-GraphGetRequest {
}
} until ([string]::IsNullOrEmpty($NextURL) -or $NextURL -is [object[]] -or ' ' -eq $NextURL)
$Tenant.LastGraphError = ''
$Tenant.GraphErrorCount = 0
Update-AzDataTableEntity @TenantsTable -Entity $Tenant
return $ReturnedData
} else {
Expand Down
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function New-CIPPAPIConfig {
Write-Host "writing to Azure"
$SetAPIAuth = New-GraphPOSTRequest -type "PUT" -uri "https://management.azure.com/subscriptions/$($subscription)/resourceGroups/$ENV:WEBSITE_RESOURCE_GROUP/providers/Microsoft.Web/sites/$ENV:WEBSITE_SITE_NAME/Config/authsettingsV2?api-version=2018-11-01" -scope "https://management.azure.com/.default" -NoAuthCheck $true -body $currentBody
$null = Set-AzKeyVaultSecret -VaultName $ENV:WEBSITE_DEPLOYMENT_ID -Name 'CIPPAPIAPP' -SecretValue (ConvertTo-SecureString -String $APIApp.AppID -AsPlainText -Force)
Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message "Succesfully setup CIPP-API Access." -Sev "info"
Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message "Successfully setup CIPP-API Access." -Sev "info"
}
return @{
ApplicationID = $APIApp.AppId
Expand Down
145 changes: 145 additions & 0 deletions Modules/CIPPCore/Public/New-CIPPSharepointSite.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
function New-CIPPSharepointSite {
<#
.SYNOPSIS
Create a new SharePoint site
.DESCRIPTION
Create a new SharePoint site using the Modern REST API
.PARAMETER SiteName
The name of the site
.PARAMETER SiteDescription
The description of the site
.PARAMETER SiteOwner
The username of the site owner
.PARAMETER TemplateName
The template to use for the site. Default is Communication
.PARAMETER SiteDesign
The design to use for the site. Default is Topic
.PARAMETER WebTemplateExtensionId
The web template extension ID to use
.PARAMETER SensitivityLabel
The Purview sensitivity label to apply to the site
.PARAMETER TenantFilter
The tenant associated with the site
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[Parameter(Mandatory = $true)]
[string]$SiteName,

[Parameter(Mandatory = $true)]
[string]$SiteDescription,

[Parameter(Mandatory = $true)]
[string]$SiteOwner,

[Parameter(Mandatory = $false)]
[ValidateSet('Communication', 'Team')]
[string]$TemplateName = 'Communication',

[Parameter(Mandatory = $false)]
[ValidateSet('Topic', 'Showcase', 'Blank', 'Custom')]
[string]$SiteDesign = 'Showcase',

[Parameter(Mandatory = $false)]
[ValidatePattern('(\{|\()?[A-Za-z0-9]{4}([A-Za-z0-9]{4}\-?){4}[A-Za-z0-9]{12}(\}|\()?')]
[string]$WebTemplateExtensionId,

[Parameter(Mandatory = $false)]
[ValidatePattern('(\{|\()?[A-Za-z0-9]{4}([A-Za-z0-9]{4}\-?){4}[A-Za-z0-9]{12}(\}|\()?')]
[string]$SensitivityLabel,

[string]$Classification,

[Parameter(Mandatory = $true)]
[string]$TenantFilter
)
$tenantName = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/sites/root' -asApp $true -tenantid $TenantFilter).id.Split('.')[0]
$AdminUrl = "https://$($tenantName)-admin.sharepoint.com"
$SitePath = $SiteName -replace ' ' -replace '[^A-Za-z0-9-]'
$SiteUrl = "https://$tenantName.sharepoint.com/sites/$SitePath"




switch ($TemplateName) {
'Communication' {
$WebTemplate = 'SITEPAGEPUBLISHING#0'
}
'Team' {
$WebTemplate = 'STS#0'
}
}

$WebTemplateExtensionId = '00000000-0000-0000-0000-000000000000'
$DefaultSiteDesignIds = @( '96c933ac-3698-44c7-9f4a-5fd17d71af9e', '6142d2a0-63a5-4ba0-aede-d9fefca2c767', 'f6cc5403-0d63-442e-96c0-285923709ffc')

switch ($SiteDesign) {
'Topic' {
$SiteDesignId = '96c933ac-3698-44c7-9f4a-5fd17d71af9e'
}
'Showcase' {
$SiteDesignId = '6142d2a0-63a5-4ba0-aede-d9fefca2c767'
}
'Blank' {
$SiteDesignId = 'f6cc5403-0d63-442e-96c0-285923709ffc'
}
'Custom' {
if ($WebTemplateExtensionId -match '^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$') {
if ($WebTemplateExtensionId -notin $DefaultSiteDesignIds) {
$WebTemplateExtensionId = $SiteDesign
$SiteDesignId = '00000000-0000-0000-0000-000000000000'
} else {
$SiteDesignId = $WebTemplateExtensionId
}
} else {
$SiteDesignId = '96c933ac-3698-44c7-9f4a-5fd17d71af9e'
}
}
}

# Create the request body
$Request = @{
Title = $SiteName
Url = $SiteUrl
Lcid = 1033
ShareByEmailEnabled = $false
Description = $SiteDescription
WebTemplate = $WebTemplate
SiteDesignId = $SiteDesignId
Owner = $SiteOwner
WebTemplateExtensionId = $WebTemplateExtensionId
}

# Set the sensitivity label if provided
if ($SensitivityLabel) {
$Request.SensitivityLabel = $SensitivityLabel
}
if ($Classification) {
$Request.Classification = $Classification
}

Write-Verbose ($Request | ConvertTo-Json -Compress -Depth 10)

$body = @{
request = $Request
}

# Create the site
if ($PSCmdlet.ShouldProcess($SiteName, 'Create new SharePoint site')) {
$AddedHeaders = @{
'accept' = 'application/json;odata.metadata=none'
'odata-version' = '4.0'
}
New-GraphPostRequest -scope "$AdminUrl/.default" -uri "$AdminUrl/_api/SPSiteManager/create" -Body ($body | ConvertTo-Json -Compress -Depth 10) -tenantid $TenantFilter -ContentType 'application/json' -AddedHeaders $AddedHeaders
}
}
13 changes: 7 additions & 6 deletions Modules/CIPPCore/Public/SAMManifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
},
"requiredResourceAccess": [
{
"resourceAppId": "aeb86249-8ea3-49e2-900b-54cc8e308f85",
"resourceAccess": [
{ "id": "fc946a4f-bc4d-413b-a090-b2c86113ec4f", "type": "Scope" }
]
},
"resourceAppId": "aeb86249-8ea3-49e2-900b-54cc8e308f85",
"resourceAccess": [
{ "id": "fc946a4f-bc4d-413b-a090-b2c86113ec4f", "type": "Scope" }
]
},
{
"resourceAppId": "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd",
"resourceAccess": [
Expand Down Expand Up @@ -151,7 +151,8 @@
{ "id": "b6890674-9dd5-4e42-bb15-5af07f541ae1", "type": "Role" },
{ "id": "9e4862a5-b68f-479e-848a-4e07e25c9916", "type": "Scope" },
{ "id": "bb6f654c-d7fd-4ae3-85c3-fc380934f515", "type": "Scope" },
{ "id": "e0a7cdbb-08b0-4697-8264-0069786e9674", "type": "Scope" }
{ "id": "e0a7cdbb-08b0-4697-8264-0069786e9674", "type": "Scope" },
{ "id": "19da66cb-0fb0-4390-b071-ebc76a349482", "type": "Role" }
]
},
{
Expand Down
Loading

0 comments on commit d9495df

Please sign in to comment.