Skip to content

Commit

Permalink
Merge pull request KelvinTegelaar#1232 from KelvinTegelaar/dev
Browse files Browse the repository at this point in the history
Dev to release
  • Loading branch information
KelvinTegelaar authored Jan 16, 2025
2 parents 98f7f61 + 0f4549a commit fd6c112
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ Function Invoke-EditUser {
[CmdletBinding()]
param($Request, $TriggerMetadata)

$APIName = $TriggerMetadata.FunctionName
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
$ApiName = $TriggerMetadata.FunctionName
$User = $Request.headers.'x-ms-client-principal'
Write-LogMessage -user $User -API $ApiName -message 'Accessed this API' -Sev 'Debug'

$UserObj = $Request.body
if ($UserObj.id -eq '') {
Expand All @@ -32,103 +33,107 @@ Function Invoke-EditUser {
Write-Host 'PowerShell HTTP trigger function processed a request.'
#Edit the user
try {
Write-Host "$([boolean]$UserObj.mustchangepass)"
$UserprincipalName = "$($UserObj.Username ? $userobj.username :$userobj.mailNickname)@$($UserObj.Domain ? $UserObj.Domain : $UserObj.primDomain.value)"
Write-Host "$([boolean]$UserObj.MustChangePass)"
$UserPrincipalName = "$($UserObj.Username ? $UserObj.username :$UserObj.mailNickname)@$($UserObj.Domain ? $UserObj.Domain : $UserObj.primDomain.value)"
$BodyToship = [pscustomobject] @{
'givenName' = $UserObj.givenname
'givenName' = $UserObj.givenName
'surname' = $UserObj.surname
'accountEnabled' = $true
'displayName' = $UserObj.displayName
'department' = $UserObj.Department
'mailNickname' = $UserObj.Username ? $userobj.username :$userobj.mailNickname
'userPrincipalName' = $UserprincipalName
'mailNickname' = $UserObj.Username ? $UserObj.username :$UserObj.mailNickname
'userPrincipalName' = $UserPrincipalName
'usageLocation' = $UserObj.usageLocation.value ? $UserObj.usageLocation.value : $UserObj.usageLocation
'city' = $UserObj.City
'country' = $UserObj.Country
'jobtitle' = $UserObj.Jobtitle
'jobTitle' = $UserObj.jobTitle
'mobilePhone' = $UserObj.MobilePhone
'streetAddress' = $UserObj.streetAddress
'postalCode' = $UserObj.PostalCode
'companyName' = $UserObj.CompanyName
'otherMails' = @($UserObj.otherMails)
'passwordProfile' = @{
'forceChangePasswordNextSignIn' = [bool]$UserObj.MustChangePass
}
} | ForEach-Object {
$NonEmptyProperties = $_.psobject.Properties | Select-Object -ExpandProperty Name
$NonEmptyProperties = $_.PSObject.Properties | Select-Object -ExpandProperty Name
$_ | Select-Object -Property $NonEmptyProperties
}
if ($UserObj.addedAttributes) {
Write-Host 'Found added attribute'
Write-Host "Added attributes: $($UserObj.addedAttributes | ConvertTo-Json)"
$UserObj.addedAttributes.getenumerator() | ForEach-Object {
$results.add("Edited property $($_.Key) with value $($_.Value)")
$UserObj.addedAttributes.GetEnumerator() | ForEach-Object {
$null = $results.Add("Edited property $($_.Key) with value $($_.Value)")
$bodytoShip | Add-Member -NotePropertyName $_.Key -NotePropertyValue $_.Value -Force
}
}
$bodyToShip = ConvertTo-Json -Depth 10 -InputObject $BodyToship -Compress
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $userObj.tenantFilter -type PATCH -body $BodyToship -verbose
$results.add( 'Success. The user has been edited.' )
Write-LogMessage -API $APINAME -tenant ($userObj.tenantFilter) -user $request.headers.'x-ms-client-principal' -message "Edited user $($UserObj.DisplayName) with id $($UserObj.id)" -Sev 'Info'
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $UserObj.tenantFilter -type PATCH -body $BodyToship -verbose
$null = $results.Add( 'Success. The user has been edited.' )
Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "Edited user $($UserObj.DisplayName) with id $($UserObj.id)" -Sev Info
if ($UserObj.password) {
$passwordProfile = [pscustomobject]@{'passwordProfile' = @{ 'password' = $UserObj.password; 'forceChangePasswordNextSignIn' = [boolean]$UserObj.mustchangepass } } | ConvertTo-Json
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $userObj.tenantFilter -type PATCH -body $PasswordProfile -verbose
$results.add("Success. The password has been set to $($UserObj.password)")
Write-LogMessage -API $APINAME -tenant ($userObj.tenantFilter) -user $request.headers.'x-ms-client-principal' -message "Reset $($UserObj.DisplayName)'s Password" -Sev 'Info'
$passwordProfile = [pscustomobject]@{'passwordProfile' = @{ 'password' = $UserObj.password; 'forceChangePasswordNextSignIn' = [boolean]$UserObj.MustChangePass } } | ConvertTo-Json
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $UserObj.tenantFilter -type PATCH -body $PasswordProfile -verbose
$null = $results.Add("Success. The password has been set to $($UserObj.password)")
Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "Reset $($UserObj.DisplayName)'s Password" -Sev Info
}
} catch {
Write-LogMessage -API $APINAME -tenant ($userObj.tenantFilter) -user $request.headers.'x-ms-client-principal' -message "User edit API failed. $($_.Exception.Message)" -Sev 'Error'
$results.add( "Failed to edit user. $($_.Exception.Message)")
$ErrorMessage = Get-CippException -Exception $_
Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "User edit API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage
$null = $results.Add( "Failed to edit user. $($ErrorMessage.NormalizedError)")
}


#Reassign the licenses
try {

if ($licenses -or $UserObj.removeLicenses) {
$CurrentLicenses = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $userObj.tenantFilter
$CurrentLicenses = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $UserObj.tenantFilter
#if the list of skuIds in $CurrentLicenses.assignedLicenses is EXACTLY the same as $licenses, we don't need to do anything, but the order in both can be different.
if (($CurrentLicenses.assignedLicenses.skuId -join ',') -eq ($licenses -join ',') -and $UserObj.removeLicenses -eq $false) {
Write-Host "$($CurrentLicenses.assignedLicenses.skuId -join ',') $(($licenses -join ','))"
$results.add( 'Success. User license is already correct.' )
$null = $results.Add( 'Success. User license is already correct.' )
} else {
if ($UserObj.removeLicenses) {
$licResults = Set-CIPPUserLicense -userid $UserObj.id -TenantFilter $UserObj.tenantFilter -RemoveLicenses $CurrentLicenses.assignedLicenses.skuId
$results.add($licResults)
$licResults = Set-CIPPUserLicense -UserId $UserObj.id -TenantFilter $UserObj.tenantFilter -RemoveLicenses $CurrentLicenses.assignedLicenses.skuId
$null = $results.Add($licResults)
} else {
#Remove all objects from $CurrentLicenses.assignedLicenses.skuId that are in $licenses
$RemoveLicenses = $CurrentLicenses.assignedLicenses.skuId | Where-Object { $_ -notin $licenses }
$licResults = Set-CIPPUserLicense -userid $UserObj.id -TenantFilter $UserObj.tenantFilter -RemoveLicenses $RemoveLicenses -AddLicenses $licenses
$results.add($licResults)
$licResults = Set-CIPPUserLicense -UserId $UserObj.id -TenantFilter $UserObj.tenantFilter -RemoveLicenses $RemoveLicenses -AddLicenses $licenses
$null = $results.Add($licResults)
}

}
}

} catch {
Write-LogMessage -API $APINAME -tenant ($userObj.tenantFilter) -user $request.headers.'x-ms-client-principal' -message "License assign API failed. $($_.Exception.Message)" -Sev 'Error'
$results.add( "We've failed to assign the license. $($_.Exception.Message)")
$ErrorMessage = Get-CippException -Exception $_
Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "License assign API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage
$null = $results.Add( "We've failed to assign the license. $($ErrorMessage.NormalizedError)")
}

#Add Aliases, removal currently not supported.
try {
if ($Aliases) {
Write-Host ($Aliases | ConvertTo-Json)
foreach ($Alias in $Aliases) {
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $userObj.tenantFilter -type 'patch' -body "{`"mail`": `"$Alias`"}" -verbose
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $UserObj.tenantFilter -type 'patch' -body "{`"mail`": `"$Alias`"}" -Verbose
}
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $userObj.tenantFilter -type 'patch' -body "{`"mail`": `"$UserprincipalName`"}" -verbose
Write-LogMessage -API $APINAME -tenant ($userObj.tenantFilter) -user $request.headers.'x-ms-client-principal' -message "Added Aliases to $($UserObj.DisplayName)" -Sev 'Info'
$results.add( 'Success. added aliases to user.')
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $UserObj.tenantFilter -type 'patch' -body "{`"mail`": `"$UserPrincipalName`"}" -Verbose
Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "Added Aliases to $($UserObj.DisplayName)" -Sev Info
$null = $results.Add( 'Success. added aliases to user.')
}

} catch {
Write-LogMessage -API $APINAME -tenant ($userObj.tenantFilter) -user $request.headers.'x-ms-client-principal' -message "Alias API failed. $($_.Exception.Message)" -Sev 'Error'
$results.add( "Successfully edited user. The password is $password. We've failed to create the Aliases: $($_.Exception.Message)")
$ErrorMessage = Get-CippException -Exception $_
Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "Alias API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage
$null = $results.Add( "Successfully edited user. The password is $password. We've failed to create the Aliases: $($ErrorMessage.NormalizedError)")
}

if ($Request.body.CopyFrom.value) {
$CopyFrom = Set-CIPPCopyGroupMembers -ExecutingUser $request.headers.'x-ms-client-principal' -CopyFromId $Request.body.CopyFrom.value -UserID $UserprincipalName -TenantFilter $userObj.tenantFilter
$results.AddRange($CopyFrom)
$CopyFrom = Set-CIPPCopyGroupMembers -ExecutingUser $User -CopyFromId $Request.body.CopyFrom.value -UserID $UserPrincipalName -TenantFilter $UserObj.tenantFilter
$null = $results.AddRange($CopyFrom)
}

if ($AddToGroups) {
Expand All @@ -145,7 +150,7 @@ Function Invoke-EditUser {

Write-Host 'Adding to group via Add-DistributionGroupMember '
$Params = @{ Identity = $GroupID; Member = $UserObj.id; BypassSecurityGroupManagerCheck = $true }
New-ExoRequest -tenantid $userObj.tenantFilter -cmdlet 'Add-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true
$null = New-ExoRequest -tenantid $UserObj.tenantFilter -cmdlet 'Add-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true

} else {

Expand All @@ -154,25 +159,26 @@ Function Invoke-EditUser {
'@odata.id' = "https://graph.microsoft.com/beta/directoryObjects/$($UserObj.id)"
}
$UserBodyJSON = ConvertTo-Json -Compress -Depth 10 -InputObject $UserBody
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$GroupID/members/`$ref" -tenantid $userObj.tenantFilter -type POST -body $UserBodyJSON -Verbose
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$GroupID/members/`$ref" -tenantid $UserObj.tenantFilter -type POST -body $UserBodyJSON -Verbose

}

Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $userObj.tenantFilter -message "Added $($UserObj.DisplayName) to $GroupName group" -Sev 'Info'
$null = $results.add("Success. $($UserObj.DisplayName) has been added to $GroupName")
Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Added $($UserObj.DisplayName) to $GroupName group" -Sev Info
$null = $results.Add("Success. $($UserObj.DisplayName) has been added to $GroupName")
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $userObj.tenantFilter -message "Failed to add member $($UserObj.DisplayName) to $GroupName. Error:$($_.Exception.Message)" -Sev 'Error'
$null = $results.add("Failed to add member $($UserObj.DisplayName) to $GroupName : $($_.Exception.Message)")
$ErrorMessage = Get-CippException -Exception $_
Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Failed to add member $($UserObj.DisplayName) to $GroupName. Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage
$null = $results.Add("Failed to add member $($UserObj.DisplayName) to $GroupName : $($ErrorMessage.NormalizedError)")
}

}
}
if ($Request.body.setManager.value) {
$ManagerBody = [PSCustomObject]@{'@odata.id' = "https://graph.microsoft.com/beta/users/$($Request.body.setManager.value)" }
$ManagerBodyJSON = ConvertTo-Json -Compress -Depth 10 -InputObject $ManagerBody
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)/manager/`$ref" -tenantid $userObj.tenantFilter -type PUT -body $ManagerBodyJSON -Verbose
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $userObj.tenantFilter -message "Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)" -Sev 'Info'
$results.add("Success. Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)")
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)/manager/`$ref" -tenantid $UserObj.tenantFilter -type PUT -body $ManagerBodyJSON -Verbose
Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)" -Sev Info
$null = $results.Add("Success. Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)")
}

if ($RemoveFromGroups) {
Expand All @@ -189,20 +195,21 @@ Function Invoke-EditUser {

Write-Host 'Removing From group via Remove-DistributionGroupMember '
$Params = @{ Identity = $GroupID; Member = $UserObj.id; BypassSecurityGroupManagerCheck = $true }
New-ExoRequest -tenantid $userObj.tenantFilter -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true
$null = New-ExoRequest -tenantid $UserObj.tenantFilter -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true

} else {

Write-Host 'Removing From group via Graph'
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$GroupID/members/$($UserObj.id)/`$ref" -tenantid $userObj.tenantFilter -type DELETE
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$GroupID/members/$($UserObj.id)/`$ref" -tenantid $UserObj.tenantFilter -type DELETE

}

Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $userObj.tenantFilter -message "Removed $($UserObj.DisplayName) from $GroupName group" -Sev 'Info'
$null = $results.add("Success. $($UserObj.DisplayName) has been removed from $GroupName")
Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Removed $($UserObj.DisplayName) from $GroupName group" -Sev Info
$null = $results.Add("Success. $($UserObj.DisplayName) has been removed from $GroupName")
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $userObj.tenantFilter -message "Failed to remove member $($UserObj.DisplayName) from $GroupName. Error:$($_.Exception.Message)" -Sev 'Error'
$null = $results.add("Failed to remove member $($UserObj.DisplayName) from $GroupName : $($_.Exception.Message)")
$ErrorMessage = Get-CippException -Exception $_
Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Failed to remove member $($UserObj.DisplayName) from $GroupName. Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage
$null = $results.Add("Failed to remove member $($UserObj.DisplayName) from $GroupName : $($ErrorMessage.NormalizedError)")
}

}
Expand Down
7 changes: 4 additions & 3 deletions Modules/CIPPCore/Public/Set-CIPPUserLicense.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ function Set-CIPPUserLicense {
Write-Host "License body JSON: $LicenseBodyJson"

try {
$LicRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$UserId/assignLicense" -tenantid $TenantFilter -type POST -body $LicenseBodyJson -Verbose
$null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$UserId/assignLicense" -tenantid $TenantFilter -type POST -body $LicenseBodyJson -Verbose
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $TenantFilter -message "Failed to assign the license. Error: $_" -Sev 'Error'
throw "Failed to assign the license. $_"
$ErrorMessage = Get-CippException -Exception $_
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $TenantFilter -message "Failed to assign the license. Error: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage
throw "Failed to assign the license. $($ErrorMessage.NormalizedError)"
}

Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $TenantFilter -message "Assigned licenses to user $UserId. Added: $AddLicenses; Removed: $RemoveLicenses" -Sev 'Info'
Expand Down

0 comments on commit fd6c112

Please sign in to comment.