diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000000..46cc4309152a --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +local.settings.json diff --git a/.github/workflows/dev_cipp44thq.yml b/.github/workflows/dev_cipp44thq.yml new file mode 100644 index 000000000000..f21a9de0596d --- /dev/null +++ b/.github/workflows/dev_cipp44thq.yml @@ -0,0 +1,30 @@ +# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action +# More GitHub Actions for Azure: https://github.com/Azure/actions + +name: Build and deploy Powershell project to Azure Function App - cipp44thq + +on: + push: + branches: + - dev + workflow_dispatch: + +env: + AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root + +jobs: + deploy: + runs-on: windows-latest + + steps: + - name: 'Checkout GitHub Action' + uses: actions/checkout@v4 + + - name: 'Run Azure Functions Action' + uses: Azure/functions-action@v1 + id: fa + with: + app-name: 'cipp44thq' + slot-name: 'Production' + package: ${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} + publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_2EBCA6FEB5E54403AE417859C5D28817 }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 0311022a9306..a807be8c00b6 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ Cache_* Logs ExcludedTenants SendNotifications/config.json +.env diff --git a/CommunityRepos.json b/CommunityRepos.json new file mode 100644 index 000000000000..e34aafb8c821 --- /dev/null +++ b/CommunityRepos.json @@ -0,0 +1,56 @@ +[ + { + "Id": "930523724", + "Name": "CIPP-Templates", + "Description": "CIPP Community Templates", + "URL": "https://github.com/CyberDrain/CIPP-Templates", + "FullName": "CyberDrain/CIPP-Templates", + "Owner": "CyberDrain", + "Visibility": "public", + "WriteAccess": false, + "DefaultBranch": "main", + "RepoPermissions": { + "admin": false, + "maintain": false, + "push": false, + "triage": false, + "pull": true + } + }, + { + "Id": "784230225", + "Name": "ConditionalAccessBaseline", + "Description": "", + "URL": "https://github.com/j0eyv/ConditionalAccessBaseline", + "FullName": "j0eyv/ConditionalAccessBaseline", + "Owner": "j0eyv", + "Visibility": "public", + "WriteAccess": false, + "DefaultBranch": "main", + "RepoPermissions": { + "admin": false, + "maintain": false, + "push": false, + "triage": false, + "pull": true + } + }, + { + "Id": "493403016", + "Name": "OpenIntuneBaseline", + "Description": "Community-driven baseline to accelerate Intune adoption and learning.", + "URL": "https://github.com/SkipToTheEndpoint/OpenIntuneBaseline", + "FullName": "SkipToTheEndpoint/OpenIntuneBaseline", + "Owner": "SkipToTheEndpoint", + "Visibility": "public", + "WriteAccess": false, + "DefaultBranch": "main", + "RepoPermissions": { + "admin": false, + "maintain": false, + "push": false, + "triage": false, + "pull": true + } + } +] diff --git a/Config/standards.json b/Config/standards.json index 4b12a7181b10..70d9710628db 100644 --- a/Config/standards.json +++ b/Config/standards.json @@ -7,24 +7,28 @@ "docsDescription": "", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.MailContacts.GeneralContact", - "label": "General Contact" + "label": "General Contact", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.MailContacts.SecurityContact", - "label": "Security Contact" + "label": "Security Contact", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.MailContacts.MarketingContact", - "label": "Marketing Contact" + "label": "Marketing Contact", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.MailContacts.TechContact", - "label": "Technical Contact" + "label": "Technical Contact", + "required": false } ], "label": "Set contact e-mails", @@ -45,6 +49,37 @@ "powershellEquivalent": "Enable-OrganizationCustomization", "recommendedBy": ["CIS"] }, + { + "name": "standards.ProfilePhotos", + "cat": "Global Standards", + "tag": ["lowimpact"], + "helpText": "Controls whether users can set their own profile photos in Microsoft 365.", + "docsDescription": "Controls whether users can set their own profile photos in Microsoft 365. When disabled, only User and Global administrators can update profile photos for users.", + "addedComponent": [ + { + "type": "select", + "multiple": false, + "creatable": false, + "label": "Select value", + "name": "standards.ProfilePhotos.state", + "options": [ + { + "label": "Enabled", + "value": "enabled" + }, + { + "label": "Disabled", + "value": "disabled" + } + ] + } + ], + "label": "Allow users to set profile photos", + "impact": "Low Impact", + "impactColour": "info", + "powershellEquivalent": "Set-OrganizationConfig -ProfilePhotoOptions EnablePhotos and Update-MgBetaAdminPeople", + "recommendedBy": [] + }, { "name": "standards.PhishProtection", "cat": "Global Standards", @@ -69,25 +104,28 @@ "helpText": "Sets the branding for the tenant. This includes the login page, and the Office 365 portal.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.Branding.signInPageText", - "label": "Sign-in page text" + "label": "Sign-in page text", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.Branding.usernameHintText", - "label": "Username hint Text" + "label": "Username hint Text", + "required": false }, { - "type": "boolean", + "type": "switch", "name": "standards.Branding.hideAccountResetCredentials", "label": "Hide self-service password reset" }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "Visual Template", "name": "standards.Branding.layoutTemplateType", - "values": [ + "options": [ { "label": "Full-screen background", "value": "default" @@ -99,12 +137,12 @@ ] }, { - "type": "boolean", + "type": "switch", "name": "standards.Branding.isHeaderShown", "label": "Show header" }, { - "type": "boolean", + "type": "switch", "name": "standards.Branding.isFooterShown", "label": "Show footer" } @@ -186,10 +224,12 @@ "helpText": "Enables and sets Idle session timeout for Microsoft 365 to 1 hour. This policy affects most M365 web apps", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, + "creatable": false, "label": "Select value", "name": "standards.ActivityBasedTimeout.timeout", - "values": [ + "options": [ { "label": "1 Hour", "value": "01:00:00" @@ -219,6 +259,64 @@ "powershellEquivalent": "Portal or Graph API", "recommendedBy": ["CIS"] }, + { + "name": "standards.AuthMethodsSettings", + "cat": "Entra (AAD) Standards", + "tag": ["lowimpact"], + "helpText": "Configures the report suspicious activity settings and system credential preferences in the authentication methods policy.", + "docsDescription": "Controls the authentication methods policy settings for reporting suspicious activity and system credential preferences. These settings help enhance the security of authentication in your organization.", + "addedComponent": [ + { + "type": "autoComplete", + "multiple": false, + "creatable": false, + "required": false, + "name": "standards.AuthMethodsSettings.ReportSuspiciousActivity", + "label": "Report Suspicious Activity Settings", + "options": [ + { + "label": "Microsoft managed", + "value": "default" + }, + { + "label": "Enabled", + "value": "enabled" + }, + { + "label": "Disabled", + "value": "disabled" + } + ] + }, + { + "type": "autoComplete", + "multiple": false, + "creatable": false, + "required": false, + "name": "standards.AuthMethodsSettings.SystemCredential", + "label": "System Credential Preferences", + "options": [ + { + "label": "Microsoft managed", + "value": "default" + }, + { + "label": "Enabled", + "value": "enabled" + }, + { + "label": "Disabled", + "value": "disabled" + } + ] + } + ], + "label": "Configure Authentication Methods Policy Settings", + "impact": "Low Impact", + "impactColour": "info", + "powershellEquivalent": "Update-MgBetaPolicyAuthenticationMethodPolicy", + "recommendedBy": [] + }, { "name": "standards.AppDeploy", "cat": "Entra (AAD) Standards", @@ -227,7 +325,7 @@ "docsDescription": "Uses the CIPP functionality that deploys applications across an entire tenant base as a standard.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.AppDeploy.appids", "label": "Application IDs, comma separated" } @@ -285,10 +383,12 @@ "docsDescription": "Sets the Authenticator Lite state to enabled. This allows users to use the Authenticator Lite built into the Outlook app instead of the full Authenticator app.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, + "creatable": false, "label": "Select value", "name": "standards.PWcompanionAppAllowedState.state", - "values": [ + "options": [ { "label": "Enabled", "value": "enabled" @@ -353,10 +453,12 @@ "docsDescription": "Enables Temporary Password generation for the tenant.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, + "creatable": false, "label": "Select TAP Lifetime", "name": "standards.TAP.config", - "values": [ + "options": [ { "label": "Only Once", "value": "true" @@ -394,10 +496,12 @@ "helpText": "Sets the state of the Cross-tenant access setting to trust external MFA. This allows guest users to use their home tenant MFA to access your tenant.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, + "creatable": false, "label": "Select value", "name": "standards.ExternalMFATrusted.state", - "values": [ + "options": [ { "label": "Enabled", "value": "true" @@ -455,10 +559,12 @@ "docsDescription": "Sets the state of the registration campaign for the tenant. If enabled nudges users to set up the Microsoft Authenticator during sign-in.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, + "creatable": false, "label": "Select value", "name": "standards.NudgeMFA.state", - "values": [ + "options": [ { "label": "Enabled", "value": "enabled" @@ -486,7 +592,7 @@ "name": "standards.DisableM365GroupUsers", "cat": "Entra (AAD) Standards", "tag": ["lowimpact"], - "helpText": "Restricts M365 group creation to certain admin roles. This disables the ability to create Teams, Sharepoint sites, Planner, etc", + "helpText": "Restricts M365 group creation to certain admin roles. This disables the ability to create Teams, SharePoint sites, Planner, etc", "docsDescription": "Users by default are allowed to create M365 groups. This restricts M365 group creation to certain admin roles. This disables the ability to create Teams, SharePoint sites, Planner, etc", "addedComponent": [], "label": "Disable M365 Group creation by users", @@ -539,9 +645,10 @@ "helpText": "This standard disables all self service licenses and enables all exclusions", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.DisableSelfServiceLicenses.Exclusions", - "label": "License Ids to exclude from this standard" + "label": "License Ids to exclude from this standard", + "required": false } ], "label": "Disable Self Service Licensing", @@ -570,9 +677,10 @@ "docsDescription": "Requires users to get administrator consent before sharing data with applications. You can preapprove specific applications.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.OauthConsent.AllowedApps", - "label": "Allowed application IDs, comma separated" + "label": "Allowed application IDs, comma separated", + "required": false } ], "label": "Require admin consent for applications (Prevent OAuth phishing)", @@ -593,6 +701,69 @@ "powershellEquivalent": "Update-MgPolicyAuthorizationPolicy", "recommendedBy": [] }, + { + "name": "standards.GuestInvite", + "cat": "Entra (AAD) Standards", + "tag": ["mediumimpact"], + "helpText": "This setting controls who can invite guests to your directory to collaborate on resources secured by your company, such as SharePoint sites or Azure resources.", + "addedComponent": [ + { + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, + "label": "Who can send invites?", + "name": "standards.GuestInvite.allowInvitesFrom", + "options": [ + { + "label": "Everyone", + "value": "everyone" + }, + { + "label": "Admins, Guest inviters and All Members", + "value": "adminsGuestInvitersAndAllMembers" + }, + { + "label": "Admins and Guest inviters", + "value": "adminsAndGuestInviters" + }, + { + "label": "None", + "value": "none" + } + ] + } + ], + "label": "Guest Invite setting", + "impact": "Medium Impact", + "impactColour": "warning", + "powershellEquivalent": "", + "recommendedBy": [] + }, + { + "name": "standards.StaleEntraDevices", + "cat": "Entra (AAD) Standards", + "tag": ["highimpact", "CIS"], + "helpText": "Cleans up Entra devices that have not connected/signed in for the specified number of days.", + "docsDescription": "Cleans up Entra devices that have not connected/signed in for the specified number of days. First disables and later deletes the devices. More info can be found in the [Microsoft documentation](https://learn.microsoft.com/en-us/entra/identity/devices/manage-stale-devices)", + "addedComponent": [ + { + "type": "number", + "name": "standards.StaleEntraDevices.deviceAgeThreshold", + "label": "Days before stale(Dont set below 30)" + } + ], + "disabledFeatures": { + "report": false, + "warn": false, + "remediate": true + }, + "label": "Cleanup stale Entra devices", + "impact": "High Impact", + "impactColour": "danger", + "powershellEquivalent": "Remove-MgDevice, Update-MgDevice or Graph API", + "recommendedBy": [] + }, { "name": "standards.UndoOauth", "cat": "Entra (AAD) Standards", @@ -689,7 +860,7 @@ "docsDescription": "Sets the e-mail address to which outbound spam alerts are sent.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.OutBoundSpamAlert.OutboundSpamContact", "label": "Outbound spam contact" } @@ -721,10 +892,11 @@ "docsDescription": "Sets the global quarantine notification interval for the tenant. This is the time between the quarantine notification emails are sent out to users. Default is 24 hours.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.GlobalQuarantineNotifications.NotificationInterval", - "values": [ + "options": [ { "label": "4 hours", "value": "04:00:00" @@ -767,10 +939,11 @@ "docsDescription": "Sets the default Focused Inbox state for the tenant. This can be overridden by the user in their Outlook settings. For more information, see [Microsoft's documentation.](https://support.microsoft.com/en-us/office/focused-inbox-for-outlook-f445ad7f-02f4-4294-a82e-71d8964e3978)", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.FocusedInbox.state", - "values": [ + "options": [ { "label": "Enabled", "value": "enabled" @@ -796,10 +969,11 @@ "docsDescription": "Sets the default state for Cloud Message Recall for the tenant. By default this is enabled. You can read more about the feature [here.](https://techcommunity.microsoft.com/t5/exchange-team-blog/cloud-based-message-recall-in-exchange-online/ba-p/3744714)", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.CloudMessageRecall.state", - "values": [ + "options": [ { "label": "Enabled", "value": "true" @@ -862,10 +1036,11 @@ "docsDescription": "Adds or removes indicators to e-mail messages received from external senders in Outlook. You can read more about this feature on [Microsoft's Exchange Team Blog.](https://techcommunity.microsoft.com/t5/exchange-team-blog/native-external-sender-callouts-on-email-in-outlook/ba-p/2250098)", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.SpoofWarn.state", - "values": [ + "options": [ { "label": "Enabled", "value": "enabled" @@ -880,7 +1055,7 @@ "label": "Enable or disable 'external' warning in Outlook", "impact": "Low Impact", "impactColour": "info", - "powershellEquivalent": "et-ExternalInOutlook –Enabled $true or $false", + "powershellEquivalent": "et-ExternalInOutlook \u2013Enabled $true or $false", "recommendedBy": ["CIS"] }, { @@ -910,10 +1085,11 @@ "helpText": "Sets the default state for automatically turning meetings into Teams meetings for the tenant. This can be overridden by the user in Outlook.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.TeamsMeetingsByDefault.state", - "values": [ + "options": [ { "label": "Enabled", "value": "true" @@ -1019,10 +1195,11 @@ }, "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select Sharing Level", "name": "standards.calDefault.permissionlevel", - "values": [ + "options": [ { "label": "Owner - The user can create, read, edit, and delete all items in the folder, and create subfolders. The user is both folder owner and folder contact.", "value": "Owner" @@ -1089,6 +1266,18 @@ "powershellEquivalent": "Get-SharingPolicy | Set-SharingPolicy -Enabled $False", "recommendedBy": ["CIS"] }, + { + "name": "standardsAutoAddProxy", + "cat": "Exchange Standards", + "tag": ["lowimpact", "CIS"], + "helpText": "Automatically adds all available domains as a proxy address.", + "docsDescription": "Automatically finds all available domain names in the tenant, and tries to add proxyaddresses based on the users UPN to each of these.", + "addedComponent": [], + "label": "Automatically deploy proxy addresses", + "impact": "Medium Impact", + "impactColour": "warning", + "powershellEquivalent": "set-mailbox -emailaddresses @{add=$emailaddress}" + }, { "name": "standards.DisableAdditionalStorageProviders", "cat": "Exchange Standards", @@ -1109,10 +1298,11 @@ "helpText": "Sets the shorten meetings settings on a tenant level. This will shorten meetings by the selected amount of minutes. Valid values are 0 to 29. Short meetings are under 60 minutes, long meetings are over 60 minutes.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.ShortenMeetings.ShortenEventScopeDefault", - "values": [ + "options": [ { "label": "Disabled/None", "value": "None" @@ -1154,10 +1344,11 @@ "docsDescription": "", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.Bookings.state", - "values": [ + "options": [ { "label": "Enabled", "value": "true" @@ -1211,7 +1402,13 @@ "tag": ["mediumimpact"], "helpText": "Sets emails sent as and on behalf of shared mailboxes to also be stored in the shared mailbox sent items folder", "docsDescription": "This makes sure that e-mails sent from shared mailboxes or delegate mailboxes, end up in the mailbox of the shared/delegate mailbox instead of the sender, allowing you to keep replies in the same mailbox as the original e-mail.", - "addedComponent": [], + "addedComponent": [ + { + "type": "switch", + "label": "Include user mailboxes", + "name": "standards.DelegateSentItems.IncludeUserMailboxes" + } + ], "label": "Set mailbox Sent Items delegation (Sent items for shared mailboxes)", "impact": "Medium Impact", "impactColour": "warning", @@ -1239,10 +1436,11 @@ "docsDescription": "Set the state of the built-in Report button in Outlook. This gives the users the ability to report emails as spam or phish.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select value", "name": "standards.UserSubmissions.state", - "values": [ + "options": [ { "label": "Enabled", "value": "enable" @@ -1254,8 +1452,9 @@ ] }, { - "type": "input", + "type": "textField", "name": "standards.UserSubmissions.email", + "required": false, "label": "Destination email address" } ], @@ -1281,7 +1480,12 @@ { "name": "standards.EXODisableAutoForwarding", "cat": "Exchange Standards", - "tag": ["highimpact", "CIS", "mdo_autoforwardingmode", "mdo_blockmailforward"], + "tag": [ + "highimpact", + "CIS", + "mdo_autoforwardingmode", + "mdo_blockmailforward" + ], "helpText": "Disables the ability for users to automatically forward e-mails to external recipients.", "docsDescription": "Disables the ability for users to automatically forward e-mails to external recipients. This is to prevent data exfiltration. Please check if there are any legitimate use cases for this feature before implementing, like forwarding invoices and such.", "addedComponent": [], @@ -1291,6 +1495,26 @@ "powershellEquivalent": "Set-HostedOutboundSpamFilterPolicy -AutoForwardingMode 'Off'", "recommendedBy": ["CIS"] }, + { + "name": "standards.RetentionPolicyTag", + "cat": "Exchange Standards", + "tag": ["highimpact"], + "helpText": "Creates a CIPP - Deleted Items retention policy tag that permanently deletes items in the Deleted Items folder after X days.", + "docsDescription": "Creates a CIPP - Deleted Items retention policy tag that permanently deletes items in the Deleted Items folder after X days.", + "addedComponent": [ + { + "type": "number", + "name": "standards.RetentionPolicyTag.AgeLimitForRetention", + "label": "Retention Days", + "required": true + } + ], + "label": "Retention Policy, permanently delete items in Deleted Items after X days", + "impact": "High Impact", + "impactColour": "danger", + "powershellEquivalent": "Set-RetentionPolicyTag", + "recommendedBy": [] + }, { "name": "standards.QuarantineRequestAlert", "cat": "Defender Standards", @@ -1299,7 +1523,7 @@ "docsDescription": "Sets a e-mail address to alert when a User requests to release a quarantined message. This is useful for monitoring and ensuring that the correct messages are released.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.QuarantineRequestAlert.NotifyUser", "label": "E-mail to receive the alert" } @@ -1313,21 +1537,26 @@ { "name": "standards.SafeLinksPolicy", "cat": "Defender Standards", - "tag": ["lowimpact", "CIS", "mdo_safelinksforemail", "mdo_safelinksforOfficeApps"], + "tag": [ + "lowimpact", + "CIS", + "mdo_safelinksforemail", + "mdo_safelinksforOfficeApps" + ], "helpText": "This creates a safelink policy that automatically scans, tracks, and and enables safe links for Email, Office, and Teams for both external and internal senders", "addedComponent": [ { - "type": "boolean", + "type": "switch", "label": "AllowClickThrough", "name": "standards.SafeLinksPolicy.AllowClickThrough" }, { - "type": "boolean", + "type": "switch", "label": "DisableUrlRewrite", "name": "standards.SafeLinksPolicy.DisableUrlRewrite" }, { - "type": "boolean", + "type": "switch", "label": "EnableOrganizationBranding", "name": "standards.SafeLinksPolicy.EnableOrganizationBranding" } @@ -1361,34 +1590,35 @@ "default": 1 }, { - "type": "boolean", + "type": "switch", "label": "Show first contact safety tip", "name": "standards.AntiPhishPolicy.EnableFirstContactSafetyTips", "default": true }, { - "type": "boolean", + "type": "switch", "label": "Show user impersonation safety tip", "name": "standards.AntiPhishPolicy.EnableSimilarUsersSafetyTips", "default": true }, { - "type": "boolean", + "type": "switch", "label": "Show domain impersonation safety tip", "name": "standards.AntiPhishPolicy.EnableSimilarDomainsSafetyTips", "default": true }, { - "type": "boolean", + "type": "switch", "label": "Show user impersonation unusual characters safety tip", "name": "standards.AntiPhishPolicy.EnableUnusualCharactersSafetyTips", "default": true }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "If the message is detected as spoof by spoof intelligence", "name": "standards.AntiPhishPolicy.AuthenticationFailAction", - "values": [ + "options": [ { "label": "Quarantine the message", "value": "Quarantine" @@ -1400,10 +1630,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "Quarantine policy for Spoof", "name": "standards.AntiPhishPolicy.SpoofQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1419,10 +1650,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "If a message is detected as user impersonation", "name": "standards.AntiPhishPolicy.TargetedUserProtectionAction", - "values": [ + "options": [ { "label": "Move to Junk Folder", "value": "MoveToJmf" @@ -1438,10 +1670,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "Quarantine policy for user impersonation", "name": "standards.AntiPhishPolicy.TargetedUserQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1457,10 +1690,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "If a message is detected as domain impersonation", "name": "standards.AntiPhishPolicy.TargetedDomainProtectionAction", - "values": [ + "options": [ { "label": "Move to Junk Folder", "value": "MoveToJmf" @@ -1476,10 +1710,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "Quarantine policy for domain impersonation", "name": "standards.AntiPhishPolicy.TargetedDomainQuarantineTag", - "values": [ + "options": [ { "label": "DefaultFullAccessWithNotificationPolicy", "value": "DefaultFullAccessWithNotificationPolicy" @@ -1495,10 +1730,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "If Mailbox Intelligence detects an impersonated user", "name": "standards.AntiPhishPolicy.MailboxIntelligenceProtectionAction", - "values": [ + "options": [ { "label": "Move to Junk Folder", "value": "MoveToJmf" @@ -1514,10 +1750,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "Apply quarantine policy", "name": "standards.AntiPhishPolicy.MailboxIntelligenceQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1552,10 +1789,11 @@ "helpText": "This creates a Safe Attachment policy", "addedComponent": [ { - "type": "Select", - "label": "Action", - "name": "standards.SafeAttachmentPolicy.Action", - "values": [ + "type": "select", + "multiple": false, + "label": "Safe Attachment Action", + "name": "standards.SafeAttachmentPolicy.SafeAttachmentAction", + "options": [ { "label": "Allow", "value": "Allow" @@ -1571,10 +1809,11 @@ ] }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "QuarantineTag", "name": "standards.SafeAttachmentPolicy.QuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1590,14 +1829,15 @@ ] }, { - "type": "boolean", + "type": "switch", "label": "Redirect", "name": "standards.SafeAttachmentPolicy.Redirect" }, { - "type": "input", + "type": "textField", "name": "standards.SafeAttachmentPolicy.RedirectAddress", - "label": "Redirect Address" + "label": "Redirect Address", + "required": false } ], "label": "Default Safe Attachment Policy", @@ -1610,13 +1850,14 @@ "name": "standards.AtpPolicyForO365", "cat": "Defender Standards", "tag": ["lowimpact", "CIS"], - "helpText": "This creates a Atp policy that enables Defender for Office 365 for Sharepoint, OneDrive and Microsoft Teams.", + "helpText": "This creates a Atp policy that enables Defender for Office 365 for SharePoint, OneDrive and Microsoft Teams.", "addedComponent": [ { - "type": "boolean", + "type": "switch", "label": "Allow people to click through Protected View even if Safe Documents identified the file as malicious", "name": "standards.AtpPolicyForO365.AllowSafeDocsOpen", - "default": false + "default": false, + "required": false } ], "label": "Default Atp Policy For O365", @@ -1628,14 +1869,21 @@ { "name": "standards.MalwareFilterPolicy", "cat": "Defender Standards", - "tag": ["lowimpact", "CIS", "mdo_zapspam", "mdo_zapphish", "mdo_zapmalware"], + "tag": [ + "lowimpact", + "CIS", + "mdo_zapspam", + "mdo_zapphish", + "mdo_zapmalware" + ], "helpText": "This creates a Malware filter policy that enables the default File filter and Zero-hour auto purge for malware.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "FileTypeAction", "name": "standards.MalwareFilterPolicy.FileTypeAction", - "values": [ + "options": [ { "label": "Reject", "value": "Reject" @@ -1647,15 +1895,17 @@ ] }, { - "type": "input", + "type": "textField", "name": "standards.MalwareFilterPolicy.OptionalFileTypes", + "required": false, "label": "Optional File Types, Comma separated" }, { - "type": "Select", + "type": "select", + "multiple": false, "label": "QuarantineTag", "name": "standards.MalwareFilterPolicy.QuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1671,23 +1921,27 @@ ] }, { - "type": "boolean", + "type": "switch", "label": "Enable Internal Sender Admin Notifications", + "required": false, "name": "standards.MalwareFilterPolicy.EnableInternalSenderAdminNotifications" }, { - "type": "input", + "type": "textField", "name": "standards.MalwareFilterPolicy.InternalSenderAdminAddress", + "required": false, "label": "Internal Sender Admin Address" }, { - "type": "boolean", + "type": "switch", "label": "Enable External Sender Admin Notifications", + "required": false, "name": "standards.MalwareFilterPolicy.EnableExternalSenderAdminNotifications" }, { - "type": "input", + "type": "textField", "name": "standards.MalwareFilterPolicy.ExternalSenderAdminAddress", + "required": false, "label": "External Sender Admin Address" } ], @@ -1710,10 +1964,13 @@ "default": 7 }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "Spam Action", "name": "standards.SpamFilterPolicy.SpamAction", - "values": [ + "options": [ { "label": "Quarantine the message", "value": "Quarantine" @@ -1725,10 +1982,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "Spam Quarantine Tag", "name": "standards.SpamFilterPolicy.SpamQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1744,10 +2004,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "High Confidence Spam Action", "name": "standards.SpamFilterPolicy.HighConfidenceSpamAction", - "values": [ + "options": [ { "label": "Quarantine the message", "value": "Quarantine" @@ -1759,10 +2022,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "High Confidence Spam Quarantine Tag", "name": "standards.SpamFilterPolicy.HighConfidenceSpamQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1778,10 +2044,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "Bulk Spam Action", "name": "standards.SpamFilterPolicy.BulkSpamAction", - "values": [ + "options": [ { "label": "Quarantine the message", "value": "Quarantine" @@ -1793,10 +2062,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "Bulk Quarantine Tag", "name": "standards.SpamFilterPolicy.BulkQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1812,10 +2084,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "Phish Spam Action", "name": "standards.SpamFilterPolicy.PhishSpamAction", - "values": [ + "options": [ { "label": "Quarantine the message", "value": "Quarantine" @@ -1827,10 +2102,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "Phish Quarantine Tag", "name": "standards.SpamFilterPolicy.PhishQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1846,10 +2124,13 @@ ] }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "label": "High Confidence Phish Quarantine Tag", "name": "standards.SpamFilterPolicy.HighConfidencePhishQuarantineTag", - "values": [ + "options": [ { "label": "AdminOnlyAccessPolicy", "value": "AdminOnlyAccessPolicy" @@ -1896,54 +2177,63 @@ "helpText": "Sets the branding profile for the Intune Company Portal app. This is a tenant wide setting and overrules any settings set on the app level.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.displayName", - "label": "Organization name" + "label": "Organization name", + "required": false }, { - "type": "boolean", + "type": "switch", "name": "standards.intuneBrandingProfile.showLogo", "label": "Show logo" }, { - "type": "boolean", + "type": "switch", "name": "standards.intuneBrandingProfile.showDisplayNameNextToLogo", - "label": "Show organization name next to logo" + "label": "Show organization name next to logo", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.contactITName", - "label": "Contact IT name" + "label": "Contact IT name", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.contactITPhoneNumber", - "label": "Contact IT phone number" + "label": "Contact IT phone number", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.contactITEmailAddress", - "label": "Contact IT email address" + "label": "Contact IT email address", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.contactITNotes", - "label": "Contact IT notes" + "label": "Contact IT notes", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.onlineSupportSiteName", - "label": "Online support site name" + "label": "Online support site name", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.onlineSupportSiteUrl", - "label": "Online support site URL" + "label": "Online support site URL", + "required": false }, { - "type": "input", + "type": "textField", "name": "standards.intuneBrandingProfile.privacyUrl", - "label": "Privacy statement URL" + "label": "Privacy statement URL", + "required": false } ], "label": "Set Intune Company Portal branding profile", @@ -1952,6 +2242,42 @@ "powershellEquivalent": "Graph API", "recommendedBy": [] }, + { + "name": "standards.IntuneComplianceSettings", + "cat": "Intune Standards", + "tag": ["lowimpact"], + "helpText": "Sets the mark devices with no compliance policy assigned as compliance/non compliant and Compliance status validity period.", + "addedComponent": [ + { + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, + "name": "standards.IntuneComplianceSettings.secureByDefault", + "label": "Mark devices with no compliance policy as", + "options": [ + { + "label": "Compliant", + "value": "false" + }, + { + "label": "Non-Compliant", + "value": "true" + } + ] + }, + { + "type": "number", + "name": "standards.IntuneComplianceSettings.deviceComplianceCheckinThresholdDays", + "label": "Compliance status validity period (days)" + } + ], + "label": "Set Intune Compliance Settings", + "impact": "Low Impact", + "impactColour": "info", + "powershellEquivalent": "", + "recommendedBy": [] + }, { "name": "standards.intuneDeviceReg", "cat": "Intune Standards", @@ -1989,10 +2315,11 @@ "docsDescription": "When a OneDrive user gets deleted, the personal SharePoint site is saved for selected amount of time that data can be retrieved from it.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "name": "standards.DeletedUserRentention.Days", "label": "Retention time (Default 30 days)", - "values": [ + "options": [ { "label": "30 days", "value": "30" @@ -2159,10 +2486,12 @@ "helpText": "If disabled, the button Add shortcut to OneDrive will be removed and users in the tenant will no longer be able to add new shortcuts to their OneDrive. Existing shortcuts will remain functional", "addedComponent": [ { - "type": "Select", + "type": "autoComplete", + "multiple": false, + "creatable": false, "label": "Add Shortcuts To OneDrive button state", "name": "standards.DisableAddShortcutsToOneDrive.state", - "values": [ + "options": [ { "label": "Disabled", "value": "true" @@ -2187,10 +2516,12 @@ "helpText": "If disabled, users in the tenant will no longer be able to use the Sync button to sync SharePoint content on all sites. However, existing synced content will remain functional on the user's computer.", "addedComponent": [ { - "type": "Select", + "type": "autoComplete", + "multiple": false, + "creatable": false, "label": "SharePoint Sync Button state", "name": "standards.SPSyncButtonState.state", - "values": [ + "options": [ { "label": "Disabled", "value": "true" @@ -2225,13 +2556,14 @@ "name": "standards.sharingCapability", "cat": "SharePoint Standards", "tag": ["highimpact", "CIS"], - "helpText": "Sets the default sharing level for OneDrive and Sharepoint. This is a tenant wide setting and overrules any settings set on the site level", + "helpText": "Sets the default sharing level for OneDrive and SharePoint. This is a tenant wide setting and overrules any settings set on the site level", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "label": "Select Sharing Level", "name": "standards.sharingCapability.Level", - "values": [ + "options": [ { "label": "Users can share only with people in the organization. No external sharing is allowed.", "value": "disabled" @@ -2251,7 +2583,7 @@ ] } ], - "label": "Set Sharing Level for OneDrive and Sharepoint", + "label": "Set Sharing Level for OneDrive and SharePoint", "impact": "High Impact", "impactColour": "danger", "powershellEquivalent": "Update-MgBetaAdminSharepointSetting", @@ -2290,7 +2622,7 @@ "helpText": "Sets the file extensions that are excluded from syncing with OneDrive. These files will be blocked from upload. '*.' is automatically added to the extension and can be omitted.", "addedComponent": [ { - "type": "input", + "type": "textField", "name": "standards.ExcludedfileExt.ext", "label": "Extensions, Comma separated" } @@ -2332,10 +2664,11 @@ "helpText": "Restricts sharing to only users with the specified domain. This is useful for organizations that only want to share with their own domain.", "addedComponent": [ { - "type": "Select", + "type": "select", + "multiple": false, "name": "standards.sharingDomainRestriction.Mode", "label": "Limit external sharing by domains", - "values": [ + "options": [ { "label": "Off", "value": "none" @@ -2351,9 +2684,10 @@ ] }, { - "type": "input", + "type": "textField", "name": "standards.sharingDomainRestriction.Domains", - "label": "Domains to allow/block, comma separated" + "label": "Domains to allow/block, comma separated", + "required": false } ], "label": "Restrict sharing to a specific domain", @@ -2369,10 +2703,13 @@ "helpText": "Defines the CIS recommended global meeting policy for Teams. This includes AllowAnonymousUsersToJoinMeeting, AllowAnonymousUsersToStartMeeting, AutoAdmittedUsers, AllowPSTNUsersToBypassLobby, MeetingChatEnabledType, DesignatedPresenterRoleMode, AllowExternalParticipantGiveRequestControl", "addedComponent": [ { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "name": "standards.TeamsGlobalMeetingPolicy.DesignatedPresenterRoleMode", "label": "Default value of the `Who can present?`", - "values": [ + "options": [ { "label": "EveryoneUserOverride", "value": "EveryoneUserOverride" @@ -2390,6 +2727,33 @@ "value": "OrganizerOnlyUserOverride" } ] + }, + { + "type": "switch", + "name": "standards.TeamsGlobalMeetingPolicy.AllowAnonymousUsersToJoinMeeting", + "label": "Allow anonymous users to join meeting" + }, + { + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, + "name": "standards.TeamsGlobalMeetingPolicy.MeetingChatEnabledType", + "label": "Meeting chat policy", + "options": [ + { + "label": "On for everyone", + "value": "Enabled" + }, + { + "label": "On for everyone but anonymous users", + "value": "EnabledExceptAnonymous" + }, + { + "label": "Off for everyone", + "value": "Disabled" + } + ] } ], "label": "Define Global Meeting Policy for Teams", @@ -2406,7 +2770,7 @@ "docsDescription": "Teams channel email addresses are an optional feature that allows users to email the Teams channel directly.", "addedComponent": [ { - "type": "boolean", + "type": "switch", "name": "standards.TeamsEmailIntegration.AllowEmailIntoChannel", "label": "Allow channel emails" } @@ -2424,27 +2788,27 @@ "helpText": "Ensure external file sharing in Teams is enabled for only approved cloud storage services.", "addedComponent": [ { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalFileSharing.AllowGoogleDrive", "label": "Allow Google Drive" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalFileSharing.AllowShareFile", "label": "Allow ShareFile" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalFileSharing.AllowBox", "label": "Allow Box" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalFileSharing.AllowDropBox", "label": "Allow Dropbox" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalFileSharing.AllowEgnyte", "label": "Allow Egnyte" } @@ -2455,6 +2819,38 @@ "powershellEquivalent": "Set-CsTeamsClientConfiguration -AllowGoogleDrive $false -AllowShareFile $false -AllowBox $false -AllowDropBox $false -AllowEgnyte $false", "recommendedBy": ["CIS 3.0"] }, + { + "name": "standards.TeamsEnrollUser", + "cat": "Teams Standards", + "tag": ["lowimpact"], + "helpText": "Controls whether users with this policy can set the voice profile capture and enrollment through the Recognition tab in their Teams client settings.", + "docsDescription": "Controls whether users with this policy can set the voice profile capture and enrollment through the Recognition tab in their Teams client settings.", + "addedComponent": [ + { + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, + "name": "standards.TeamsEnrollUser.EnrollUserOverride", + "label": "Voice and Face Enrollment", + "options": [ + { + "label": "Disabled", + "value": "Disabled" + }, + { + "label": "Enabled", + "value": "Enabled" + } + ] + } + ], + "label": "Default voice and face enrollment", + "impact": "Low Impact", + "impactColour": "info", + "powershellEquivalent": "Set-CsTeamsMeetingPolicy -Identity Global -EnrollUserOverride $false", + "recommendedBy": [] + }, { "name": "standards.TeamsExternalAccessPolicy", "cat": "Teams Standards", @@ -2463,17 +2859,17 @@ "docsDescription": "Sets the properties of the Global external access policy. External access policies determine whether or not your users can: 1) communicate with users who have Session Initiation Protocol (SIP) accounts with a federated organization; 2) communicate with users who are using custom applications built with Azure Communication Services; 3) access Skype for Business Server over the Internet, without having to log on to your internal network; 4) communicate with users who have SIP accounts with a public instant messaging (IM) provider such as Skype; and, 5) communicate with people who are using Teams with an account that's not managed by an organization.", "addedComponent": [ { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalAccessPolicy.EnableFederationAccess", "label": "Allow communication from trusted organizations" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalAccessPolicy.EnablePublicCloudAccess", "label": "Allow user to communicate with Skype users" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsExternalAccessPolicy.EnableTeamsConsumerAccess", "label": "Allow communication with unmanaged Teams accounts" } @@ -2492,20 +2888,23 @@ "docsDescription": "Sets the properties of the Global federation configuration. Federation configuration settings determine whether or not your users can communicate with users who have SIP accounts with a federated organization.", "addedComponent": [ { - "type": "boolean", + "type": "switch", "name": "standards.TeamsFederationConfiguration.AllowTeamsConsumer", "label": "Allow users to communicate with other organizations" }, { - "type": "boolean", + "type": "switch", "name": "standards.TeamsFederationConfiguration.AllowPublicUsers", "label": "Allow users to communicate with Skype Users" }, { - "type": "Select", + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, "name": "standards.TeamsFederationConfiguration.DomainControl", "label": "Communication Mode", - "values": [ + "options": [ { "label": "Allow all external domains", "value": "AllowAllExternal" @@ -2525,9 +2924,10 @@ ] }, { - "type": "input", + "type": "textField", "name": "standards.TeamsFederationConfiguration.DomainList", - "label": "Domains, Comma separated" + "label": "Domains, Comma separated", + "required": false } ], "label": "Federation Configuration for Microsoft Teams", @@ -2535,5 +2935,424 @@ "impactColour": "warning", "powershellEquivalent": "Set-CsTenantFederationConfiguration", "recommendedBy": [] + }, + { + "name": "standards.TeamsMessagingPolicy", + "cat": "Teams Standards", + "tag": ["mediumimpact"], + "helpText": "Sets the properties of the Global messaging policy.", + "docsDescription": "Sets the properties of the Global messaging policy. Messaging policies control which chat and channel messaging features are available to users in Teams.", + "addedComponent": [ + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.AllowOwnerDeleteMessage", + "label": "Allow Owner to Delete Messages", + "default": false + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.AllowUserDeleteMessage", + "label": "Allow User to Delete Messages", + "default": true + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.AllowUserEditMessage", + "label": "Allow User to Edit Messages", + "default": true + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.AllowUserDeleteChat", + "label": "Allow User to Delete Chats", + "default": true + }, + { + "type": "autoComplete", + "required": true, + "multiple": false, + "creatable": false, + "name": "standards.TeamsMessagingPolicy.ReadReceiptsEnabledType", + "label": "Read Receipts Enabled Type", + "options": [ + { + "label": "User controlled", + "value": "UserPreference" + }, + { + "label": "Turned on for everyone", + "value": "Everyone" + }, + { + "label": "Turned off for everyone", + "value": "None" + } + ] + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.CreateCustomEmojis", + "label": "Allow Creating Custom Emojis", + "default": true + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.DeleteCustomEmojis", + "label": "Allow Deleting Custom Emojis", + "default": false + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.AllowSecurityEndUserReporting", + "label": "Allow reporting message as security concern", + "default": true + }, + { + "type": "switch", + "name": "standards.TeamsMessagingPolicy.AllowCommunicationComplianceEndUserReporting", + "label": "Allow reporting message as inappropriate content", + "default": true + } + ], + "label": "Global Messaging Policy for Microsoft Teams", + "impact": "Medium Impact", + "impactColour": "warning", + "powershellEquivalent": "Set-CsTeamsMessagingPolicy", + "recommendedBy": [] + }, + { + "name": "standards.AutopilotStatusPage", + "cat": "Device Management Standards", + "tag": ["lowimpact"], + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "helpText": "Deploy the Autopilot Status Page, which shows progress during device setup through Autopilot.", + "docsDescription": "This standard allows configuration of the Autopilot Status Page, providing users with a visual representation of the progress during device setup. It includes options like timeout, logging, and retry settings.", + "addedComponent": [ + { + "type": "number", + "name": "standards.AutopilotStatusPage.TimeOutInMinutes", + "label": "Timeout in minutes", + "default": 60 + }, + { + "type": "textField", + "name": "standards.AutopilotStatusPage.ErrorMessage", + "label": "Custom Error Message" + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.ShowProgress", + "label": "Show progress to users", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.EnableLog", + "label": "Turn on log collection", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.OBEEOnly", + "label": "Show status page only with OOBE setup", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.BlockDevice", + "label": "Block device usage during setup", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.AllowRetry", + "label": "Allow retry", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.AllowReset", + "label": "Allow reset", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotStatusPage.AllowFail", + "label": "Allow users to use device if setup fails", + "default": true + } + ], + "label": "Enable Autopilot Status Page", + "impact": "Low Impact", + "impactColour": "info", + "recommendedBy": [] + }, + { + "name": "standards.AutopilotProfile", + "cat": "Device Management Standards", + "tag": ["lowimpact"], + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "helpText": "Assign the appropriate Autopilot profile to streamline device deployment.", + "docsDescription": "This standard allows the deployment of Autopilot profiles to devices, including settings such as unique name templates, language options, and local admin privileges.", + "addedComponent": [ + { + "type": "textField", + "name": "standards.AutopilotProfile.DisplayName", + "label": "Profile Display Name" + }, + { + "type": "textField", + "name": "standards.AutopilotProfile.Description", + "label": "Profile Description" + }, + { + "type": "textField", + "name": "standards.AutopilotProfile.DeviceNameTemplate", + "label": "Unique Device Name Template" + }, + { + "type": "autoComplete", + "multiple": false, + "creatable": false, + "name": "standards.AutopilotProfile.Languages", + "label": "Languages", + "api": { + "url": "/languageList.json", + "labelField": "language", + "valueField": "tag" + } + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.CollectHash", + "label": "Convert all targeted devices to Autopilot", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.AssignToAllDevices", + "label": "Assign to all devices", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.SelfDeployingMode", + "label": "Enable Self-deploying Mode", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.HideTerms", + "label": "Hide Terms and Conditions", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.HidePrivacy", + "label": "Hide Privacy Settings", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.HideChangeAccount", + "label": "Hide Change Account Options", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.NotLocalAdmin", + "label": "Setup user as a standard user (not local admin)", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.AllowWhiteGlove", + "label": "Allow White Glove OOBE", + "default": true + }, + { + "type": "switch", + "name": "standards.AutopilotProfile.AutoKeyboard", + "label": "Automatically configure keyboard", + "default": true + } + ], + "label": "Enable Autopilot Profile", + "impact": "Low Impact", + "impactColour": "info", + "recommendedBy": [] + }, + { + "name": "standards.IntuneTemplate", + "cat": "Templates", + "label": "Intune Template", + "multiple": true, + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "impact": "High", + "helpText": "Deploy and manage Intune templates across devices.", + "addedComponent": [ + { + "type": "autoComplete", + "multiple": false, + "creatable": false, + "name": "TemplateList", + "label": "Select Intune Template", + "api": { + "url": "/api/ListIntuneTemplates", + "labelField": "Displayname", + "valueField": "GUID", + "queryKey": "languages" + } + }, + { + "name": "AssignTo", + "label": "Who should this template be assigned to?", + "type": "radio", + "options": [ + { "label": "Do not assign", "value": "On" }, + { "label": "Assign to all users", "value": "allLicensedUsers" }, + { "label": "Assign to all devices", "value": "AllDevices" }, + { + "label": "Assign to all users and devices", + "value": "AllDevicesAndUsers" + }, + { "label": "Assign to Custom Group", "value": "customGroup" } + ] + }, + { + "type": "textField", + "required": false, + "name": "customGroup", + "label": "Enter the custom group name if you selected 'Assign to Custom Group'. Wildcards are allowed." + } + ] + }, + { + "name": "standards.TransportRuleTemplate", + "label": "Transport Rule Template", + "cat": "Templates", + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "impact": "Medium", + "helpText": "Deploy transport rules to manage email flow.", + "addedComponent": [ + { + "type": "autoComplete", + "name": "transportRuleTemplate", + "label": "Select Transport Rule Template", + "api": { + "url": "/api/ListTransportRulesTemplates", + "labelField": "name", + "valueField": "GUID", + "queryKey": "ListTransportRulesTemplates" + } + } + ] + }, + { + "name": "standards.ConditionalAccessTemplate", + "label": "Conditional Access Template", + "cat": "Templates", + "multiple": true, + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "impact": "High", + "helpText": "Manage conditional access policies for better security.", + "addedComponent": [ + { + "type": "autoComplete", + "name": "TemplateList", + "multiple": false, + "label": "Select Conditional Access Template", + "api": { + "url": "/api/ListCATemplates", + "labelField": "displayName", + "valueField": "GUID", + "queryKey": "ListCATemplates" + } + }, + { + "name": "state", + "label": "What state should we deploy this template in?", + "type": "radio", + "options": [ + { "value": "donotchange", "label": "Do not change state" }, + { "value": "Enabled", "label": "Set to enabled" }, + { "value": "Disabled", "label": "Set to disabled" }, + { + "value": "enabledForReportingButNotEnforced", + "label": "Set to report only" + } + ] + } + ] + }, + { + "name": "standards.ExchangeConnectorTemplate", + "label": "Exchange Connector Template", + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "impact": "Medium", + "helpText": "Deploy and manage Exchange connectors.", + "addedComponent": [ + { + "type": "autoComplete", + "name": "exConnectorTemplate", + "label": "Select Exchange Connector Template", + "api": { + "url": "/api/ListExConnectorTemplates", + "labelField": "name", + "valueField": "GUID", + "queryKey": "ListExConnectorTemplates" + } + } + ] + }, + { + "name": "standards.GroupTemplate", + "label": "Group Template", + "multi": true, + "cat": "Templates", + "disabledFeatures": { + "report": true, + "warn": true, + "remediate": false + }, + "impact": "Medium", + "helpText": "Deploy and manage group templates.", + "addedComponent": [ + { + "type": "autoComplete", + "name": "groupTemplate", + "label": "Select Group Template", + "api": { + "url": "/api/ListGroupTemplates", + "labelField": "Displayname", + "valueField": "GUID", + "queryKey": "ListGroupTemplates" + } + } + ] } ] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000000..3db270cc69a1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,7 @@ +# To enable ssh & remote debugging on app service change the base image to the one below +# FROM mcr.microsoft.com/azure-functions/powershell:4-powershell7.2-appservice +FROM mcr.microsoft.com/azure-functions/powershell:4-powershell7.2 +ENV AzureWebJobsScriptRoot=/home/site/wwwroot \ + AzureFunctionsJobHost__Logging__Console__IsEnabled=true + +COPY . /home/site/wwwroot \ No newline at end of file diff --git a/Modules/CIPPCore/Public/Add-CIPPAlias.ps1 b/Modules/CIPPCore/Public/Add-CIPPAlias.ps1 index 68f297e4440b..f5579a06d493 100644 --- a/Modules/CIPPCore/Public/Add-CIPPAlias.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPAlias.ps1 @@ -6,7 +6,7 @@ function Add-CIPPAlias { $UserprincipalName, $TenantFilter, $APIName = 'Set Manager', - $ExecutingUser + $Headers ) try { @@ -16,10 +16,10 @@ function Add-CIPPAlias { } Write-Host "Resetting primary alias to $User" New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($user)" -tenantid $TenantFilter -type 'patch' -body "{`"mail`": `"$User`"}" -verbose - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Added alias $($Alias) to $($UserprincipalName)" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($TenantFilter) -message "Added alias $($Alias) to $($UserprincipalName)" -Sev 'Info' return ("Added Aliases: $($Aliases -join ',')") } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Failed to set alias. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($TenantFilter) -message "Failed to set alias. Error:$($_.Exception.Message)" -Sev 'Error' throw "Failed to set alias: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Add-CIPPGroupMember.ps1 b/Modules/CIPPCore/Public/Add-CIPPGroupMember.ps1 index c81175d2c9ef..455b2dcad9c4 100644 --- a/Modules/CIPPCore/Public/Add-CIPPGroupMember.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPGroupMember.ps1 @@ -1,5 +1,5 @@ function Add-CIPPGroupMember( - [string]$ExecutingUser, + $Headers, [string]$GroupType, [string]$GroupId, [string]$Member, @@ -17,11 +17,11 @@ function Add-CIPPGroupMember( $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($GroupId)" -tenantid $TenantFilter -type patch -body $addmemberbody -Verbose } $Message = "Successfully added user $($Member) to $($GroupId)." - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $Message -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message $Message -Sev 'Info' return $message } catch { $message = "Failed to add user $($Member) to $($GroupId) - $($_.Exception.Message)" - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $message -Sev 'error' -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message $message -Sev 'error' -LogData (Get-CippException -Exception $_) return $message } } diff --git a/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 b/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 index 6154119e56a4..ed2bfd4da7c0 100644 --- a/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 @@ -4,7 +4,8 @@ function Add-CIPPScheduledTask { [pscustomobject]$Task, [bool]$Hidden, $DisallowDuplicateName = $false, - [string]$SyncType = $null + [string]$SyncType = $null, + $Headers ) $Table = Get-CIPPTable -TableName 'ScheduledTasks' @@ -33,6 +34,10 @@ function Add-CIPPScheduledTask { } } + if ($Headers) { + $Parameters.Headers = $Headers | Select-Object -Property 'x-forwarded-for', 'x-ms-client-principal', 'x-ms-client-principal-idp', 'x-ms-client-principal-name' + } + $Parameters = ($Parameters | ConvertTo-Json -Depth 10 -Compress) $AdditionalProperties = [System.Collections.Hashtable]@{} foreach ($Prop in $task.AdditionalProperties) { diff --git a/Modules/CIPPCore/Public/Alerts/Get-CIPPAlertEntraLicenseUtilization.ps1 b/Modules/CIPPCore/Public/Alerts/Get-CIPPAlertEntraLicenseUtilization.ps1 new file mode 100644 index 000000000000..3d6817d1c1eb --- /dev/null +++ b/Modules/CIPPCore/Public/Alerts/Get-CIPPAlertEntraLicenseUtilization.ps1 @@ -0,0 +1,53 @@ +function Get-CIPPAlertEntraLicenseUtilization { + <# + .FUNCTIONALITY + Entrypoint + #> + [CmdletBinding()] + Param ( + [Parameter(Mandatory = $false)] + [Alias('input')] + $InputValue, + $TenantFilter + ) + try { + # Set threshold with fallback to 110% + $Threshold = if ($InputValue) { [int]$InputValue } else { 110 } + + $LicenseData = New-GraphGETRequest -uri 'https://graph.microsoft.com/beta/reports/azureADPremiumLicenseInsight' -tenantid $($TenantFilter) + $Alerts = [System.Collections.Generic.List[string]]::new() + + # Check P1 License utilization + if ($LicenseData.entitledP1LicenseCount -gt 0) { + $P1Used = $LicenseData.p1FeatureUtilizations.conditionalAccess.userCount + $P1Entitled = $LicenseData.entitledP1LicenseCount + $P1Usage = ($P1Used / $P1Entitled) * 100 + $P1Overage = $P1Used - $P1Entitled + + if ($P1Usage -gt $Threshold -and $P1Overage -ge 5) { + $Alerts.Add("P1 License utilization is at $([math]::Round($P1Usage,2))% (Using $P1Used of $P1Entitled licenses, over by $P1Overage)") + } + } + + # Check P2 License utilization + if ($LicenseData.entitledP2LicenseCount -gt 0) { + $P2Used = $LicenseData.p2FeatureUtilizations.riskBasedConditionalAccess.userCount + $P2Entitled = $LicenseData.entitledP2LicenseCount + $P2Usage = ($P2Used / $P2Entitled) * 100 + $P2Overage = $P2Used - $P2Entitled + + if ($P2Usage -gt $Threshold -and $P2Overage -ge 5) { + $Alerts.Add("P2 License utilization is at $([math]::Round($P2Usage,2))% (Using $P2Used of $P2Entitled licenses, over by $P2Overage)") + } + } + + if ($Alerts.Count -gt 0) { + $AlertData = "License Over-utilization Alert (Threshold: $Threshold%, Min Overage: 5): $($Alerts -join ' | ')" + Write-AlertTrace -cmdletName $MyInvocation.MyCommand -tenantFilter $TenantFilter -data $AlertData + } + + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -message "Failed to check license utilization: $($ErrorMessage.NormalizedError)" -API 'License Utilization Alert' -tenant $TenantFilter -sev Info -LogData $ErrorMessage + } +} diff --git a/Modules/CIPPCore/Public/Authentication/Get-CippApiAuth.ps1 b/Modules/CIPPCore/Public/Authentication/Get-CippApiAuth.ps1 new file mode 100644 index 000000000000..6d936936aa72 --- /dev/null +++ b/Modules/CIPPCore/Public/Authentication/Get-CippApiAuth.ps1 @@ -0,0 +1,29 @@ +function Get-CippApiAuth { + Param( + [string]$RGName, + [string]$FunctionAppName + ) + + if ($env:MSI_SECRET) { + Disable-AzContextAutosave -Scope Process | Out-Null + $Context = (Connect-AzAccount -Identity).Context + } else { + $Context = Get-AzContext + } + # Get subscription id + $SubscriptionId = $Context.Subscription.Id + + # Get auth settings + $AuthSettings = Invoke-AzRestMethod -Uri "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$RGName/providers/Microsoft.Web/sites/$($FunctionAppName)/config/authsettingsV2/list?api-version=2020-06-01" -ErrorAction Stop | Select-Object -ExpandProperty Content | ConvertFrom-Json + + if ($AuthSettings.properties) { + [PSCustomObject]@{ + ApiUrl = "https://$($FunctionAppName).azurewebsites.net" + TenantID = $AuthSettings.properties.identityProviders.azureActiveDirectory.registration.openIdIssuer -replace 'https://sts.windows.net/', '' -replace '/v2.0', '' + ClientIDs = $AuthSettings.properties.identityProviders.azureActiveDirectory.validation.defaultAuthorizationPolicy.allowedApplications + Enabled = $AuthSettings.properties.identityProviders.azureActiveDirectory.enabled + } + } else { + throw 'No auth settings found' + } +} diff --git a/Modules/CIPPCore/Public/Authentication/Get-CippApiClient.ps1 b/Modules/CIPPCore/Public/Authentication/Get-CippApiClient.ps1 new file mode 100644 index 000000000000..ce038d763729 --- /dev/null +++ b/Modules/CIPPCore/Public/Authentication/Get-CippApiClient.ps1 @@ -0,0 +1,43 @@ +function Get-CippApiClient { + <# + .SYNOPSIS + Get the API client details + .DESCRIPTION + This function retrieves the API client details + .PARAMETER AppId + The AppId of the API client + .EXAMPLE + Get-CippApiClient -AppId 'cipp-api' + #> + [CmdletBinding()] + param ( + $AppId + ) + + $Table = Get-CIPPTable -TableName 'ApiClients' + if ($AppId) { + $Table.Filter = "RowKey eq '$AppId'" + } + $Apps = Get-CIPPAzDataTableEntity @Table + $Apps = foreach ($Client in $Apps) { + $Client = $Client | Select-Object -Property @{Name = 'ClientId'; Expression = { $_.RowKey } }, AppName, Role, IPRange, Enabled + + if (!$Client.Role) { + $Client.Role = $null + } + + if ($Client.IPRange) { + try { + $IPRange = @($Client.IPRange | ConvertFrom-Json -ErrorAction Stop) + if (($IPRange | Measure-Object).Count -eq 0) { @('Any') } + $Client.IPRange = $IPRange + } catch { + $Client.IPRange = @('Any') + } + } else { + $Client.IPRange = @('Any') + } + $Client + } + return $Apps +} diff --git a/Modules/CIPPCore/Public/Authentication/New-CIPPAPIConfig.ps1 b/Modules/CIPPCore/Public/Authentication/New-CIPPAPIConfig.ps1 new file mode 100644 index 000000000000..50a36af97418 --- /dev/null +++ b/Modules/CIPPCore/Public/Authentication/New-CIPPAPIConfig.ps1 @@ -0,0 +1,118 @@ +function New-CIPPAPIConfig { + + [CmdletBinding(SupportsShouldProcess)] + param ( + $APIName = 'CIPP API Config', + $Headers, + [switch]$ResetSecret, + [string]$AppName, + [string]$AppId + ) + + try { + if ($AppId) { + $APIApp = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/applications(appid='$($AppId)')" -NoAuthCheck $true + } else { + $CreateBody = @{ + api = @{ + oauth2PermissionScopes = @( + @{ + adminConsentDescription = 'Allow the application to access CIPP-API on behalf of the signed-in user.' + adminConsentDisplayName = 'Access CIPP-API' + id = 'ba7ffeff-96ea-4ac4-9822-1bcfee9adaa4' + isEnabled = $true + type = 'User' + userConsentDescription = 'Allow the application to access CIPP-API on your behalf.' + userConsentDisplayName = 'Access CIPP-API' + value = 'user_impersonation' + } + ) + } + displayName = $AppName + requiredResourceAccess = @( + @{ + resourceAccess = @( + @{ + id = 'e1fe6dd8-ba31-4d61-89e7-88639da4683d' + type = 'Scope' + } + ) + resourceAppId = '00000003-0000-0000-c000-000000000000' + } + ) + signInAudience = 'AzureADMyOrg' + web = @{ + homePageUrl = 'https://cipp.app' + implicitGrantSettings = @{ + enableAccessTokenIssuance = $false + enableIdTokenIssuance = $true + } + redirectUris = @("https://$($ENV:Website_hostname)/.auth/login/aad/callback") + } + } | ConvertTo-Json -Depth 10 -Compress + + if ($PSCmdlet.ShouldProcess($AppName, 'Create API App')) { + Write-Information 'Creating app' + $APIApp = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/applications' -NoAuthCheck $true -type POST -body $CreateBody + Write-Information 'Creating password' + $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" + Write-Information 'Adding App URL' + $APIIdUrl = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)" -NoAuthCheck $true -type PATCH -body "{`"identifierUris`":[`"api://$($APIApp.appId)`"]}" + Write-Information 'Adding serviceprincipal' + $ServicePrincipal = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/serviceprincipals' -NoAuthCheck $true -type POST -body "{`"accountEnabled`":true,`"appId`":`"$($APIApp.appId)`",`"displayName`":`"$AppName`",`"tags`":[`"WindowsAzureActiveDirectoryIntegratedApp`",`"AppServiceIntegratedApp`"]}" + Write-LogMessage -headers $Headers -API $APINAME -tenant 'None '-message "Created CIPP-API App with name '$($APIApp.displayName)'." -Sev 'info' + } + } + if ($ResetSecret.IsPresent -and $APIApp) { + if ($PSCmdlet.ShouldProcess($APIApp.displayName, 'Reset API Secret')) { + Write-Information 'Removing all old passwords' + $Requests = @( + @{ + id = 'removeOldPasswords' + method = 'PATCH' + url = "applications/$($APIApp.id)/" + headers = @{ + 'Content-Type' = 'application/json' + } + body = @{ + passwordCredentials = @() + } + }, + @{ + id = 'addNewPassword' + method = 'POST' + url = "applications/$($APIApp.id)/addPassword" + headers = @{ + 'Content-Type' = 'application/json' + } + body = @{ + passwordCredential = @{ + displayName = 'Generated by API Setup' + } + } + dependsOn = @('removeOldPasswords') + } + ) + $BatchResponse = New-GraphBulkRequest -tenantid $env:TenantID -NoAuthCheck $true -asapp $true -Requests $Requests + $APIPassword = $BatchResponse | Where-Object { $_.id -eq 'addNewPassword' } | Select-Object -ExpandProperty body + Write-LogMessage -headers $Headers -API $APINAME -tenant 'None '-message "Reset CIPP-API Password for '$($APIApp.displayName)'." -Sev 'info' + } + } + + return @{ + AppName = $APIApp.displayName + ApplicationID = $APIApp.appId + ApplicationSecret = $APIPassword.secretText + Results = $Results + } + + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-Information ($ErrorMessage | ConvertTo-Json -Depth 10) + Write-LogMessage -headers $Headers -API $APINAME -tenant 'None' -message "Failed to setup CIPP-API Access: $($ErrorMessage.NormalizedError) Linenumber: $($_.InvocationInfo.ScriptLineNumber)" -Sev 'Error' -LogData $ErrorMessage + return @{ + Results = "Failed to setup CIPP-API Access: $($ErrorMessage.NormalizedError)" + } + + } +} diff --git a/Modules/CIPPCore/Public/Authentication/Set-CippApiAuth.ps1 b/Modules/CIPPCore/Public/Authentication/Set-CippApiAuth.ps1 new file mode 100644 index 000000000000..3a809dffee09 --- /dev/null +++ b/Modules/CIPPCore/Public/Authentication/Set-CippApiAuth.ps1 @@ -0,0 +1,72 @@ +function Set-CippApiAuth { + [CmdletBinding(SupportsShouldProcess)] + Param( + [string]$RGName, + [string]$FunctionAppName, + [string]$TenantId, + [string[]]$ClientIds + ) + + if ($env:MSI_SECRET) { + Disable-AzContextAutosave -Scope Process | Out-Null + $Context = (Connect-AzAccount -Identity).Context + } else { + $Context = Get-AzContext + } + # Get subscription id + $SubscriptionId = $Context.Subscription.Id + + # Get auth settings + $AuthSettings = Invoke-AzRestMethod -Uri "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$RGName/providers/Microsoft.Web/sites/$($FunctionAppName)/config/authsettingsV2/list?api-version=2020-06-01" | Select-Object -ExpandProperty Content | ConvertFrom-Json + + # Set allowed audiences + $AllowedAudiences = foreach ($ClientId in $ClientIds) { + "api://$ClientId" + } + + if (!$AllowedAudiences) { $AllowedAudiences = @() } + if (!$ClientIds) { $ClientIds = @() } + + # Set auth settings + + if (($ClientIds | Measure-Object).Count -gt 0) { + $AuthSettings.properties.identityProviders.azureActiveDirectory = @{ + enabled = $true + registration = @{ + clientId = $ClientIds[0] ?? $ClientIds + openIdIssuer = "https://sts.windows.net/$TenantID/v2.0" + } + validation = @{ + allowedAudiences = @($AllowedAudiences) + defaultAuthorizationPolicy = @{ + allowedApplications = @($ClientIds) + } + } + } + } else { + $AuthSettings.properties.identityProviders.azureActiveDirectory = @{ + enabled = $false + registration = @{} + validation = @{} + } + } + + $AuthSettings.properties.globalValidation = @{ + unauthenticatedClientAction = 'Return401' + } + $AuthSettings.properties.login = @{ + tokenStore = @{ + enabled = $true + tokenRefreshExtensionHours = 72 + } + } + + if ($PSCmdlet.ShouldProcess('Update auth settings')) { + # Update auth settings + $null = Invoke-AzRestMethod -Uri "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$RGName/providers/Microsoft.Web/sites/$($FunctionAppName)/config/authsettingsV2?api-version=2020-06-01" -Method PUT -Payload ($AuthSettings | ConvertTo-Json -Depth 10) + } + + if ($PSCmdlet.ShouldProcess('Update allowed tenants')) { + $null = Update-AzFunctionAppSetting -Name $FunctionAppName -ResourceGroupName $RGName -AppSetting @{ 'WEBSITE_AUTH_AAD_ALLOWED_TENANTS' = $TenantId } + } +} diff --git a/Modules/CIPPCore/Public/Authentication/Test-CIPPAccess.ps1 b/Modules/CIPPCore/Public/Authentication/Test-CIPPAccess.ps1 index aa12f2741414..2e0ad55e9807 100644 --- a/Modules/CIPPCore/Public/Authentication/Test-CIPPAccess.ps1 +++ b/Modules/CIPPCore/Public/Authentication/Test-CIPPAccess.ps1 @@ -12,27 +12,40 @@ function Test-CIPPAccess { # Check help for role $APIRole = $Help.Role - if (!$Request.Headers.'x-ms-client-principal' -or ($Request.Headers.'x-ms-client-principal-id' -and $Request.Headers.'x-ms-client-principal-idp' -eq 'aad')) { + if ($Request.Headers.'x-ms-client-principal-idp' -eq 'aad' -and $Request.Headers.'x-ms-client-principal-name' -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') { # Direct API Access + $ForwardedFor = $Request.Headers.'x-forwarded-for' -split ',' | Select-Object -First 1 $IPRegex = '^(?(?:\d{1,3}(?:\.\d{1,3}){3}|\[[0-9a-fA-F:]+\]|[0-9a-fA-F:]+))(?::\d+)?$' - $IPAddress = $Request.Headers.'x-forwarded-for' -replace $IPRegex, '$1' -replace '[\[\]]', '' - Write-Information "API Access: AppId=$($Request.Headers.'x-ms-client-principal-id') IP=$IPAddress" + $IPAddress = $ForwardedFor -replace $IPRegex, '$1' -replace '[\[\]]', '' - # TODO: Implement API Client support, create Get-CippApiClient function - <#$Client = Get-CippApiClient -AppId $Request.Headers.'x-ms-client-principal-id' + $Client = Get-CippApiClient -AppId $Request.Headers.'x-ms-client-principal-name' if ($Client) { - if ($Client.AllowedIPs -contains $IPAddress -or $Client.AllowedIPs -contains 'All')) { - if ($Client.CustomRoles) { - $CustomRoles = @($Client.CustomRoles) + Write-Information "API Access: AppName=$($Client.AppName), AppId=$($Request.Headers.'x-ms-client-principal-name'), IP=$IPAddress" + $IPMatched = $false + if ($Client.IPRange -notcontains 'Any') { + foreach ($Range in $Client.IPRange) { + if ($IPaddress -eq $Range -or (Test-IpInRange -IPAddress $IPAddress -Range $Range)) { + $IPMatched = $true + break + } + } + } else { + $IPMatched = $true + } + + if ($IPMatched) { + if ($Client.Role) { + $CustomRoles = @($Client.Role) } else { - $CustomRoles = @('CIPP-API') + $CustomRoles = @('cipp-api') } } else { throw 'Access to this CIPP API endpoint is not allowed, the API Client does not have the required permission' } - } else { #> - $CustomRoles = @('cipp-api') - # } + } else { + $CustomRoles = @('cipp-api') + Write-Information "API Access: AppId=$($Request.Headers.'x-ms-client-principal-name'), IP=$IPAddress" + } } else { $DefaultRoles = @('admin', 'editor', 'readonly', 'anonymous', 'authenticated') $User = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Request.Headers.'x-ms-client-principal')) | ConvertFrom-Json diff --git a/Modules/CIPPCore/Public/Authentication/Test-IpInRange.ps1 b/Modules/CIPPCore/Public/Authentication/Test-IpInRange.ps1 new file mode 100644 index 000000000000..2279b20ce110 --- /dev/null +++ b/Modules/CIPPCore/Public/Authentication/Test-IpInRange.ps1 @@ -0,0 +1,53 @@ +function Test-IpInRange { + <# + .SYNOPSIS + Test if an IP address is in a CIDR range + .DESCRIPTION + This function tests if an IP address is in a CIDR range + .PARAMETER IPAddress + The IP address to test + .PARAMETER Range + The CIDR range to test + .EXAMPLE + Test-IpInRange -IPAddress "1.1.1.1" -Range "1.1.1.1/24" + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [string]$IPAddress, + [Parameter(Mandatory = $true)] + [string]$Range + ) + + function ConvertIpToBigInteger { + param([System.Net.IPAddress]$ip) + return [System.Numerics.BigInteger]::Parse( + [BitConverter]::ToString($ip.GetAddressBytes()).Replace('-', ''), + [System.Globalization.NumberStyles]::HexNumber + ) + } + + try { + $IP = [System.Net.IPAddress]::Parse($IPAddress) + $rangeParts = $Range -split '/' + $networkAddr = [System.Net.IPAddress]::Parse($rangeParts[0]) + $prefix = [int]$rangeParts[1] + + if ($networkAddr.AddressFamily -ne $IP.AddressFamily) { + return $false + } + + $ipBig = ConvertIpToBigInteger $IP + $netBig = ConvertIpToBigInteger $networkAddr + $maxBits = if ($networkAddr.AddressFamily -eq 'InterNetworkV6') { 128 } else { 32 } + $shift = $maxBits - $prefix + $mask = [System.Numerics.BigInteger]::Pow(2, $shift) - [System.Numerics.BigInteger]::One + $invertedMask = [System.Numerics.BigInteger]::MinusOne -bxor $mask + $ipMasked = $ipBig -band $invertedMask + $netMasked = $netBig -band $invertedMask + + return $ipMasked -eq $netMasked + } catch { + return $false + } +} diff --git a/Modules/CIPPCore/Public/CippQueue/Invoke-ListCippQueue.ps1 b/Modules/CIPPCore/Public/CippQueue/Invoke-ListCippQueue.ps1 index 7914041f8cf4..7738d9babd37 100644 --- a/Modules/CIPPCore/Public/CippQueue/Invoke-ListCippQueue.ps1 +++ b/Modules/CIPPCore/Public/CippQueue/Invoke-ListCippQueue.ps1 @@ -8,8 +8,8 @@ function Invoke-ListCippQueue { param($Request = $null, $TriggerMetadata = $null) if ($Request) { - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -72,4 +72,4 @@ function Invoke-ListCippQueue { } else { return $QueueData } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/CippQueue/Invoke-RemoveCippQueue.ps1 b/Modules/CIPPCore/Public/CippQueue/Invoke-RemoveCippQueue.ps1 index 656aa592c8a7..afd30af62654 100644 --- a/Modules/CIPPCore/Public/CippQueue/Invoke-RemoveCippQueue.ps1 +++ b/Modules/CIPPCore/Public/CippQueue/Invoke-RemoveCippQueue.ps1 @@ -7,8 +7,8 @@ function Invoke-RemoveCippQueue { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -22,4 +22,4 @@ function Invoke-RemoveCippQueue { StatusCode = [HttpStatusCode]::OK Body = @{Results = @('History cleared') } }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Clear-CIPPImmutableId.ps1 b/Modules/CIPPCore/Public/Clear-CIPPImmutableId.ps1 new file mode 100644 index 000000000000..ca9d60c172de --- /dev/null +++ b/Modules/CIPPCore/Public/Clear-CIPPImmutableId.ps1 @@ -0,0 +1,22 @@ +function Clear-CIPPImmutableId { + [CmdletBinding()] + param ( + $TenantFilter, + $userid, + $Headers, + $APIName + ) + + try { + $Body = [pscustomobject]@{ onPremisesImmutableId = $null } + $Body = ConvertTo-Json -InputObject $Body -Depth 5 -Compress + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$userid" -tenantid $TenantFilter -type PATCH -body $Body + Write-LogMessage -headers $Headers -API $APIName -message "Successfully cleared immutable ID for $userid" -sev Info + return 'Successfully cleared immutable ID for user.' + } catch { + $ErrorMessage = Get-CippException -Exception $_ + $Message = "Could not clear immutable ID for $($userid): $($ErrorMessage.NormalizedError)" + Write-LogMessage -headers $Headers -API $APIName -message $Message -sev Error -LogData $ErrorMessage + return $Message + } +} diff --git a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-CIPPAccessTenantTest.ps1 b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-CIPPAccessTenantTest.ps1 index 447661a71d88..7b50d26df778 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-CIPPAccessTenantTest.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-CIPPAccessTenantTest.ps1 @@ -5,5 +5,5 @@ function Push-CIPPAccessTenantTest { #> Param($Item) - Test-CIPPAccessTenant -Tenant $Item.customerId -ExecutingUser 'CIPP' + Test-CIPPAccessTenant -Tenant $Item.customerId -Headers 'CIPP' } diff --git a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOffboardingMailboxPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOffboardingMailboxPermissions.ps1 index e1497d902ce1..e3b9845d105b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOffboardingMailboxPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOffboardingMailboxPermissions.ps1 @@ -7,5 +7,5 @@ function Push-ExecOffboardingMailboxPermissions { $Item ) - Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid 'AllUsers' -AccessUser $Item.User -TenantFilter $Item.TenantFilter -APIName $Item.APINAME -ExecutingUser $Item.ExecutingUser + Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid 'AllUsers' -AccessUser $Item.User -TenantFilter $Item.TenantFilter -APIName $Item.APINAME -Headers $Item.Headers } diff --git a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOnboardTenantQueue.ps1 b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOnboardTenantQueue.ps1 index 7f9e54f72637..2806f3f9de4b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOnboardTenantQueue.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecOnboardTenantQueue.ps1 @@ -229,25 +229,24 @@ Function Push-ExecOnboardTenantQueue { if ($AccessAssignments.status -notcontains 'pending') { $OnboardingSteps.Step3.Message = 'Group check: Access assignments are mapped and active' $OnboardingSteps.Step3.Status = 'succeeded' - if ($Item.AddMissingGroups -eq $true) { - $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = 'Checking for missing groups for SAM user' }) - $SamUserId = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/me?`$select=id").id - $CurrentMemberships = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/me/transitiveMemberOf?`$select=id,displayName" - foreach ($Role in $Item.Roles) { - if ($CurrentMemberships.id -notcontains $Role.GroupId) { - $PostBody = @{ - '@odata.id' = 'https://graph.microsoft.com/v1.0/directoryObjects/{0}' -f $SamUserId - } | ConvertTo-Json -Compress - try { - New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($Role.GroupId)/members/`$ref" -body $PostBody -AsApp $true -NoAuthCheck $true - $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = "Added SAM user to $($Role.GroupName)" }) - } catch { - $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = "Failed to add SAM user to $($Role.GroupName) - $($_.Exception.Message)" }) - } + + $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = 'Checking for missing groups for SAM user' }) + $SamUserId = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/me?`$select=id" -NoAuthCheck $true).id + $CurrentMemberships = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/me/transitiveMemberOf?`$select=id,displayName" -NoAuthCheck $true + foreach ($Role in $Item.Roles) { + if ($CurrentMemberships.id -notcontains $Role.GroupId) { + $PostBody = @{ + '@odata.id' = 'https://graph.microsoft.com/v1.0/directoryObjects/{0}' -f $SamUserId + } | ConvertTo-Json -Compress + try { + New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($Role.GroupId)/members/`$ref" -body $PostBody -AsApp $true -NoAuthCheck $true + $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = "Added SAM user to $($Role.GroupName)" }) + } catch { + $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = "Failed to add SAM user to $($Role.GroupName) - $($_.Exception.Message)" }) } } - $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = 'SAM user group check completed' }) } + $Logs.Add([PSCustomObject]@{ Date = (Get-Date).ToUniversalTime(); Log = 'SAM user group check completed' }) } else { $OnboardingSteps.Step3.Message = 'Group check: Access assignments are still pending, try again later' $OnboardingSteps.Step3.Status = 'failed' diff --git a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecScheduledCommand.ps1 b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecScheduledCommand.ps1 index d7fdf61608be..015589f57b06 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecScheduledCommand.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Activity Triggers/Push-ExecScheduledCommand.ps1 @@ -11,9 +11,38 @@ function Push-ExecScheduledCommand { $task = $Item.TaskInfo $commandParameters = $Item.Parameters | ConvertTo-Json -Depth 10 | ConvertFrom-Json -AsHashtable + $Function = Get-Command -Name $Item.Command + if ($null -eq $Function) { + $Results = "Task Failed: The command $($Item.Command) does not exist." + $State = 'Failed' + Update-AzDataTableEntity -Force @Table -Entity @{ + PartitionKey = $task.PartitionKey + RowKey = $task.RowKey + Results = "$Results" + TaskState = $State + } + Write-LogMessage -API 'Scheduler_UserTasks' -tenant $tenant -message "Failed to execute task $($task.Name): The command $($Item.Command) does not exist." -sev Error + return + } + + try { + $ParamsToRemove = [System.Collections.Generic.List[string]]::new() + foreach ($Parameter in $commandParameters.GetEnumerator()) { + if (!$Function.Parameters.ContainsKey($Parameter.Key)) { + $ParamsToRemove.Add($Parameter.Key) + } + } + foreach ($Param in $ParamsToRemove) { + $commandParameters.Remove($Param) + } + } catch { + Write-Host "Failed to remove parameters: $($_.Exception.Message)" + } + $tenant = $Item.Parameters.TenantFilter Write-Host "Started Task: $($Item.Command) for tenant: $tenant" try { + try { Write-Host "Starting task: $($Item.Command) with parameters: $($commandParameters | ConvertTo-Json)" $results = & $Item.Command @commandParameters diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecAddAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecAddAlert.ps1 index 837b439f0a9a..4d59debe39f5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecAddAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecAddAlert.ps1 @@ -10,18 +10,37 @@ Function Invoke-ExecAddAlert { [CmdletBinding()] param($Request, $TriggerMetadata) - if ($Request.Body.sendEmailNow) { - $CIPPAlert = @{ - Type = 'email' - Title = 'Test Email Alert' - HTMLContent = 'This is a test from CIPP' - TenantFilter = 'PartnerTenant' + $Severity = 'Alert' + + $Result = if ($Request.Body.sendEmailNow -or $Request.Body.sendWebhookNow -eq $true -or $Request.Body.writeLog -eq $true) { + $Title = 'CIPP Notification Test' + if ($Request.Body.sendEmailNow) { + $CIPPAlert = @{ + Type = 'email' + Title = $Title + HTMLContent = $Request.Body.text + } + Send-CIPPAlert @CIPPAlert + } + if ($Request.Body.sendWebhookNow) { + $JSONContent = @{ + Title = $Title + Text = $Request.Body.text + } | ConvertTo-Json -Compress + $CIPPAlert = @{ + Type = 'webhook' + Title = $Title + JSONContent = $JSONContent + } + Send-CIPPAlert @CIPPAlert + } + if ($Request.Body.writeLog) { + Write-LogMessage -headers $Request.Headers -API 'Alerts' -message $Request.Body.text -Sev $Severity + 'Successfully generated alert.' } - $Result = Send-CIPPAlert @CIPPAlert } else { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'Alerts' -message $request.body.text -Sev $request.body.Severity - $Result = 'Successfully generated alert.' - # Associate values to output bindings by calling 'Push-OutputBinding'. + Write-LogMessage -headers $Request.Headers -API 'Alerts' -message $Request.Body.text -Sev $Severity + 'Successfully generated alert.' } Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecDurableFunctions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecDurableFunctions.ps1 index e056a656c402..484bc24dab25 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecDurableFunctions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecDurableFunctions.ps1 @@ -9,7 +9,7 @@ function Invoke-ExecDurableFunctions { param($Request, $TriggerMetadata) $APIName = 'ExecDurableStats' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Collect info $StorageContext = New-AzStorageContext -ConnectionString $env:AzureWebJobsStorage diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecEditTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecEditTemplate.ps1 index 0d765e27a478..3299b5c922d0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecEditTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecEditTemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecEditTemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { $Table = Get-CippTable -tablename 'templates' @@ -34,12 +34,12 @@ Function Invoke-ExecEditTemplate { PartitionKey = "$Type" GUID = "$GUID" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Edited template $($Request.body.name) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Edited template $($Request.body.name) with GUID $GUID" -Sev 'Debug' } $body = [pscustomobject]@{ 'Results' = 'Successfully saved the template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to edit template: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to edit template: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Editing template failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGeoIPLookup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGeoIPLookup.ps1 index cd3dbc1a42b6..0cf94d30d806 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGeoIPLookup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGeoIPLookup.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecGeoIPLookup { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $IP = $Request.Query.IP ?? $Request.Body.IP if (-not $IP) { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGraphRequest.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGraphRequest.ps1 index 7ebe9d3aa714..dec61d0e5b25 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGraphRequest.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecGraphRequest.ps1 @@ -8,8 +8,8 @@ Function Invoke-ExecGraphRequest { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Function ConvertTo-FlatObject { # https://evotec.xyz/powershell-converting-advanced-object-to-flat-object/ - MIT License @@ -91,10 +91,10 @@ Function Invoke-ExecGraphRequest { } catch { continue } - } + } } - $GraphRequest = $RawGraphRequest | Where-Object -Property '@odata.context' -EQ $null | ConvertTo-FlatObject + $GraphRequest = $RawGraphRequest | Where-Object -Property '@odata.context' -EQ $null | ConvertTo-FlatObject $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecListBackup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecListBackup.ps1 index 268f91caac18..013317b805b6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecListBackup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecListBackup.ps1 @@ -25,11 +25,11 @@ Function Invoke-ExecListBackup { } $Result = Get-CIPPBackup @CippBackupParams - Write-Host ($Result | ConvertTo-Json) + if ($request.Query.NameOnly) { $Result = $Result | Select-Object @{Name = 'BackupName'; exp = { $_.RowKey } }, Timestamp | Sort-Object Timestamp -Descending } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'Alerts' -message $request.body.text -Sev $request.body.Severity + # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecPartnerWebhook.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecPartnerWebhook.ps1 index ea26ed3aca03..045ad540318f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecPartnerWebhook.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecPartnerWebhook.ps1 @@ -42,7 +42,7 @@ function Invoke-ExecPartnerWebhook { PartnerCenter = $true BaseURL = $BaseURL EventType = $Request.Body.EventType - ExecutingUser = $Request.Headers.'x-ms-client-principal' + Headers = $Request.Headers.'x-ms-client-principal' } $Results = New-CIPPGraphSubscription @Webhook diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 index 84721b1e06c1..67fab612224f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 @@ -33,7 +33,7 @@ Function Invoke-ExecSetCIPPAutoBackup { Add-CIPPScheduledTask -Task $TaskBody -hidden $false $Result = @{ 'Results' = 'Scheduled Task Successfully created' } } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'Alerts' -message $request.body.text -Sev $request.body.Severity + Write-LogMessage -headers $Request.Headers -API $Request.Params.CIPPEndpoint -message 'Scheduled automatic CIPP backups' -Sev 'Info' # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetCippAlerts.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetCippAlerts.ps1 index 377bd557879b..f10665096d54 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetCippAlerts.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetCippAlerts.ps1 @@ -67,8 +67,8 @@ Function Invoke-GetCippAlerts { } if ($Rows) { $Rows | ForEach-Object { $Alerts.Add($_) } } $Alerts = @($Alerts) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetVersion.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetVersion.ps1 index 61df91438485..6bc115e7e4f0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetVersion.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-GetVersion.ps1 @@ -10,8 +10,8 @@ Function Invoke-GetVersion { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $CIPPVersion = $request.query.localversion diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListApiTest.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListApiTest.ps1 new file mode 100644 index 000000000000..b8ba63e8a322 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListApiTest.ps1 @@ -0,0 +1,15 @@ +function Invoke-ListApiTest { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + CIPP.Core.Read + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = ($Request | ConvertTo-Json -Depth 5) + }) +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListGraphRequest.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListGraphRequest.ps1 index 45bede27c0b2..09beb0a109e2 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListGraphRequest.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ListGraphRequest.ps1 @@ -9,10 +9,10 @@ function Invoke-ListGraphRequest { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $Message = 'Accessed this API | Endpoint: {0}' -f $Request.Query.Endpoint - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message $Message -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message $Message -Sev 'Debug' $CippLink = ([System.Uri]$TriggerMetadata.Headers.Referer).PathAndQuery @@ -117,6 +117,9 @@ function Invoke-ListGraphRequest { } $Metadata = $GraphRequestParams + if ($Request.Headers.'x-ms-coldstart' -eq 1) { + $Metadata.ColdStart = $true + } try { $Results = Get-GraphRequestList @GraphRequestParams diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionMapping.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionMapping.ps1 index 01558e4c2c9f..3fbb1ac29ccf 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionMapping.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionMapping.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecExtensionMapping { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -38,6 +38,16 @@ Function Invoke-ExecExtensionMapping { 'Sherweb' { $Body = Get-SherwebMapping -CIPPMapping $Table } + 'HaloPSAFields' { + $TicketTypes = Get-HaloTicketType + $Body = @{'TicketTypes' = $TicketTypes } + } + 'PWPushFields' { + $Accounts = Get-PwPushAccount + $Body = @{ + 'Accounts' = $Accounts + } + } } } @@ -67,7 +77,7 @@ Function Invoke-ExecExtensionMapping { } } } catch { - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "mapping API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "mapping API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } } @@ -92,7 +102,7 @@ Function Invoke-ExecExtensionMapping { } } } catch { - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "mapping API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "mapping API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionSync.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionSync.ps1 index 136009bd740b..239976f082f5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionSync.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionSync.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecExtensionSync { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' switch ($Request.Query.Extension) { 'Gradient' { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionTest.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionTest.ps1 index 3d9ca5f3dfb5..a0c36e11d199 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionTest.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionTest.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecExtensionTest { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable -TableName Extensionsconfig $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json) # Interact with query parameters or the body of the request. @@ -19,53 +19,80 @@ Function Invoke-ExecExtensionTest { switch ($Request.query.extensionName) { 'HaloPSA' { $token = Get-HaloToken -configuration $Configuration.HaloPSA - $Results = [pscustomobject]@{'Results' = 'Successfully Connected to HaloPSA' } + if ($token) { + $Results = [pscustomobject]@{'Results' = 'Successfully Connected to HaloPSA' } + } else { + $Results = [pscustomobject]@{'Results' = 'Failed to connect to HaloPSA, check your API credentials and try again.' } + } } 'Gradient' { $GradientToken = Get-GradientToken -Configuration $Configuration.Gradient - $ExistingIntegrations = Invoke-RestMethod -Uri 'https://app.usegradient.com/api/vendor-api/organization' -Method GET -Headers $GradientToken - if ($ExistingIntegrations.Status -ne 'active') { - $ActivateRequest = Invoke-RestMethod -Uri 'https://app.usegradient.com/api/vendor-api/organization/status/active' -Method PATCH -Headers $GradientToken + if ($GradientToken) { + try { + $ExistingIntegrations = Invoke-RestMethod -Uri 'https://app.usegradient.com/api/vendor-api/organization' -Method GET -Headers $GradientToken + if ($ExistingIntegrations.Status -ne 'active') { + $ActivateRequest = Invoke-RestMethod -Uri 'https://app.usegradient.com/api/vendor-api/organization/status/active' -Method PATCH -Headers $GradientToken + } + $Results = [pscustomobject]@{'Results' = 'Successfully Connected to Gradient' } + } catch { + $Results = [pscustomobject]@{'Results' = 'Failed to connect to Gradient, check your API credentials and try again.' } + } + } else { + $Results = [pscustomobject]@{'Results' = 'Failed to connect to Gradient, check your API credentials and try again.' } } - $Results = [pscustomobject]@{'Results' = 'Successfully Connected to Gradient' } - } 'CIPP-API' { $Results = [pscustomobject]@{'Results' = 'You cannot test the CIPP-API from CIPP. Please check the documentation on how to test the CIPP-API.' } } 'NinjaOne' { $token = Get-NinjaOneToken -configuration $Configuration.NinjaOne - $Results = [pscustomobject]@{'Results' = 'Successfully Connected to NinjaOne' } + if ($token) { + $Results = [pscustomobject]@{'Results' = 'Successfully Connected to NinjaOne' } + } else { + $Results = [pscustomobject]@{'Results' = 'Failed to connect to NinjaOne, check your API credentials and try again.' } + } } 'PWPush' { $Payload = 'This is a test from CIPP' $PasswordLink = New-PwPushLink -Payload $Payload if ($PasswordLink) { - $Results = [pscustomobject]@{'Results' = 'Successfully generated PWPush'; 'Link' = $PasswordLink } + $Results = [pscustomobject]@{Results = @(@{'resultText' = 'Successfully generated PWPush, hit the Copy to Clipboard button to retrieve the test.'; 'copyField' = $PasswordLink; 'state' = 'success' }) } } else { $Results = [pscustomobject]@{'Results' = 'PWPush is not enabled' } } } 'Hudu' { - Connect-HuduAPI -configuration $Configuration.Hudu + Connect-HuduAPI -configuration $Configuration $Version = Get-HuduAppInfo if ($Version.version) { $Results = [pscustomobject]@{'Results' = ('Successfully Connected to Hudu, version: {0}' -f $Version.version) } } else { - $Results = [pscustomobject]@{'Results' = 'Failed to connect to Hudu' } + $Results = [pscustomobject]@{'Results' = 'Failed to connect to Hudu, check your API credentials and try again.' } } } 'Sherweb' { $token = Get-SherwebAuthentication - $Results = [pscustomobject]@{'Results' = 'Successfully Connected to Sherweb' } + if ($token) { + $Results = [pscustomobject]@{'Results' = 'Successfully Connected to Sherweb' } + } else { + $Results = [pscustomobject]@{'Results' = 'Failed to connect to Sherweb, check your API credentials and try again.' } + } } 'HIBP' { $ConnectionTest = Get-HIBPConnectionTest $Results = [pscustomobject]@{'Results' = 'Successfully Connected to HIBP' } } 'GitHub' { - $GitHubResponse = Invoke-GitHubApiRequest -Configuration $Configuration.GitHub -Method 'GET' -Path 'user' -Verbose - $Results = [pscustomobject]@{ 'Results' = "Successfully connected to GitHub user: $($GitHubResponse.login)" } + $GitHubResponse = Invoke-GitHubApiRequest -Method 'GET' -Path 'user' -ReturnHeaders + if ($GitHubResponse.login) { + if ($GitHubResponse.Headers.'x-oauth-scopes') { + $Results = [pscustomobject]@{ 'Results' = "Successfully connected to GitHub user: $($GitHubResponse.login) with scopes: $($GitHubResponse.Headers.'x-oauth-scopes')" } + } else { + $Results = [pscustomobject]@{ 'Results' = "Successfully connected to GitHub user: $($GitHubResponse.login) using a Fine Grained PAT" } + } + } else { + $Results = [pscustomobject]@{ 'Results' = 'Failed to connect to GitHub. Check your API credentials and try again.' } + } } } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionsConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionsConfig.ps1 index 60ba2aa4adca..afba503c5d7c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionsConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ExecExtensionsConfig.ps1 @@ -7,28 +7,11 @@ Function Invoke-ExecExtensionsConfig { .ROLE CIPP.Extension.ReadWrite #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Scope = 'Function')] [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $Request.Headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - - #Connect-AzAccount -UseDeviceAuthentication - # Write to the Azure Functions log stream. - Write-Information 'PowerShell HTTP trigger function processed a request.' $Body = [PSCustomObject]$Request.Body $results = try { - if ($Body.CIPPAPI.Enabled) { - try { - $APIConfig = New-CIPPAPIConfig -ExecutingUser $Request.Headers.'x-ms-client-principal' -resetpassword $Body.CIPPAPI.ResetPassword - $AddedText = $APIConfig.Results - } catch { - $AddedText = ' Could not enable CIPP-API. Check the CIPP documentation for API requirements.' - $Body = $Body | Select-Object * -ExcludeProperty CIPPAPI - } - } - # Check if NinjaOne URL is set correctly and the instance has at least version 5.6 if ($Body.NinjaOne) { $AllowedNinjaHostnames = @( @@ -40,16 +23,7 @@ Function Invoke-ExecExtensionsConfig { ) $SetNinjaHostname = $Body.NinjaOne.Instance -replace '/ws', '' -replace 'https://', '' if ($AllowedNinjaHostnames -notcontains $SetNinjaHostname) { - throw "NinjaOne URL is not allowed. Allowed hostnames are: $($AllowedNinjaHostnames -join ', ')" - } - - try { - [version]$Version = (Invoke-WebRequest -Method GET -Uri "$SetNinjaHostname/app-version.txt" -ea stop).content - } catch { - throw "Failed to connect to NinjaOne check your Instance is set correctly eg 'app.ninjarmm.com'" - } - if ($Version -lt [version]'5.6.0.0') { - throw 'NinjaOne 5.6.0.0 is required.' + "Error: NinjaOne URL is not allowed. Allowed hostnames are: $($AllowedNinjaHostnames -join ', ')" } } @@ -62,17 +36,7 @@ Function Invoke-ExecExtensionsConfig { Write-Information 'writing API Key to keyvault, and clearing.' Write-Information "$ENV:WEBSITE_DEPLOYMENT_ID" if ($Body.$APIKey.APIKey) { - if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') { - $DevSecretsTable = Get-CIPPTable -tablename 'DevSecrets' - $Secret = [PSCustomObject]@{ - 'PartitionKey' = $APIKey - 'RowKey' = $APIKey - 'APIKey' = $Body.$APIKey.APIKey - } - Add-CIPPAzDataTableEntity @DevSecretsTable -Entity $Secret -Force - } else { - $null = Set-AzKeyVaultSecret -VaultName $ENV:WEBSITE_DEPLOYMENT_ID -Name $APIKey -SecretValue (ConvertTo-SecureString -AsPlainText -Force -String $Body.$APIKey.APIKey) - } + Set-ExtensionAPIKey -Extension $APIKey -APIKey $Body.$APIKey.APIKey } if ($Body.$APIKey.PSObject.Properties.Name -notcontains 'APIKey') { $Body.$APIKey | Add-Member -MemberType NoteProperty -Name APIKey -Value 'SentToKeyVault' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ListExtensionSync.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ListExtensionSync.ps1 index dd1564a91e73..0f8aa6c2bc77 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ListExtensionSync.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Extensions/Invoke-ListExtensionSync.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListExtensionSync { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 index 86a74a58a459..ad4e195f12a4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 @@ -14,8 +14,8 @@ Function Invoke-AddScheduledItem { } else { $hidden = $true } - $Result = Add-CIPPScheduledTask -Task $Request.body -hidden $hidden -DisallowDuplicateName $Request.query.DisallowDuplicateName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message $Result -Sev 'Info' + $Result = Add-CIPPScheduledTask -Task $Request.body -Headers $Request.Headers -hidden $hidden -DisallowDuplicateName $Request.query.DisallowDuplicateName + Write-LogMessage -headers $Request.Headers -API $APINAME -message $Result -Sev 'Info' Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 index 3fcce60e2d53..22a8eb024ce9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 @@ -11,7 +11,7 @@ Function Invoke-RemoveScheduledItem { param($Request, $TriggerMetadata) $APIName = 'RemoveScheduledItem' - $User = $request.headers.'x-ms-client-principal' + $User = $Request.Headers $task = @{ RowKey = $Request.Query.id ? $Request.Query.id : $Request.Body.id @@ -20,7 +20,7 @@ Function Invoke-RemoveScheduledItem { $Table = Get-CIPPTable -TableName 'ScheduledTasks' Remove-AzDataTableEntity -Force @Table -Entity $task - Write-LogMessage -user $User -API $APINAME -message "Task removed: $($task.RowKey)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Task removed: $($task.RowKey)" -Sev 'Info' Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 index 5e3726e5d73f..4568e389f721 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAccessChecks { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -Headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable -tablename 'AccessChecks' $LastRun = (Get-Date).ToUniversalTime() @@ -25,7 +25,7 @@ Function Invoke-ExecAccessChecks { $Results = $null } if (!$Results) { - $Results = Test-CIPPAccessPermissions -tenantfilter $ENV:TenantID -APIName $APINAME -ExecutingUser $Request.Headers.'x-ms-client-principal' + $Results = Test-CIPPAccessPermissions -tenantfilter $ENV:TenantID -APIName $APINAME -Headers $Request.Headers } else { try { $LastRun = [DateTime]::SpecifyKind($Cache.Timestamp.DateTime, [DateTimeKind]::Utc) @@ -34,7 +34,7 @@ Function Invoke-ExecAccessChecks { } } } else { - $Results = Test-CIPPAccessPermissions -tenantfilter $ENV:TenantID -APIName $APINAME -ExecutingUser $Request.Headers.'x-ms-client-principal' + $Results = Test-CIPPAccessPermissions -tenantfilter $ENV:TenantID -APIName $APINAME -Headers $Request.Headers } } 'Tenants' { @@ -82,12 +82,12 @@ Function Invoke-ExecAccessChecks { } if ($Request.Query.SkipCache -eq 'true' -or $Request.Query.SkipCache -eq $true) { - $Message = Test-CIPPAccessTenant -ExecutingUser $Request.Headers.'x-ms-client-principal' + $Message = Test-CIPPAccessTenant -Headers $Request.Headers } if ($Request.Body.TenantId) { $Tenant = Get-Tenants -TenantFilter $Request.Body.TenantId - $null = Test-CIPPAccessTenant -Tenant $Tenant.customerId -ExecutingUser $Request.Headers.'x-ms-client-principal' + $null = Test-CIPPAccessTenant -Tenant $Tenant.customerId -Headers $Request.Headers $Results = "Refreshing tenant $($Tenant.displayName)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAddTrustedIP.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAddTrustedIP.ps1 index 4613ea2c3c68..41a0ae5a2854 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAddTrustedIP.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAddTrustedIP.ps1 @@ -12,13 +12,13 @@ Function Invoke-ExecAddTrustedIP { $Table = Get-CippTable -tablename 'trustedIps' Add-CIPPAzDataTableEntity @Table -Entity @{ - PartitionKey = $request.query.tenantfilter - RowKey = $Request.query.ip - state = $request.query.State + PartitionKey = $Request.Body.tenantfilter + RowKey = $Request.Body.IP + state = $Request.Body.State } -Force Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK - Body = @{ results = "Added $($Request.query.ip) to database with state $($Request.query.state) for $($Request.query.tenantfilter)" } + Body = @{ results = "Added $($Request.Body.IP) to database with state $($Request.Body.State) for $($Request.Body.tenantfilter)" } }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecApiClient.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecApiClient.ps1 new file mode 100644 index 000000000000..08ed1490a556 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecApiClient.ps1 @@ -0,0 +1,186 @@ +function Invoke-ExecApiClient { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + CIPP.Extension.ReadWrite + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $Table = Get-CippTable -tablename 'ApiClients' + $Action = $Request.Query.Action ?? $Request.Body.Action + + switch ($Action) { + 'List' { + $Apps = Get-CIPPAzDataTableEntity @Table + if (!$Apps) { + $Apps = @() + } else { + $Apps = Get-CippApiClient + $Body = @{ Results = @($Apps) } + } + } + 'ListAvailable' { + $sitename = $env:WEBSITE_SITE_NAME + $Apps = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/applications?`$filter=signInAudience eq 'AzureAdMyOrg' and web/redirectUris/any(x:x eq 'https://$($sitename).azurewebsites.net/.auth/login/aad/callback')&`$top=999&`$select=appId,displayName,createdDateTime,api,web,passwordCredentials&`$count=true" -NoAuthCheck $true -asapp $true -ComplexFilter + $Body = @{ + Results = @($Apps) + } + } + 'AddUpdate' { + if ($Request.Body.ClientId -or $Request.Body.AppName) { + $ClientId = $Request.Body.ClientId.value ?? $Request.Body.ClientId + try { + $ApiConfig = @{ + Headers = $Request.Headers + } + if ($ClientId) { + $ApiConfig.ClientId = $ClientId + $ApiConfig.ResetSecret = $Request.Body.CIPPAPI.ResetSecret + } + if ($Request.Body.AppName) { + $ApiConfig.AppName = $Request.Body.AppName + } + $APIConfig = New-CIPPAPIConfig @ApiConfig + + $ClientId = $APIConfig.ApplicationID + $AddedText = $APIConfig.Results + } catch { + $AddedText = 'Could not modify App Registrations. Check the CIPP documentation for API requirements.' + $Body = $Body | Select-Object * -ExcludeProperty CIPPAPI + } + } + + if ($Request.Body.IpRange.value) { + $IpRange = [System.Collections.Generic.List[string]]::new() + $regexPattern = '^(?:(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?:/\d{1,2})?|(?:[0-9A-Fa-f]{1,4}:){1,7}[0-9A-Fa-f]{1,4}(?:/\d{1,3})?)$' + foreach ($IP in @($Request.Body.IPRange.value)) { + if ($IP -match $regexPattern) { + $IpRange.Add($IP) + } + } + } else { + $IpRange = @() + } + + $ExistingClient = Get-CIPPAzDataTableEntity @Table -Filter "RowKey eq '$($ClientId)'" + if ($ExistingClient) { + $Client = $ExistingClient + $Client.Role = [string]$Request.Body.Role.value + $Client.IPRange = "$(@($IpRange) | ConvertTo-Json -Compress)" + $Client.Enabled = $Request.Body.Enabled ?? $false + Write-LogMessage -headers $Request.Headers -API 'ExecApiClient' -message "Updated API client $($Request.Body.ClientId)" -Sev 'Info' + $Results = 'API client updated' + } else { + $Client = @{ + 'PartitionKey' = 'ApiClients' + 'RowKey' = "$($ClientId)" + 'AppName' = "$($APIConfig.AppName ?? $Request.Body.ClientId.addedFields.displayName)" + 'Role' = [string]$Request.Body.Role.value + 'IPRange' = "$(@($IpRange) | ConvertTo-Json -Compress)" + 'Enabled' = $Request.Body.Enabled ?? $false + } + $Results = @{ + resultText = "API Client created with the name '$($Client.AppName)'. Use the Copy to Clipboard button to retrieve the secret." + copyField = $APIConfig.ApplicationSecret + state = 'success' + } + } + + Add-CIPPAzDataTableEntity @Table -Entity $Client -Force | Out-Null + $Body = @($Results) + } + 'GetAzureConfiguration' { + $RGName = $ENV:WEBSITE_RESOURCE_GROUP + $FunctionAppName = $ENV:WEBSITE_SITE_NAME + try { + $APIClients = Get-CippApiAuth -RGName $RGName -FunctionAppName $FunctionAppName + $Results = $ApiClients + } catch { + $Results = @{ + Enabled = 'Could not get API clients, ensure you have the appropriate rights to read the Authentication settings.' + } + } + $Body = @{ + Results = $Results + } + } + 'SaveToAzure' { + $TenantId = $ENV:TenantId + $RGName = $ENV:WEBSITE_RESOURCE_GROUP + $FunctionAppName = $ENV:WEBSITE_SITE_NAME + $AllClients = Get-CIPPAzDataTableEntity @Table -Filter 'Enabled eq true' + $ClientIds = $AllClients.RowKey + try { + Set-CippApiAuth -RGName $RGName -FunctionAppName $FunctionAppName -TenantId $TenantId -ClientIds $ClientIds + $Body = @{ Results = 'API clients saved to Azure' } + Write-LogMessage -headers $Request.Headers -API 'ExecApiClient' -message 'Saved API clients to Azure' -Sev 'Info' + } catch { + $Body = @{ Results = 'Failed to save allowed API clients to Azure, ensure your function app has the appropriate rights to make changes to the Authentication settings.' } + Write-Information (Get-CippException -Exception $_ | ConvertTo-Json) + } + } + 'ResetSecret' { + $Client = Get-CIPPAzDataTableEntity @Table -Filter "RowKey eq '$($Request.Body.ClientId)'" + if (!$Client) { + $Results = @{ + resultText = 'API client not found' + severity = 'error' + } + } else { + $ApiConfig = New-CIPPAPIConfig -ResetSecret -AppId $Request.Body.ClientId -Headers $Request.Headers + + if ($ApiConfig.ApplicationSecret) { + $Results = @{ + resultText = "API secret reset for $($Client.AppName). Use the Copy to Clipboard button to retrieve the new secret." + copyField = $ApiConfig.ApplicationSecret + state = 'success' + } + } else { + $Results = @{ + resultText = "Failed to reset secret for $($Client.AppName)" + state = 'error' + } + } + } + $Body = @($Results) + } + 'Delete' { + try { + if ($Request.Body.ClientId) { + $ClientId = $Request.Body.ClientId.value ?? $Request.Body.ClientId + if ($Request.Body.RemoveAppReg -eq $true) { + Write-Information "Deleting API Client: $ClientId from Entra" + $App = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/applications?`$filter=appId eq '$($ClientId)'&`$select=id,appId,web" -NoAuthCheck $true -asapp $true + $Id = $App.id + if ($Id -and $App.web.redirectUris -like "*$($env:WEBSITE_SITE_NAME)*") { + New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$Id" -type DELETE -Body '{}' -NoAuthCheck $true -asapp $true + Write-Information "Deleted App Registration for $ClientId" + } else { + Write-Information "App Registration for $ClientId not found or Redirect URI does not match" + } + } + Write-Information "Deleting API Client: $ClientId from CIPP" + $Client = Get-CIPPAzDataTableEntity @Table -Filter "RowKey eq '$($ClientId)'" -Property RowKey, PartitionKey + Remove-AzDataTableEntity @Table -Entity $Client -Force + Write-LogMessage -headers $Request.Headers -API 'ExecApiClient' -message "Deleted API client $ClientId" -Sev 'Info' + $Body = @{ Results = "API client $ClientId deleted" } + } else { + $Body = @{ Results = "API client $ClientId not found or not a valid CIPP-API application" } + } + } catch { + Write-LogMessage -headers $Request.Headers -API 'ExecApiClient' -message "Failed to remove app registration for $ClientId" -Sev 'Warning' + } + } + default { + $Body = @{Results = 'Invalid action' } + } + } + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $Body + }) +} + diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecBackendURLs.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecBackendURLs.ps1 index 9dfb2932b4a3..80c0de481eaa 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecBackendURLs.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecBackendURLs.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecBackendURLs { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Subscription = ($ENV:WEBSITE_OWNER_NAME).split('+') | Select-Object -First 1 $SWAName = $ENV:WEBSITE_SITE_NAME -replace 'cipp', 'CIPP-SWA-' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCPVPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCPVPermissions.ps1 index 11fbdb4022bd..663468180762 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCPVPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCPVPermissions.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecCPVPermissions { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCustomRole.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCustomRole.ps1 index b4614cd96b40..8206c0d0b0d3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCustomRole.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecCustomRole.ps1 @@ -11,7 +11,7 @@ function Invoke-ExecCustomRole { $Table = Get-CippTable -tablename 'CustomRoles' switch ($Request.Query.Action) { 'AddUpdate' { - Write-LogMessage -user $Request.Headers.'x-ms-client-principal' -API 'ExecCustomRole' -message "Saved custom role $($Request.Body.RoleName)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API 'ExecCustomRole' -message "Saved custom role $($Request.Body.RoleName)" -Sev 'Info' $Role = @{ 'PartitionKey' = 'CustomRoles' 'RowKey' = "$($Request.Body.RoleName.ToLower())" @@ -23,7 +23,7 @@ function Invoke-ExecCustomRole { $Body = @{Results = 'Custom role saved' } } 'Delete' { - Write-LogMessage -user $Request.Headers.'x-ms-client-principal' -API 'ExecCustomRole' -message "Deleted custom role $($Request.Body.RoleName)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API 'ExecCustomRole' -message "Deleted custom role $($Request.Body.RoleName)" -Sev 'Info' $Role = Get-CIPPAzDataTableEntity @Table -Filter "RowKey eq '$($Request.Body.RoleName)'" -Property RowKey, PartitionKey Remove-AzDataTableEntity -Force @Table -Entity $Role $Body = @{Results = 'Custom role deleted' } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecDnsConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecDnsConfig.ps1 index aaf16a8c8b10..99d071ee8035 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecDnsConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecDnsConfig.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecDnsConfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # List of supported resolvers $ValidResolvers = @( @@ -59,7 +59,7 @@ Function Invoke-ExecDnsConfig { } if ($updated) { Add-CIPPAzDataTableEntity @ConfigTable -Entity $Config -Force - Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message 'DNS configuration updated' -Sev 'Info' + Write-LogMessage -API $APINAME -tenant 'Global' -headers $Request.Headers -message 'DNS configuration updated' -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Success: DNS configuration updated.' } } else { $StatusCode = [HttpStatusCode]::BadRequest @@ -90,18 +90,18 @@ Function Invoke-ExecDnsConfig { } 'GetConfig' { $body = [pscustomobject]$Config - Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message 'Retrieved DNS configuration' -Sev 'Debug' + Write-LogMessage -API $APINAME -tenant 'Global' -headers $Request.Headers -message 'Retrieved DNS configuration' -Sev 'Debug' } 'RemoveDomain' { $Filter = "RowKey eq '{0}'" -f $Request.Query.Domain $DomainRow = Get-CIPPAzDataTableEntity @DomainTable -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @DomainTable -Entity $DomainRow - Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message "Removed Domain - $($Request.Query.Domain) " -Sev 'Info' + Write-LogMessage -API $APINAME -tenant 'Global' -headers $Request.Headers -message "Removed Domain - $($Request.Query.Domain) " -Sev 'Info' $body = [pscustomobject]@{ 'Results' = "Domain removed - $($Request.Query.Domain)" } } } } catch { - Write-LogMessage -API $APINAME -tenant $($name) -user $request.headers.'x-ms-client-principal' -message "DNS Config API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -API $APINAME -tenant $($name) -headers $Request.Headers -message "DNS Config API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } $StatusCode = [HttpStatusCode]::BadRequest } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeLicenses.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeLicenses.ps1 index 1d554d031aef..1df4e0188d26 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeLicenses.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeLicenses.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecExcludeLicenses { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -32,7 +32,7 @@ Function Invoke-ExecExcludeLicenses { $Rows = Get-CIPPAzDataTableEntity @Table - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message 'got excluded licenses list' -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message 'got excluded licenses list' -Sev 'Info' } $body = @($Rows) } @@ -48,7 +48,7 @@ Function Invoke-ExecExcludeLicenses { } Add-CIPPAzDataTableEntity @Table -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added exclusion $($request.body.SKUName)" -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added exclusion $($request.body.SKUName)" -Sev 'Info' $body = [pscustomobject]@{'Results' = "Success. We've added $($request.body.SKUName) to the excluded list." } } @@ -56,11 +56,11 @@ Function Invoke-ExecExcludeLicenses { $Filter = "RowKey eq '{0}' and PartitionKey eq 'License'" -f $Request.Body.GUID $Entity = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $Entity - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Removed exclusion $($Request.Query.GUID)" -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Removed exclusion $($Request.Query.GUID)" -Sev 'Info' $body = [pscustomobject]@{'Results' = "Success. We've removed $($Request.query.guid) from the excluded list." } } } catch { - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Exclusion API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Exclusion API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeTenant.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeTenant.ps1 index ccb04d2bceb6..d1beb8ca2547 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeTenant.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecExcludeTenant.ps1 @@ -10,21 +10,20 @@ Function Invoke-ExecExcludeTenant { [CmdletBinding()] param($Request, $TriggerMetadata) - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $user = $request.headers.'x-ms-client-principal' - $username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($user)) | ConvertFrom-Json).userDetails + $username = $Request.Headers.'x-ms-client-principal-name' $date = (Get-Date).tostring('yyyy-MM-dd') $TenantsTable = Get-CippTable -tablename Tenants if ($Request.Query.List) { $ExcludedFilter = "PartitionKey eq 'Tenants' and Excluded eq true" $ExcludedTenants = Get-CIPPAzDataTableEntity @TenantsTable -Filter $ExcludedFilter - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message 'got excluded tenants list' -Sev 'Debug' + Write-LogMessage -API $APINAME -headers $Request.Headers -message 'got excluded tenants list' -Sev 'Debug' $body = @($ExcludedTenants) } elseif ($Request.query.ListAll) { $ExcludedTenants = Get-CIPPAzDataTableEntity @TenantsTable -filter "PartitionKey eq 'Tenants'" | Sort-Object -Property displayName - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message 'got excluded tenants list' -Sev 'Debug' + Write-LogMessage -API $APINAME -headers $Request.Headers -message 'got excluded tenants list' -Sev 'Debug' $body = @($ExcludedTenants) } try { @@ -40,7 +39,7 @@ Function Invoke-ExecExcludeTenant { $Tenant } Update-AzDataTableEntity -Force @TenantsTable -Entity ([pscustomobject]$Excluded) - Write-LogMessage -API $APINAME -tenant $($name) -user $request.headers.'x-ms-client-principal' -message "Added exclusion for customer(s): $($Excluded.defaultDomainName -join ',')" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $($name) -headers $Request.Headers -message "Added exclusion for customer(s): $($Excluded.defaultDomainName -join ',')" -Sev 'Info' $body = [pscustomobject]@{'Results' = "Success. Added exclusions for customer(s): $($Excluded.defaultDomainName -join ',')" } } @@ -52,11 +51,11 @@ Function Invoke-ExecExcludeTenant { $Tenant.ExcludeDate = '' Update-AzDataTableEntity -Force @TenantsTable -Entity $Tenant } - Write-LogMessage -API $APINAME -tenant $($name) -user $request.headers.'x-ms-client-principal' -message "Removed exclusion for customer $($name)" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $($name) -headers $Request.Headers -message "Removed exclusion for customer $($name)" -Sev 'Info' $body = [pscustomobject]@{'Results' = "Success. We've removed $name from the excluded tenants." } } } catch { - Write-LogMessage -API $APINAME -tenant $($name) -user $request.headers.'x-ms-client-principal' -message "Exclusion API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -API $APINAME -tenant $($name) -headers $Request.Headers -message "Exclusion API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } } if (!$body) { $body = @() } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecMaintenanceScripts.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecMaintenanceScripts.ps1 index fe01aed3123e..c78ba5176232 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecMaintenanceScripts.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecMaintenanceScripts.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecMaintenanceScripts { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { $GraphToken = Get-GraphToken -returnRefresh $true $AccessTokenDetails = Read-JwtAccessDetails -Token $GraphToken.access_token @@ -67,7 +67,7 @@ Function Invoke-ExecMaintenanceScripts { } } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Failed to retrieve maintenance scripts. Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Failed to retrieve maintenance scripts. Error: $($_.Exception.Message)" -Sev 'Error' $Body = @{Status = "Failed to retrieve maintenance scripts $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecNotificationConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecNotificationConfig.ps1 index 411400303392..77a1ac8ae164 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecNotificationConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecNotificationConfig.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecNotificationConfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPartnerMode.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPartnerMode.ps1 index 75605662298d..614ac38e610c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPartnerMode.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPartnerMode.ps1 @@ -53,9 +53,8 @@ Function Invoke-ExecPartnerMode { Body = @{ results = @( @{ - result = "Set Tenant mode to $($Request.body.TenantMode)" - copyInfo = $null - state = 'info' + resultText = "Set Tenant mode to $($Request.body.TenantMode)" + state = 'success' } ) } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPasswordConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPasswordConfig.ps1 index 25e72a914e82..b237e5fd15c7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPasswordConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPasswordConfig.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecPasswordConfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable -TableName Settings $PasswordType = (Get-CIPPAzDataTableEntity @Table) diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPermissionRepair.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPermissionRepair.ps1 index 8f629db28e81..499d31a60a22 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPermissionRepair.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecPermissionRepair.ps1 @@ -70,7 +70,7 @@ function Invoke-ExecPermissionRepair { $Body = @{ 'Results' = 'Permissions Updated' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'ExecPermissionRepair' -message 'CIPP-SAM Permissions Updated' -Sev 'Info' -LogData $Permissions + Write-LogMessage -headers $Request.Headers -API 'ExecPermissionRepair' -message 'CIPP-SAM Permissions Updated' -Sev 'Info' -LogData $Permissions } else { $Body = @{ 'Results' = 'No permissions to update' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRestoreBackup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRestoreBackup.ps1 index e07e8e139dca..e243f4ab2e0c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRestoreBackup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRestoreBackup.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecRestoreBackup { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { if ($Request.Body.BackupName -like 'CippBackup_*') { @@ -26,7 +26,7 @@ Function Invoke-ExecRestoreBackup { $Table.Entity = $ht2 Add-CIPPAzDataTableEntity @Table -Force } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Created backup' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Created backup' -Sev 'Debug' $body = [pscustomobject]@{ 'Results' = 'Successfully restored backup.' } @@ -43,14 +43,14 @@ Function Invoke-ExecRestoreBackup { $Table.Entity = $ht2 Add-AzDataTableEntity @Table -Force } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Created backup' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Created backup' -Sev 'Debug' $body = [pscustomobject]@{ 'Results' = 'Successfully restored backup.' } } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to restore backup: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to restore backup: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Backup restore failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRunBackup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRunBackup.ps1 index 561a655c2b19..faee7cb04412 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRunBackup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecRunBackup.ps1 @@ -10,13 +10,31 @@ Function Invoke-ExecRunBackup { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $CSVfile = New-CIPPBackup -BackupType 'CIPP' - $body = [pscustomobject]@{ - 'Results' = 'Created backup' - backup = $CSVfile.BackupData - } | ConvertTo-Json -Depth 5 -Compress + $APIName = $Request.Params.CIPPEndpoint + + try { + $CSVfile = New-CIPPBackup -BackupType 'CIPP' -Request $Request + $body = [pscustomobject]@{ + 'Results' = @{ + resultText = 'Created backup' + state = 'success' + } + backup = $CSVfile.BackupData + } | ConvertTo-Json -Depth 5 -Compress + + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Created CIPP backup' -Sev 'Info' + + } catch { + $body = [pscustomobject]@{ + 'Results' = @( + @{ + resultText = 'Failed to create backup' + state = 'error' + } + ) + } | ConvertTo-Json -Depth 5 -Compress + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Failed to create CIPP backup' -Sev 'Error' -LogData (Get-CippException -Exception $_) + } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecSAMAppPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecSAMAppPermissions.ps1 index 8aeeafdb6222..9b9ac162784a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecSAMAppPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecSAMAppPermissions.ps1 @@ -25,7 +25,7 @@ function Invoke-ExecSAMAppPermissions { $Body = @{ 'Results' = 'Permissions Updated' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'ExecSAMAppPermissions' -message 'CIPP-SAM Permissions Updated' -Sev 'Info' -LogData $Permissions + Write-LogMessage -headers $Request.Headers -API 'ExecSAMAppPermissions' -message 'CIPP-SAM Permissions Updated' -Sev 'Info' -LogData $Permissions } catch { $Body = @{ 'Results' = $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ListCustomRole.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ListCustomRole.ps1 new file mode 100644 index 000000000000..284be3d8095c --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ListCustomRole.ps1 @@ -0,0 +1,55 @@ +function Invoke-ListCustomRole { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + CIPP.Core.Read + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $Table = Get-CippTable -tablename 'CustomRoles' + + $Body = Get-CIPPAzDataTableEntity @Table + + if (!$Body) { + $Body = @( + @{ + RowKey = 'No custom roles found' + } + ) + } else { + $Body = foreach ($Role in $Body) { + try { + $Role.Permissions = $Role.Permissions | ConvertFrom-Json + } catch { + $Role.Permissions = '' + } + if ($Role.AllowedTenants) { + try { + $Role.AllowedTenants = @($Role.AllowedTenants | ConvertFrom-Json) + } catch { + $Role.AllowedTenants = '' + } + } else { + $Role | Add-Member -NotePropertyName AllowedTenants -NotePropertyValue @() -Force + } + if ($Role.BlockedTenants) { + try { + $Role.BlockedTenants = @($Role.BlockedTenants | ConvertFrom-Json) + } catch { + $Role.BlockedTenants = '' + } + } else { + $Role | Add-Member -NotePropertyName BlockedTenants -NotePropertyValue @() -Force + } + $Role + } + $Body = @($Body) + } + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $Body + }) +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Setup/Invoke-ExecSAMSetup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Setup/Invoke-ExecSAMSetup.ps1 index 9fdb71146215..c5c431ef50d4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Setup/Invoke-ExecSAMSetup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Setup/Invoke-ExecSAMSetup.ps1 @@ -7,6 +7,7 @@ Function Invoke-ExecSAMSetup { .ROLE CIPP.AppSettings.ReadWrite #> + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] [CmdletBinding()] param($Request, $TriggerMetadata) @@ -24,13 +25,13 @@ Function Invoke-ExecSAMSetup { Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ ContentType = 'text/html' StatusCode = [HttpStatusCode]::Forbidden - Body = 'Could not find an admin cookie in your browser. Make sure you do not have an adblocker active, use a Chromium browser, and allow cookies. If our automatic refresh does not work, try pressing the URL bar and hitting enter. We will try to refresh ourselves in 3 seconds.' + Body = 'Could not find an admin cookie in your browser, please confirm that you have the admin role in CIPP. Make sure you do not have an adblocker active, use a Chromium browser, and allow cookies. If our automatic refresh does not work, try pressing the URL bar and hitting enter. We will try to refresh ourselves in 3 seconds.' }) exit } - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') { $DevSecretsTable = Get-CIPPTable -tablename 'DevSecrets' $Secret = Get-CIPPAzDataTableEntity @DevSecretsTable -Filter "PartitionKey eq 'Secret' and RowKey eq 'Secret'" @@ -52,7 +53,7 @@ Function Invoke-ExecSAMSetup { } } if (!$ENV:SetFromProfile) { - Write-Host "We're reloading from KV" + Write-Information "We're reloading from KV" Get-CIPPAuthentication } @@ -76,15 +77,16 @@ Function Invoke-ExecSAMSetup { if ($Request.Body.applicationid) { Set-AzKeyVaultSecret -VaultName $kv -Name 'applicationid' -SecretValue (ConvertTo-SecureString -String $Request.Body.applicationid -AsPlainText -Force) } if ($Request.Body.applicationsecret) { Set-AzKeyVaultSecret -VaultName $kv -Name 'applicationsecret' -SecretValue (ConvertTo-SecureString -String $Request.Body.applicationsecret -AsPlainText -Force) } } + $Results = @{ Results = 'The keys have been replaced. Please perform a permissions check.' } } if ($Request.Query.error -eq 'invalid_client') { $Results = 'Client ID was not found in Azure. Try waiting 10 seconds to try again, if you have gotten this error after 5 minutes, please restart the process.' } if ($Request.Query.code) { try { $TenantId = $Rows.tenantid - if (!$TenantId) { $TenantId = $ENV:TenantID } + if (!$TenantId -or $TenantId -eq 'NotStarted') { $TenantId = $ENV:TenantID } $AppID = $Rows.appid - if (!$AppID) { $appid = $ENV:ApplicationID } + if (!$AppID -or $AppID -eq 'NotStarted') { $appid = $ENV:ApplicationID } $URL = ($Request.headers.'x-ms-original-url').split('?') | Select-Object -First 1 if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') { $clientsecret = $Secret.ApplicationSecret @@ -92,7 +94,7 @@ Function Invoke-ExecSAMSetup { $clientsecret = Get-AzKeyVaultSecret -VaultName $kv -Name 'ApplicationSecret' -AsPlainText } if (!$clientsecret) { $clientsecret = $ENV:ApplicationSecret } - Write-Host "client_id=$appid&scope=https://graph.microsoft.com/.default+offline_access+openid+profile&code=$($Request.Query.code)&grant_type=authorization_code&redirect_uri=$($url)&client_secret=$clientsecret" -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" + Write-Information "client_id=$appid&scope=https://graph.microsoft.com/.default+offline_access+openid+profile&code=$($Request.Query.code)&grant_type=authorization_code&redirect_uri=$($url)&client_secret=$clientsecret" #-Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" $RefreshToken = Invoke-RestMethod -Method POST -Body "client_id=$appid&scope=https://graph.microsoft.com/.default+offline_access+openid+profile&code=$($Request.Query.code)&grant_type=authorization_code&redirect_uri=$($url)&client_secret=$clientsecret" -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -ContentType 'application/x-www-form-urlencoded' if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') { @@ -140,7 +142,7 @@ Function Invoke-ExecSAMSetup { $step = 2 } $Token = (New-DeviceLogin -clientid '1b730954-1685-4b74-9bfd-dac224a7b894' -Scope 'https://graph.microsoft.com/.default' -device_code $SAMSetup.device_code) - Write-Host "Token is $($token | ConvertTo-Json)" + Write-Information "Token is $($token | ConvertTo-Json)" if ($Token.access_token) { $step = 2 $rows.SamSetup = [string]($Token | ConvertTo-Json) @@ -166,22 +168,22 @@ Function Invoke-ExecSAMSetup { try { $SPNDefender = (Invoke-RestMethod 'https://graph.microsoft.com/v1.0/servicePrincipals' -Headers @{ authorization = "Bearer $($Token.access_token)" } -Method POST -Body "{ `"appId`": `"fc780465-2017-40d4-a0c5-307022471b92`" }" -ContentType 'application/json') } catch { - Write-Host "didn't deploy spn for defender, probably already there." + Write-Information "didn't deploy spn for defender, probably already there." } try { $SPNTeams = (Invoke-RestMethod 'https://graph.microsoft.com/v1.0/servicePrincipals' -Headers @{ authorization = "Bearer $($Token.access_token)" } -Method POST -Body "{ `"appId`": `"48ac35b8-9aa8-4d74-927d-1f4a14a0b239`" }" -ContentType 'application/json') } catch { - Write-Host "didn't deploy spn for Teams, probably already there." + Write-Information "didn't deploy spn for Teams, probably already there." } try { $SPNO365Manage = (Invoke-RestMethod 'https://graph.microsoft.com/v1.0/servicePrincipals' -Headers @{ authorization = "Bearer $($Token.access_token)" } -Method POST -Body "{ `"appId`": `"c5393580-f805-4401-95e8-94b7a6ef2fc2`" }" -ContentType 'application/json') } catch { - Write-Host "didn't deploy spn for O365 Management, probably already there." + Write-Information "didn't deploy spn for O365 Management, probably already there." } try { $SPNPartnerCenter = (Invoke-RestMethod 'https://graph.microsoft.com/v1.0/servicePrincipals' -Headers @{ authorization = "Bearer $($Token.access_token)" } -Method POST -Body "{ `"appId`": `"fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd`" }" -ContentType 'application/json') } catch { - Write-Host "didn't deploy spn for PartnerCenter, probably already there." + Write-Information "didn't deploy spn for PartnerCenter, probably already there." } $SPN = (Invoke-RestMethod 'https://graph.microsoft.com/v1.0/servicePrincipals' -Headers @{ authorization = "Bearer $($Token.access_token)" } -Method POST -Body "{ `"appId`": `"$($AppId.appId)`" }" -ContentType 'application/json') Start-Sleep 3 diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilter.ps1 index e36aaea55402..51ea0dcc4908 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilter.ps1 @@ -11,11 +11,11 @@ Function Invoke-AddConnectionFilter { param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $RequestParams = $Request.Body.PowerShellCommand | - ConvertFrom-Json | + $RequestParams = $Request.Body.PowerShellCommand | + ConvertFrom-Json | Select-Object -Property *, @{Name='identity'; Expression={$_.name}} -ExcludeProperty GUID, comments, name $Tenants = ($Request.body.selectedTenants).value @@ -23,10 +23,10 @@ Function Invoke-AddConnectionFilter { try { $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Set-HostedConnectionFilterPolicy' -cmdParams $RequestParams "Successfully created Connectionfilter for $tenantfilter." - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Updated Connection filter rule for $($tenantfilter)" -sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenantfilter -message "Updated Connection filter rule for $($tenantfilter)" -sev Info } catch { "Could not create create Connection Filter rule for $($tenantfilter): $($_.Exception.message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Could not create create connection filter rule for $($tenantfilter): $($_.Exception.message)" -sev Error + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenantfilter -message "Could not create create connection filter rule for $($tenantfilter): $($_.Exception.message)" -sev Error } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilterTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilterTemplate.ps1 index 17b1fd994f4b..a6d509c168cf 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilterTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddConnectionFilterTemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddConnectionFilterTemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host ($request | ConvertTo-Json -Compress) try { @@ -35,12 +35,12 @@ Function Invoke-AddConnectionFilterTemplate { RowKey = "$GUID" PartitionKey = 'ConnectionfilterTemplate' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created Connection Filter Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created Connection Filter Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create Connection Filter Template: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to create Connection Filter Template: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "ConnectionFilter Template Deployment failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddContact.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddContact.ps1 index c52e2e60ffbd..454db172aab0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddContact.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddContact.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddContact { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $contactobj = $Request.body @@ -31,10 +31,10 @@ Function Invoke-AddContact { Write-Host ( $NewContact | ConvertTo-Json) New-ExoRequest -tenantid $Request.body.tenantid -cmdlet 'Set-MailContact' -cmdparams @{identity = $NewContact.id; HiddenFromAddressListsEnabled = [boolean]$contactobj.hidefromGAL } -UseSystemMailbox $true $body = [pscustomobject]@{'Results' = 'Successfully added a contact.' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($contactobj.tenantid) -message "Created contact $($contactobj.displayname) with id $($GraphRequest.id) for " -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($contactobj.tenantid) -message "Created contact $($contactobj.displayname) with id $($GraphRequest.id) for " -Sev 'Info' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($contactobj.tenantid) -message "Contact creation API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($contactobj.tenantid) -message "Contact creation API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to create contact. $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnector.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnector.ps1 index 6f54028ddeb6..b475be078c06 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnector.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnector.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddExConnector { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ConnectorType = ($Request.body.PowerShellCommand | ConvertFrom-Json).cippConnectorType $RequestParams = $Request.Body.PowerShellCommand | ConvertFrom-Json | Select-Object -Property * -ExcludeProperty GUID, cippConnectorType, comments @@ -21,10 +21,10 @@ Function Invoke-AddExConnector { try { $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet "New-$($ConnectorType)connector" -cmdParams $RequestParams "Successfully created Connector for $Tenantfilter." - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Tenantfilter -message "Created Connector for $($Tenantfilter)" -sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $Tenantfilter -message "Created Connector for $($Tenantfilter)" -sev 'Info' } catch { "Could not create created Connector for $($Tenantfilter): $($_.Exception.message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Tenantfilter -message "Could not create created Connector for $($Tenantfilter): $($_.Exception.message)" -sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $Tenantfilter -message "Could not create created Connector for $($Tenantfilter): $($_.Exception.message)" -sev 'Error' } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnectorTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnectorTemplate.ps1 index 222c01f420ff..a91f35176339 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnectorTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddExConnectorTemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddExConnectorTemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host ($request | ConvertTo-Json -Compress) @@ -41,11 +41,11 @@ Function Invoke-AddExConnectorTemplate { direction = $request.body.cippconnectortype PartitionKey = 'ExConnectorTemplate' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created Connector Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created Connector Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create Connector Template: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to create Connector Template: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Connector Template creation failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddRoomMailbox.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddRoomMailbox.ps1 index 11b662d34d47..0951cd7a3c09 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddRoomMailbox.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddRoomMailbox.ps1 @@ -1,5 +1,3 @@ -using namespace System.Net - Function Invoke-AddRoomMailbox { <# .FUNCTIONALITY @@ -10,18 +8,13 @@ Function Invoke-AddRoomMailbox { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' - - # Write to the Azure Functions log stream. - Write-Host 'PowerShell HTTP trigger function processed a request.' - + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $Tenant = $Request.body.tenantid + $User = $Request.Headers $Results = [System.Collections.Generic.List[Object]]::new() $MailboxObject = $Request.body - $Tenant = $MailboxObject.tenantid $AddRoomParams = [pscustomobject]@{ Name = $MailboxObject.username DisplayName = $MailboxObject.displayName @@ -34,11 +27,11 @@ Function Invoke-AddRoomMailbox { try { $AddRoomRequest = New-ExoRequest -tenantid $Tenant -cmdlet 'New-Mailbox' -cmdparams $AddRoomParams $Results.Add("Successfully created room: $($MailboxObject.DisplayName).") - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Created room $($MailboxObject.DisplayName) with id $($AddRoomRequest.id)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Created room $($MailboxObject.DisplayName) with id $($AddRoomRequest.id)" -Sev 'Info' # Block sign-in for the mailbox try { - $Request = Set-CIPPSignInState -userid $AddRoomRequest.ExternalDirectoryObjectId -TenantFilter $Tenant -APIName $APINAME -ExecutingUser $User -AccountEnabled $false + $Request = Set-CIPPSignInState -userid $AddRoomRequest.ExternalDirectoryObjectId -TenantFilter $Tenant -APIName $APINAME -Headers $User -AccountEnabled $false $Results.add("Blocked sign-in for Room mailbox; $($MailboxObject.userPrincipalName)") } catch { $ErrorMessage = Get-CippException -Exception $_ @@ -47,7 +40,7 @@ Function Invoke-AddRoomMailbox { $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Failed to create room: $($MailboxObject.DisplayName). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Failed to create room: $($MailboxObject.DisplayName). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $Results.Add("Failed to create Room mailbox $($MailboxObject.userPrincipalName). $($ErrorMessage.NormalizedError)") $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSharedMailbox.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSharedMailbox.ps1 index acf3d26dc1bf..d79795c18fa0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSharedMailbox.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSharedMailbox.ps1 @@ -10,10 +10,10 @@ Function Invoke-AddSharedMailbox { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -34,15 +34,15 @@ Function Invoke-AddSharedMailbox { } $AddSharedRequest = New-ExoRequest -tenantid $Tenant -cmdlet 'New-Mailbox' -cmdparams $BodyToShip $Body = $Results.add("Successfully created shared mailbox: $Email.") - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Created shared mailbox $($MailboxObject.displayname) with email $Email" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Created shared mailbox $($MailboxObject.displayname) with email $Email" -Sev 'Info' # Block sign-in for the mailbox try { - $null = Set-CIPPSignInState -userid $AddSharedRequest.ExternalDirectoryObjectId -TenantFilter $Tenant -APIName $APINAME -ExecutingUser $User -AccountEnabled $false + $null = Set-CIPPSignInState -userid $AddSharedRequest.ExternalDirectoryObjectId -TenantFilter $Tenant -APIName $APINAME -Headers $User -AccountEnabled $false $Body = $Results.add("Blocked sign-in for shared mailbox $Email") } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Failed to block sign-in for shared mailbox $Email. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Failed to block sign-in for shared mailbox $Email. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $Body = $Results.add("Failed to block sign-in for shared mailbox $Email. Error: $($ErrorMessage.NormalizedError)") } @@ -55,19 +55,19 @@ Function Invoke-AddSharedMailbox { 'EmailAddresses' = @{'@odata.type' = '#Exchange.GenericHashTable'; Add = $Aliases } } $null = New-ExoRequest -tenantid $Tenant -cmdlet 'Set-Mailbox' -cmdparams $AliasBodyToShip -UseSystemMailbox $true - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Added aliases to $Email : $($Aliases -join ',')" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Added aliases to $Email : $($Aliases -join ',')" -Sev 'Info' $Body = $results.add("Added Aliases to $Email : $($Aliases -join ',')") } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Failed to add aliases to $Email : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Failed to add aliases to $Email : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $Body = $results.add("ERROR: Failed to add aliases to $Email : $($ErrorMessage.NormalizedError)") } } $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Failed to create shared mailbox. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Failed to create shared mailbox. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $Body = $Results.add("Failed to create Shared Mailbox. $($ErrorMessage.NormalizedError)") $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilter.ps1 index 7d267b3c8ac1..88def6633399 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilter.ps1 @@ -11,8 +11,8 @@ Function Invoke-AddSpamFilter { param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $RequestParams = $Request.Body.PowerShellCommand | ConvertFrom-Json | Select-Object -Property * -ExcludeProperty GUID, comments $RequestPriority = $Request.Body.Priority @@ -31,10 +31,10 @@ Function Invoke-AddSpamFilter { } $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet 'New-HostedContentFilterRule' -cmdParams $ruleparams "Successfully created spamfilter for $tenantfilter." - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Created spamfilter rule for $($tenantfilter)" -sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenantfilter -message "Created spamfilter rule for $($tenantfilter)" -sev Info } catch { "Could not create create spamfilter rule for $($tenantfilter): $($_.Exception.message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Could not create create spamfilter rule for $($tenantfilter): $($_.Exception.message)" -sev Error + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenantfilter -message "Could not create create spamfilter rule for $($tenantfilter): $($_.Exception.message)" -sev Error } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilterTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilterTemplate.ps1 index 37cf34b88916..46e692cd809e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilterTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddSpamFilterTemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddSpamFilterTemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host ($request | ConvertTo-Json -Compress) try { @@ -34,12 +34,12 @@ Function Invoke-AddSpamFilterTemplate { RowKey = "$GUID" PartitionKey = 'SpamfilterTemplate' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created Spam Filter Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created Spam Filter Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create Spam Filter Template: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to create Spam Filter Template: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Spamfilter Template Deployment failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportRule.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportRule.ps1 index fae7f8b60e5f..18c1c71e134d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportRule.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportRule.ps1 @@ -10,9 +10,9 @@ Function Invoke-AddTransportRule { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExetutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExetutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $ExecutingUser = $Request.Headers + Write-LogMessage -Headers $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' $RequestParams = $Request.Body.PowerShellCommand | ConvertFrom-Json | Select-Object -Property * -ExcludeProperty GUID, HasSenderOverride, ExceptIfHasSenderOverride, ExceptIfMessageContainsDataClassifications, MessageContainsDataClassifications @@ -31,11 +31,11 @@ Function Invoke-AddTransportRule { "Successfully created transport rule for $tenantFilter." } - Write-LogMessage -user $ExetutingUser -API $APINAME -tenant $tenantFilter -message "Created transport rule for $($tenantFilter)" -sev Info + Write-LogMessage -Headers $ExecutingUser -API $APINAME -tenant $tenantFilter -message "Created transport rule for $($tenantFilter)" -sev Info } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not create transport rule for $($tenantFilter): $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $ExetutingUser -API $APINAME -tenant $tenantFilter -message "Could not create transport rule for $($tenantFilter). Error:$($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $ExecutingUser -API $APINAME -tenant $tenantFilter -message "Could not create transport rule for $($tenantFilter). Error:$($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportTemplate.ps1 index 9c176d7c8939..ecf773ddb29f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-AddTransportTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-AddTransportTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev Debug + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev Debug Write-Host ($request | ConvertTo-Json -Depth 10 -Compress) try { @@ -35,12 +35,12 @@ Function Invoke-AddTransportTemplate { RowKey = "$GUID" PartitionKey = 'TransportTemplate' } - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Created Transport Rule Template $($Request.body.name) with GUID $GUID" -Sev Debug + Write-LogMessage -Headers $Headers -API $APINAME -message "Created Transport Rule Template $($Request.body.name) with GUID $GUID" -Sev Debug $body = [pscustomobject]@{'Results' = "Created Transport Rule Template $($Request.body.name) with GUID $GUID" } $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Failed to create Transport Rule Template: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Failed to create Transport Rule Template: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to create Transport Rule Template: $($ErrorMessage.NormalizedError)" } $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditAntiPhishingFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditAntiPhishingFilter.ps1 index 979da9a1c9b6..feaa27471516 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditAntiPhishingFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditAntiPhishingFilter.ps1 @@ -8,8 +8,8 @@ function Invoke-EditAntiPhishingFilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -40,11 +40,11 @@ function Invoke-EditAntiPhishingFilter { New-ExoRequest @ExoRequestParam $Result = "Sucessfully set Anti-Phishing rule $($Request.query.RuleName) to $($Request.query.State)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev Info } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $Result = "Failed setting Anti-Phishing rule $($Request.query.RuleName) to $($request.query.State). Error: $ErrorMessage" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditContact.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditContact.ps1 index 03a6b21254bb..f08ca3c40bdf 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditContact.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditContact.ps1 @@ -10,44 +10,54 @@ Function Invoke-EditContact { [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 = $Request.Params.CIPPEndpoint + $TenantID = $Request.body.tenantID + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $contactobj = $Request.body - write-host "This is the contact object: $contactobj" - # Write to the Azure Functions log stream. - Write-Host 'PowerShell HTTP trigger function processed a request.' try { - - $BodyToship = [pscustomobject] @{ - 'DisplayName' = $contactobj.DisplayName - 'WindowsEmailAddress' = $contactobj.mail - 'FirstName' = $contactObj.firstName - 'LastName' = $contactobj.LastName - "Title" = $contactobj.jobTitle - "StreetAddress" = $contactobj.StreetAddress - "PostalCode" = $contactobj.PostalCode - "City" = $contactobj.City - "CountryOrRegion" = $contactobj.Country - "Company" = $contactobj.companyName - "mobilePhone" = $contactobj.MobilePhone - "phone" = $contactobj.BusinessPhone - 'identity' = $contactobj.ContactID + # Extract contact information from the request body + $contactInfo = $Request.body + + # Log the received contact object + Write-Host "Received contact object: $($contactInfo | ConvertTo-Json)" + + # Prepare the body for the Set-Contact cmdlet + $bodyForSetContact = [pscustomobject] @{ + 'Identity' = $contactInfo.ContactID + 'DisplayName' = $contactInfo.displayName + 'WindowsEmailAddress' = $contactInfo.email + 'FirstName' = $contactInfo.firstName + 'LastName' = $contactInfo.LastName + 'Title' = $contactInfo.Title + 'StreetAddress' = $contactInfo.StreetAddress + 'PostalCode' = $contactInfo.PostalCode + 'City' = $contactInfo.City + 'CountryOrRegion' = $contactInfo.CountryOrRegion + 'Company' = $contactInfo.Company + 'mobilePhone' = $contactInfo.mobilePhone + 'phone' = $contactInfo.phone } - $EditContact = New-ExoRequest -tenantid $Request.body.tenantID -cmdlet 'Set-Contact' -cmdparams $BodyToship -UseSystemMailbox $true - $Results = [pscustomobject]@{'Results' = "Successfully edited contact $($contactobj.Displayname)" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($contactobj.tenantid) -message "Created contact $($contactobj.displayname)" -Sev 'Info' - } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($contactobj.tenantid) -message "Contact creation API failed. $($_.Exception.Message)" -Sev 'Error' - $Results = [pscustomobject]@{'Results' = "Failed to edit contact. $($_.Exception.Message)" } + # Call the Set-Contact cmdlet to update the contact + $null = New-ExoRequest -tenantid $TenantID -cmdlet 'Set-Contact' -cmdParams $bodyForSetContact -UseSystemMailbox $true + $null = New-ExoRequest -tenantid $TenantID -cmdlet 'Set-MailContact' -cmdParams @{Identity = $contactInfo.ContactID; HiddenFromAddressListsEnabled = [System.Convert]::ToBoolean($contactInfo.hidefromGAL) } -UseSystemMailbox $true + $Results = "Successfully edited contact $($contactInfo.DisplayName)" + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantID -message $Results -Sev Info + $StatusCode = [HttpStatusCode]::OK + } catch { + $ErrorMessage = Get-CippException -Exception $_ + $Results = "Failed to edit contact. $($ErrorMessage.NormalizedError)" + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantID -message $Results -Sev Error -LogData $ErrorMessage + $StatusCode = [HttpStatusCode]::InternalServerError } + + $Results = [pscustomobject]@{'Results' = "$Results" } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK + StatusCode = $StatusCode Body = $Results }) - } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditExConnector.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditExConnector.ps1 index 35b181507cda..904f9d2c826e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditExConnector.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditExConnector.ps1 @@ -10,29 +10,33 @@ Function Invoke-EditExConnector { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $Request.Headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $Tenantfilter = $request.Query.tenantfilter ?? $Request.Body.tenantfilter + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $TenantFilter = $Request.Query.tenantFilter ?? $Request.Body.tenantFilter try { $ConnectorState = $Request.Query.State ?? $Request.Body.State - $State = if ($ConnectorState -eq 'enable') { $true } else { $false } + $State = if ($ConnectorState -eq 'Enable') { $true } else { $false } $Guid = $Request.Query.GUID ?? $Request.Body.GUID - $type = $Request.Query.Type ?? $Request.Body.Type + $Type = $Request.Query.Type ?? $Request.Body.Type $Params = @{ Identity = $Guid Enabled = $State } - $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet "Set-$($Type)Connector" -cmdParams $params -UseSystemMailbox $true + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-$($Type)Connector" -cmdParams $params -UseSystemMailbox $true $Result = "Set Connector $($Guid) to $($ConnectorState)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Set Connector $($Request.query.guid) to $($request.query.State)" -sev 'Info' + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantFilter -message "Set Connector $($Guid) to $($ConnectorState)" -sev Info + $StatusCode = [HttpStatusCode]::OK } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Failed setting Connector $($Guid) to $($ConnectorState). Error:$($_.Exception.Message)" -Sev 'Error' - $ErrorMessage = Get-NormalizedError -Message $_.Exception - $Result = $ErrorMessage + $ErrorMessage = Get-CIPPException -Exception $_ + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantFilter -message "Failed setting Connector $($Guid) to $($ConnectorState). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + $Result = $ErrorMessage.NormalizedError + $StatusCode = [HttpStatusCode]::Forbidden } + # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK + StatusCode = $StatusCode Body = @{Results = $Result } }) diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditMalwareFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditMalwareFilter.ps1 index 550cd11dce80..315596cb252e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditMalwareFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditMalwareFilter.ps1 @@ -8,8 +8,8 @@ function Invoke-EditMalwareFilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -40,11 +40,11 @@ function Invoke-EditMalwareFilter { New-ExoRequest @ExoRequestParam $Result = "Sucessfully set Malware Filter rule $($Request.query.RuleName) to $($Request.query.State)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev Info } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $Result = "Failed setting Malware Filter rule $($Request.query.RuleName) to $($request.query.State). Error: $ErrorMessage" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditRoomMailbox.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditRoomMailbox.ps1 new file mode 100644 index 000000000000..fda1275a1956 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditRoomMailbox.ps1 @@ -0,0 +1,82 @@ +using namespace System.Net + +Function Invoke-EditRoomMailbox { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + Exchange.Room.ReadWrite + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $APIName = $TriggerMetadata.FunctionName + $Tenant = $Request.body.tenantid + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Accessed this API' -Sev 'Debug' + + + $Results = [System.Collections.Generic.List[Object]]::new() + $MailboxObject = $Request.body + + # First update the mailbox properties + $UpdateMailboxParams = @{ + Identity = $MailboxObject.roomId + DisplayName = $MailboxObject.displayName + } + + if (![string]::IsNullOrWhiteSpace($MailboxObject.capacity)) { + $UpdateMailboxParams.Add('ResourceCapacity', $MailboxObject.capacity) + } + if (![string]::IsNullOrWhiteSpace($MailboxObject.hiddenFromAddressListsEnabled)) { + $UpdateMailboxParams.Add('HiddenFromAddressListsEnabled', $MailboxObject.hiddenFromAddressListsEnabled) + } + + + # Then update the place properties + $UpdatePlaceParams = @{ + Identity = $MailboxObject.roomId + } + + # Add optional parameters if they exist + $PlaceProperties = @( + 'Building', 'Floor', 'FloorLabel', 'Phone', + 'AudioDeviceName', 'VideoDeviceName', 'DisplayDeviceName', + 'IsWheelChairAccessible', 'Tags', + 'Street', 'City', 'State', 'CountryOrRegion', 'Desks', + 'PostalCode', 'Localities', 'SpaceType', 'CustomSpaceType', + 'ResourceLinks' + ) + + foreach ($prop in $PlaceProperties) { + if (![string]::IsNullOrWhiteSpace($MailboxObject.$prop)) { + $UpdatePlaceParams[$prop] = $MailboxObject.$prop + } + } + + try { + # Update mailbox properties + $null = New-ExoRequest -tenantid $Tenant -cmdlet 'Set-Mailbox' -cmdParams $UpdateMailboxParams + + # Update place properties + $null = New-ExoRequest -tenantid $Tenant -cmdlet 'Set-Place' -cmdParams $UpdatePlaceParams + $Results.Add("Successfully updated room: $($MailboxObject.DisplayName)") + + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $Tenant -message "Updated room $($MailboxObject.DisplayName)" -Sev 'Info' + $StatusCode = [HttpStatusCode]::OK + + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $Tenant -message "Failed to update room: $($MailboxObject.DisplayName). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $Results.Add("Failed to update Room mailbox $($MailboxObject.userPrincipalName). $($ErrorMessage.NormalizedError)") + + $StatusCode = [HttpStatusCode]::Forbidden + } + + $Body = [pscustomobject]@{ 'Results' = @($Results) } + + # Associate values to output bindings by calling 'Push-OutputBinding'. + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = $StatusCode + Body = $Body + }) +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeAttachmentsFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeAttachmentsFilter.ps1 index 15b3e4a489e4..b552059cabf8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeAttachmentsFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeAttachmentsFilter.ps1 @@ -8,8 +8,8 @@ function Invoke-EditSafeAttachmentsFilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -40,11 +40,11 @@ function Invoke-EditSafeAttachmentsFilter { New-ExoRequest @ExoRequestParam $Result = "Sucessfully set SafeAttachment rule $($Request.query.RuleName) to $($Request.query.State)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev Info } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $Result = "Failed setting SafeAttachment rule $($Request.query.RuleName) to $($request.query.State). Error: $ErrorMessage" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeLinksFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeLinksFilter.ps1 index d6263d9103cf..9d1663070e2e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeLinksFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSafeLinksFilter.ps1 @@ -8,8 +8,8 @@ function Invoke-EditSafeLinksFilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -40,11 +40,11 @@ function Invoke-EditSafeLinksFilter { New-ExoRequest @ExoRequestParam $Result = "Sucessfully set SafeLinks rule $($Request.query.RuleName) to $($Request.query.State)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev Info } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $Result = "Failed setting SafeLinks rule $($Request.query.RuleName) to $($request.query.State). Error: $ErrorMessage" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message $Result -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSpamFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSpamFilter.ps1 index 931299cb6102..f4bcef687f68 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSpamFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditSpamFilter.ps1 @@ -10,8 +10,8 @@ Function Invoke-EditSpamFilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter $Params = @{ @@ -22,10 +22,10 @@ Function Invoke-EditSpamFilter { $cmdlet = if ($request.query.state -eq 'enable') { 'Enable-HostedContentFilterRule' } else { 'Disable-HostedContentFilterRule' } $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet $cmdlet -cmdParams $params -useSystemmailbox $true $Result = "Set Spamfilter rule to $($request.query.State)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Set Spamfilter rule $($Request.query.name) to $($request.query.State)" -sev Info + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenantfilter -message "Set Spamfilter rule $($Request.query.name) to $($request.query.State)" -sev Info } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantfilter -message "Failed setting Spamfilter rule $($Request.query.guid) to $($request.query.State). Error:$ErrorMessage" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenantfilter -message "Failed setting Spamfilter rule $($Request.query.guid) to $($request.query.State). Error:$ErrorMessage" -Sev 'Error' $Result = $ErrorMessage } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditTransportRule.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditTransportRule.ps1 index eb8f57c38f10..87ec4164e9d8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditTransportRule.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-EditTransportRule.ps1 @@ -10,9 +10,9 @@ Function Invoke-EditTransportRule { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Query.tenantFilter ?? $Request.body.tenantFilter $Identity = $Request.Query.guid ?? $Request.body.guid @@ -26,11 +26,11 @@ Function Invoke-EditTransportRule { $cmdlet = if ($State -eq 'enable') { 'Enable-TransportRule' } else { 'Disable-TransportRule' } $null = New-ExoRequest -tenantid $TenantFilter -cmdlet $cmdlet -cmdParams $params -UseSystemMailbox $true $Result = "Set transport rule $($Identity) to $($State)" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message $Result -sev Info + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantFilter -message $Result -sev Info $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Failed setting transport rule $($Identity) to $($State). Error:$($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantFilter -message "Failed setting transport rule $($Identity) to $($State). Error:$($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $Result = $ErrorMessage.NormalizedError $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoRoomMailbox.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoRoomMailbox.ps1 index 8d64cb14e527..0631d7afa78a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoRoomMailbox.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoRoomMailbox.ps1 @@ -10,16 +10,16 @@ Function Invoke-ExecConvertToRoomMailbox { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' # Interact with query parameters or the body of the request. Try { - $ConvertedMailbox = Set-CIPPMailboxType -userid $Request.query.id -tenantFilter $Request.query.TenantFilter -APIName $APINAME -ExecutingUser $User -MailboxType 'Room' + $ConvertedMailbox = Set-CIPPMailboxType -userid $Request.query.id -tenantFilter $Request.query.TenantFilter -APIName $APINAME -Headers $User -MailboxType 'Room' $Results = [pscustomobject]@{'Results' = "$ConvertedMailbox" } $StatusCode = [HttpStatusCode]::OK } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoSharedMailbox.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoSharedMailbox.ps1 index 30b5ab753120..b704bac3dd5b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoSharedMailbox.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecConverttoSharedMailbox.ps1 @@ -10,10 +10,10 @@ Function Invoke-ExecConverttoSharedMailbox { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $Tenant = $Request.query.TenantFilter - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -22,7 +22,7 @@ Function Invoke-ExecConverttoSharedMailbox { # Interact with query parameters or the body of the request. Try { $MailboxType = if ($request.query.ConvertToUser -eq 'true') { 'Regular' } else { 'Shared' } - $ConvertedMailbox = Set-CIPPMailboxType -userid $Request.query.id -tenantFilter $Tenant -APIName $APINAME -ExecutingUser $User -MailboxType $MailboxType + $ConvertedMailbox = Set-CIPPMailboxType -userid $Request.query.id -tenantFilter $Tenant -APIName $APINAME -Headers $User -MailboxType $MailboxType $Results = [pscustomobject]@{'Results' = "$ConvertedMailbox" } $StatusCode = [HttpStatusCode]::OK } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecCopyForSent.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecCopyForSent.ps1 index 4aadbd74c563..f3f9b27e6b11 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecCopyForSent.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecCopyForSent.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecCopyForSent { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -21,7 +21,7 @@ Function Invoke-ExecCopyForSent { # Interact with query parameters or the body of the request. Try { $MessageCopyForSentAsEnabled = if ($request.query.MessageCopyForSentAsEnabled -eq 'false') { 'false' } else { 'true' } - $MessageResult = Set-CIPPMessageCopy -userid $Request.query.id -tenantFilter $Request.query.TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' -MessageCopyForSentAsEnabled $MessageCopyForSentAsEnabled + $MessageResult = Set-CIPPMessageCopy -userid $Request.query.id -tenantFilter $Request.query.TenantFilter -APIName $APINAME -Headers $Request.Headers -MessageCopyForSentAsEnabled $MessageCopyForSentAsEnabled $Results = [pscustomobject]@{'Results' = "$MessageResult" } } catch { $Results = [pscustomobject]@{'Results' = "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed - $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditCalendarPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditCalendarPermissions.ps1 index fbc9b085a552..eb644addef25 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditCalendarPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditCalendarPermissions.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecEditCalendarPermissions { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Extract parameters from query or body $TenantFilter = if ($Request.query.TenantFilter) { $Request.query.TenantFilter } else { $Request.Body.TenantFilter } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditMailboxPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditMailboxPermissions.ps1 index d017f8ae65a4..4743382dd6c9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditMailboxPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEditMailboxPermissions.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecEditMailboxPermissions { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME-message 'Accessed this API' -Sev 'Debug' $Username = $request.body.userID $Tenantfilter = $request.body.tenantfilter if ($username -eq $null) { exit } @@ -23,9 +23,9 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Remove-mailboxpermission' -cmdParams @{Identity = $userid; user = $RemoveUser; accessRights = @('FullAccess'); } $results.add("Removed $($removeuser) from $($username) Shared Mailbox permissions") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Removed $($RemoveUser) from $($username) Shared Mailbox permission" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Removed $($RemoveUser) from $($username) Shared Mailbox permission" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not remove mailbox permissions for $($removeuser) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not remove mailbox permissions for $($removeuser) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add("Could not remove $($removeuser) shared mailbox permissions for $($username). Error: $($_.Exception.Message)") } } @@ -35,10 +35,10 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Add-MailboxPermission' -cmdParams @{Identity = $userid; user = $UserAutomap; accessRights = @('FullAccess'); automapping = $true } $results.add( "Granted $($UserAutomap) access to $($username) Mailbox with automapping") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Granted $($UserAutomap) access to $($username) Mailbox with automapping" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Granted $($UserAutomap) access to $($username) Mailbox with automapping" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not add mailbox permissions for $($UserAutomap) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not add mailbox permissions for $($UserAutomap) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add( "Could not add $($UserAutomap) shared mailbox permissions for $($username). Error: $($_.Exception.Message)") } } @@ -48,9 +48,9 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Add-MailboxPermission' -cmdParams @{Identity = $userid; user = $UserNoAutomap; accessRights = @('FullAccess'); automapping = $false } $results.add( "Granted $UserNoAutomap access to $($username) Mailbox without automapping") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Granted $UserNoAutomap access to $($username) Mailbox without automapping" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Granted $UserNoAutomap access to $($username) Mailbox without automapping" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not add mailbox permissions for $($UserNoAutomap) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not add mailbox permissions for $($UserNoAutomap) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add("Could not add $($UserNoAutomap) shared mailbox permissions for $($username). Error: $($_.Exception.Message)") } } @@ -61,9 +61,9 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Add-RecipientPermission' -cmdParams @{Identity = $userid; Trustee = $UserSendAs; accessRights = @('SendAs') } $results.add( "Granted $UserSendAs access to $($username) with Send As permissions") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Granted $UserSendAs access to $($username) with Send As permissions" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Granted $UserSendAs access to $($username) with Send As permissions" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not add mailbox permissions for $($UserSendAs) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not add mailbox permissions for $($UserSendAs) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add("Could not add $($UserSendAs) send-as permissions for $($username). Error: $($_.Exception.Message)") } } @@ -74,9 +74,9 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Remove-RecipientPermission' -cmdParams @{Identity = $userid; Trustee = $UserSendAs; accessRights = @('SendAs') } $results.add( "Removed $UserSendAs from $($username) with Send As permissions") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Removed $UserSendAs from $($username) with Send As permissions" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Removed $UserSendAs from $($username) with Send As permissions" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not remove mailbox permissions for $($UserSendAs) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not remove mailbox permissions for $($UserSendAs) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add("Could not remove $($UserSendAs) send-as permissions for $($username). Error: $($_.Exception.Message)") } } @@ -87,9 +87,9 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; GrantSendonBehalfTo = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $UserSendOnBehalf }; } $results.add( "Granted $UserSendOnBehalf access to $($username) with Send On Behalf Permissions") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Granted $UserSendOnBehalf access to $($username) with Send On Behalf Permissions" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Granted $UserSendOnBehalf access to $($username) with Send On Behalf Permissions" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not add send on behalf permissions for $($UserSendOnBehalf) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not add send on behalf permissions for $($UserSendOnBehalf) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add("Could not add $($UserSendOnBehalf) send on behalf permissions for $($username). Error: $($_.Exception.Message)") } } @@ -100,9 +100,9 @@ Function Invoke-ExecEditMailboxPermissions { try { $MailboxPerms = New-ExoRequest -Anchor $username -tenantid $Tenantfilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; GrantSendonBehalfTo = @{'@odata.type' = '#Exchange.GenericHashTable'; remove = $UserSendOnBehalf }; } $results.add( "Removed $UserSendOnBehalf from $($username) Send on Behalf Permissions") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Removed $UserSendOnBehalf from $($username) Send on Behalf Permissions" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Removed $UserSendOnBehalf from $($username) Send on Behalf Permissions" -Sev 'Info' -tenant $TenantFilter } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME-message "Could not Remove send on behalf permissions for $($UserSendOnBehalf) on $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME-message "Could not Remove send on behalf permissions for $($UserSendOnBehalf) on $($username)" -Sev 'Error' -tenant $TenantFilter $results.add("Could not remove $($UserSendOnBehalf) send on behalf permissions for $($username). Error: $($_.Exception.Message)") } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEmailForward.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEmailForward.ps1 index 1886cb55375b..955606318b02 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEmailForward.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEmailForward.ps1 @@ -15,19 +15,19 @@ Function Invoke-ExecEmailForward { $ForwardingAddress = $request.body.ForwardInternal.value $ForwardingSMTPAddress = $request.body.ForwardExternal $ForwardOption = $request.body.forwardOption - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint [bool]$KeepCopy = if ($request.body.keepCopy -eq 'true') { $true } else { $false } if ($ForwardOption -eq 'internalAddress') { try { - Set-CIPPForwarding -userid $username -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' -Forward $ForwardingAddress -keepCopy $KeepCopy + Set-CIPPForwarding -userid $username -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers -Forward $ForwardingAddress -keepCopy $KeepCopy if (-not $request.body.KeepCopy) { $results = "Forwarding all email for $($username) to $($ForwardingAddress) and not keeping a copy" } else { $results = "Forwarding all email for $($username) to $($ForwardingAddress) and keeping a copy" } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not add forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Could not add forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter $results = "Could not add forwarding for $($username). Error: $($_.Exception.Message)" } @@ -35,14 +35,14 @@ Function Invoke-ExecEmailForward { if ($ForwardOption -eq 'ExternalAddress') { try { - Set-CIPPForwarding -userid $username -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' -forwardingSMTPAddress $ForwardingSMTPAddress -keepCopy $KeepCopy + Set-CIPPForwarding -userid $username -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers -forwardingSMTPAddress $ForwardingSMTPAddress -keepCopy $KeepCopy if (-not $request.body.KeepCopy) { $results = "Forwarding all email for $($username) to $($ForwardingSMTPAddress) and not keeping a copy" } else { $results = "Forwarding all email for $($username) to $($ForwardingSMTPAddress) and keeping a copy" } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not add forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Could not add forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter $results = "Could not add forwarding for $($username). Error: $($_.Exception.Message)" } @@ -51,10 +51,10 @@ Function Invoke-ExecEmailForward { if ($ForwardOption -eq 'disabled') { try { - Set-CIPPForwarding -userid $username -username $username -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName -Disable $true + Set-CIPPForwarding -userid $username -username $username -tenantFilter $Tenantfilter -Headers $Request.Headers -APIName $APIName -Disable $true $results = "Disabled Email Forwarding for $($username)" } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not disable Email forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Could not disable Email forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter $results = "Could not disable Email forwarding for $($username). Error: $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEnableArchive.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEnableArchive.ps1 index f1dfb475b1cd..599b50ee0f34 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEnableArchive.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecEnableArchive.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecEnableArchive { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -20,7 +20,7 @@ Function Invoke-ExecEnableArchive { # Interact with query parameters or the body of the request. Try { - $ResultsArch = Set-CIPPMailboxArchive -userid $Request.query.id -tenantFilter $Request.query.TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' -ArchiveEnabled $true + $ResultsArch = Set-CIPPMailboxArchive -userid $Request.query.id -tenantFilter $Request.query.TenantFilter -APIName $APINAME -Headers $Request.Headers -ArchiveEnabled $true $Results = [pscustomobject]@{'Results' = "$ResultsArch" } } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDelete.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDelete.ps1 index d66af4964171..6dc149972be2 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDelete.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDelete.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecGroupsDelete { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -20,7 +20,7 @@ Function Invoke-ExecGroupsDelete { # Interact with query parameters or the body of the request. Try { - $RemoveResults = Remove-CIPPGroup -ID $Request.query.id -GroupType $Request.query.GroupType -tenantFilter $Request.query.TenantFilter -displayName $Request.query.displayName -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $RemoveResults = Remove-CIPPGroup -ID $Request.query.id -GroupType $Request.query.GroupType -tenantFilter $Request.query.TenantFilter -displayName $Request.query.displayName -APIName $APINAME -Headers $Request.Headers $Results = [pscustomobject]@{'Results' = $RemoveResults } } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDeliveryManagement.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDeliveryManagement.ps1 index 1f096507bd61..5d7c0c45bc92 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDeliveryManagement.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsDeliveryManagement.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecGroupsDeliveryManagement { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -20,11 +20,11 @@ Function Invoke-ExecGroupsDeliveryManagement { # Interact with query parameters or the body of the request. Try { - $SetResults = Set-CIPPGroupAuthentication -ID $Request.query.id -GroupType $Request.query.GroupType -OnlyAllowInternalString $Request.query.OnlyAllowInternal -tenantFilter $Request.query.TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $SetResults = Set-CIPPGroupAuthentication -ID $Request.query.id -GroupType $Request.query.GroupType -OnlyAllowInternalString $Request.query.OnlyAllowInternal -tenantFilter $Request.query.TenantFilter -APIName $APINAME -Headers $Request.Headers $Results = [pscustomobject]@{'Results' = $SetResults } } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Delivery Management failed: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Delivery Management failed: $($_.Exception.Message)" -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsHideFromGAL.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsHideFromGAL.ps1 index caf559918240..b8bfa298cf6c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsHideFromGAL.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecGroupsHideFromGAL.ps1 @@ -10,16 +10,16 @@ Function Invoke-ExecGroupsHideFromGAL { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. Try { - $GroupStatus = Set-CIPPGroupGAL -Id $Request.query.id -tenantFilter $Request.query.TenantFilter -GroupType $Request.query.groupType -HiddenString $Request.query.HidefromGAL -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $GroupStatus = Set-CIPPGroupGAL -Id $Request.query.id -tenantFilter $Request.query.TenantFilter -GroupType $Request.query.groupType -HiddenString $Request.query.HidefromGAL -APIName $APINAME -Headers $Request.Headers $Results = [pscustomobject]@{'Results' = $GroupStatus } } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Hide/UnHide from GAL failed: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Hide/UnHide from GAL failed: $($_.Exception.Message)" -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecHideFromGAL.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecHideFromGAL.ps1 index 145a0ed7c46d..21b234e9bfd5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecHideFromGAL.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecHideFromGAL.ps1 @@ -10,10 +10,9 @@ Function Invoke-ExecHideFromGAL { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $Headers = $Request.Headers + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Support if the request is a POST or a GET. So to support legacy(GET) and new(POST) requests @@ -23,7 +22,7 @@ Function Invoke-ExecHideFromGAL { Try { - $HideResults = Set-CIPPHideFromGAL -tenantFilter $TenantFilter -UserID $UserId -hidefromgal $Hidden -ExecutingUser $ExecutingUser -APIName $APIName + $HideResults = Set-CIPPHideFromGAL -tenantFilter $TenantFilter -UserID $UserId -hidefromgal $Hidden -Headers $Request.Headers -APIName $APIName $Results = [pscustomobject]@{'Results' = $HideResults } $StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailTest.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailTest.ps1 index a80a812b45d6..52281c5e24d4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailTest.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailTest.ps1 @@ -9,8 +9,8 @@ Function Invoke-ExecMailTest { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxMobileDevices.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxMobileDevices.ps1 index b633755f759b..5d752378f18a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxMobileDevices.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxMobileDevices.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecMailboxMobileDevices { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -20,7 +20,7 @@ Function Invoke-ExecMailboxMobileDevices { # Interact with query parameters or the body of the request. Try { - $MobileResults = Set-CIPPMobileDevice -UserId $request.query.Userid -Guid $request.query.guid -DeviceId $request.query.deviceid -Quarantine $request.query.Quarantine -tenantFilter $request.query.tenantfilter -APIName $APINAME -Delete $Request.query.Delete -ExecutingUser $request.headers.'x-ms-client-principal' + $MobileResults = Set-CIPPMobileDevice -UserId $request.query.Userid -Guid $request.query.guid -DeviceId $request.query.deviceid -Quarantine $request.query.Quarantine -tenantFilter $request.query.tenantfilter -APIName $APINAME -Delete $Request.query.Delete -Headers $Request.Headers $Results = [pscustomobject]@{'Results' = $MobileResults } } catch { $Results = [pscustomobject]@{'Results' = "Failed $($request.query.Userid): $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxRestore.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxRestore.ps1 index fe94e74424a1..b80c2fc0c750 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxRestore.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecMailboxRestore.ps1 @@ -7,8 +7,8 @@ function Invoke-ExecMailboxRestore { #> Param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { switch ($Request.Query.Action) { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecQuarantineManagement.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecQuarantineManagement.ps1 index 893302ffb327..4421360709dc 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecQuarantineManagement.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecQuarantineManagement.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecQuarantineManagement { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -30,9 +30,9 @@ Function Invoke-ExecQuarantineManagement { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Release-QuarantineMessage' -cmdParams $Params $Results = [pscustomobject]@{'Results' = "Successfully processed $($Request.Body.Identity)" } - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message "Successfully processed Quarantine ID $($Request.Body.Identity)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message "Successfully processed Quarantine ID $($Request.Body.Identity)" -Sev 'Info' } catch { - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantFilter -message "Quarantine Management failed: $($_.Exception.Message)" -Sev 'Error' -LogData $_ + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantFilter -message "Quarantine Management failed: $($_.Exception.Message)" -Sev 'Error' -LogData $_ $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecRemoveMailboxRule.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecRemoveMailboxRule.ps1 index a747ac432e33..530767520c08 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecRemoveMailboxRule.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecRemoveMailboxRule.ps1 @@ -16,14 +16,14 @@ Function Invoke-ExecRemoveMailboxRule { $RuleId = $Request.Query.ruleId $Username = $Request.Query.userPrincipalName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -tenant $TenantFilter -message 'Accessed this API' -Sev 'Debug' + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -tenant $TenantFilter -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' # Remove the rule - $Results = Remove-CIPPMailboxRule -userid $User -username $Username -TenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $User -RuleId $RuleId -RuleName $RuleName + $Results = Remove-CIPPMailboxRule -userid $User -username $Username -TenantFilter $TenantFilter -APIName $APINAME -Headers $User -RuleId $RuleId -RuleName $RuleName if ($Results -like '*Could not delete*') { $StatusCode = [HttpStatusCode]::Forbidden diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxLocale.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxLocale.ps1 index 02974ceb2c9a..f7d1c12ba762 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxLocale.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxLocale.ps1 @@ -10,17 +10,17 @@ Function Invoke-ExecSetMailboxLocale { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $Tenant = $Request.body.TenantFilter - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' # Interact with query parameters or the body of the request. - $Results = Set-CippMailboxLocale -username $Request.Body.user -locale $Request.body.locale -tenantFilter $Tenant -APIName $APINAME -ExecutingUser $User + $Results = Set-CippMailboxLocale -username $Request.Body.user -locale $Request.body.locale -tenantFilter $Tenant -APIName $APINAME -Headers $User # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxQuota.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxQuota.ps1 index f63df3442613..f5ced965516b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxQuota.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetMailboxQuota.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecSetMailboxQuota { [CmdletBinding()] param($Request, $TriggerMetadata) try { - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Username = $request.body.user $Tenantfilter = $request.body.tenantfilter $quota = $Request.body.quota @@ -19,20 +19,20 @@ Function Invoke-ExecSetMailboxQuota { if ($Request.Body.ProhibitSendQuota) { $quota = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $Username; ProhibitSendQuota = $quota } "Changed ProhibitSendQuota for $username - $($message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Changed ProhibitSendQuota for $username - $($message)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Changed ProhibitSendQuota for $username - $($message)" -Sev 'Info' -tenant $TenantFilter } if ($Request.Body.ProhibitSendReceiveQuota) { $quota = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $Username; ProhibitSendReceiveQuota = $quota } "Changed ProhibitSendReceiveQuota for $username - $($message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Changed ProhibitSendReceiveQuota for $username - $($message)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Changed ProhibitSendReceiveQuota for $username - $($message)" -Sev 'Info' -tenant $TenantFilter } if ($Request.Body.IssueWarningQuota) { $quota = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $Username; IssueWarningQuota = $quota } "Changed IssueWarningQuota for $username - $($message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Changed IssueWarningQuota for $username - $($message)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Changed IssueWarningQuota for $username - $($message)" -Sev 'Info' -tenant $TenantFilter } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not adjust mailbox quota for $($username)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Could not adjust mailbox quota for $($username)" -Sev 'Error' -tenant $TenantFilter "Could not adjust mailbox quota for $($username). Error: $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetOoO.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetOoO.ps1 index 612be4253734..1b60c5f7b8c0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetOoO.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecSetOoO.ps1 @@ -8,8 +8,8 @@ Function Invoke-ExecSetOoO { [CmdletBinding()] param($Request, $TriggerMetadata) try { - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'X-MS-CLIENT-PRINCIPAL' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Username = $request.body.userId $Tenantfilter = $request.body.tenantfilter if ($Request.body.input) { @@ -25,9 +25,9 @@ Function Invoke-ExecSetOoO { $Results = try { if ($Request.Body.AutoReplyState.value -ne 'Scheduled') { - Set-CIPPOutOfOffice -userid $Username -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'X-MS-CLIENT-PRINCIPAL' -InternalMessage $InternalMessage -ExternalMessage $ExternalMessage -State $Request.Body.AutoReplyState.value + Set-CIPPOutOfOffice -userid $Username -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers -InternalMessage $InternalMessage -ExternalMessage $ExternalMessage -State $Request.Body.AutoReplyState.value } else { - Set-CIPPOutOfOffice -userid $Username -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'X-MS-CLIENT-PRINCIPAL' -InternalMessage $InternalMessage -ExternalMessage $ExternalMessage -StartTime $StartTime -EndTime $EndTime -State $Request.Body.AutoReplyState.value + Set-CIPPOutOfOffice -userid $Username -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers -InternalMessage $InternalMessage -ExternalMessage $ExternalMessage -StartTime $StartTime -EndTime $EndTime -State $Request.Body.AutoReplyState.value } } catch { "Could not add out of office message for $($username). Error: $($_.Exception.Message)" diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecStartManagedFolderAssistant.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecStartManagedFolderAssistant.ps1 index 4781bb09eb7b..962d6a02d316 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecStartManagedFolderAssistant.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ExecStartManagedFolderAssistant.ps1 @@ -10,10 +10,10 @@ Function Invoke-ExecStartManagedFolderAssistant { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers $Tenant = $Request.query.TenantFilter - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -27,7 +27,7 @@ Function Invoke-ExecStartManagedFolderAssistant { $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $Tenant -message "Failed to create room: $($MailboxObject.DisplayName). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $Tenant -message "Failed to create room: $($MailboxObject.DisplayName). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $Results.Add("Failed to start Managed Folder Assistant for mailbox $($Request.query.id). Error: $($ErrorMessage.NormalizedError)") $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListAntiPhishingFilters.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListAntiPhishingFilters.ps1 index 45b9ee2b18ab..d6075e578313 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListAntiPhishingFilters.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListAntiPhishingFilters.ps1 @@ -8,8 +8,8 @@ function Invoke-ListAntiPhishingFilters { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilter.ps1 index 61c62cef6d78..fb80de05afbd 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilter.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListConnectionFilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilterTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilterTemplates.ps1 index b11f7c512fa8..08d32756da2f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilterTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListConnectionFilterTemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListConnectionFilterTemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CippTable -tablename 'templates' #List new policies diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListGlobalAddressList.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListGlobalAddressList.ps1 index 993f894fed02..15d5702ce0a1 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListGlobalAddressList.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListGlobalAddressList.ps1 @@ -10,9 +10,9 @@ Function Invoke-ListGlobalAddressList { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Query.tenantFilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantine.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantine.ps1 index 409b7652ccec..8447c76786ed 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantine.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantine.ps1 @@ -8,8 +8,8 @@ function Invoke-ListMailQuarantine { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantineMessage.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantineMessage.ps1 index 45127f00be8d..0a5031712a26 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantineMessage.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMailQuarantineMessage.ps1 @@ -8,8 +8,8 @@ function Invoke-ListMailQuarantineMessage { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $Request.Query.Tenantfilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMalwareFilters.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMalwareFilters.ps1 index 03836df0bc9e..597472165fda 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMalwareFilters.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMalwareFilters.ps1 @@ -8,8 +8,8 @@ function Invoke-ListMalwareFilters { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMessageTrace.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMessageTrace.ps1 index 9c7c3bc1482e..c2f51fd1d89e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMessageTrace.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListMessageTrace.ps1 @@ -66,11 +66,11 @@ Function Invoke-ListMessageTrace { Write-Information ($SearchParams | ConvertTo-Json) New-ExoRequest -TenantId $TenantFilter -Cmdlet 'Get-MessageTrace' -CmdParams $SearchParams | Select-Object MessageTraceId, Status, Subject, RecipientAddress, SenderAddress, @{ Name = 'Received'; Expression = { $_.Received.ToString('u') } }, FromIP, ToIP - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($TenantFilter) -message 'Executed message trace' -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $($TenantFilter) -message 'Executed message trace' -Sev 'Info' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Failed executing messagetrace. Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Failed executing messagetrace. Error: $($_.Exception.Message)" -Sev 'Error' $trace = @{Status = "Failed to retrieve message trace $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListOoO.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListOoO.ps1 index dc3a35d2201c..3fe5c9a4a15b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListOoO.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListOoO.ps1 @@ -10,10 +10,10 @@ Function Invoke-ListOoO { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $Tenantfilter = $request.query.tenantFilter try { - $Body = Get-CIPPOutOfOffice -userid $Request.query.userid -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $Body = Get-CIPPOutOfOffice -userid $Request.query.userid -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $Body = [pscustomobject]@{'Results' = "Failed. $ErrorMessage" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListRecipients.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListRecipients.ps1 index e995daa9231c..69d049c13ae9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListRecipients.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListRecipients.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListRecipients { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeAttachmentsFilters.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeAttachmentsFilters.ps1 index 511b1e3a2556..8b71d807876f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeAttachmentsFilters.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeAttachmentsFilters.ps1 @@ -8,8 +8,8 @@ function Invoke-ListSafeAttachmentsFilters { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeLinksFilters.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeLinksFilters.ps1 index f5fa0d5932a9..bcf5e939e498 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeLinksFilters.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSafeLinksFilters.ps1 @@ -8,8 +8,8 @@ function Invoke-ListSafeLinksFilters { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamFilterTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamFilterTemplates.ps1 index e38c63bbedbf..a74c9491e4af 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamFilterTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamFilterTemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListSpamFilterTemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CippTable -tablename 'templates' #List new policies diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamfilter.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamfilter.ps1 index cb58d1a378f2..efa8a228914c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamfilter.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListSpamfilter.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListSpamfilter { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRules.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRules.ps1 index 283afe12e1ee..702247ac6b3e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRules.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRules.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListTransportRules { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRulesTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRulesTemplates.ps1 index 31fe9e6b04a9..93846a810e02 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRulesTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Email-Exchange/Invoke-ListTransportRulesTemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListTransportRulesTemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CippTable -tablename 'templates' $Templates = Get-ChildItem 'Config\*.TransportRuleTemplate.json' | ForEach-Object { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddChocoApp.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddChocoApp.ps1 index a2320397fa3f..34cfeb198291 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddChocoApp.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddChocoApp.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddChocoApp { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host 'PowerShell HTTP trigger function processed a request.' $ChocoApp = $request.body @@ -47,10 +47,10 @@ Function Invoke-AddChocoApp { PartitionKey = 'apps' } "Successfully added Choco App for $($Tenant) to queue." - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Successfully added Choco App $($intunebody.Displayname) to queue" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant -message "Successfully added Choco App $($intunebody.Displayname) to queue" -Sev 'Info' } catch { "Failed adding Choco App for $($Tenant) to queue" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Failed to add Chocolatey Application $($intunebody.Displayname) to queue" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant -message "Failed to add Chocolatey Application $($intunebody.Displayname) to queue" -Sev 'Error' } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddMSPApp.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddMSPApp.ps1 index d0e3c340a7b5..b5d055d24c1b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddMSPApp.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddMSPApp.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddMSPApp { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host 'PowerShell HTTP trigger function processed a request.' $RMMApp = $request.body @@ -81,9 +81,9 @@ Function Invoke-AddMSPApp { status = 'Not Deployed yet' } "Successfully added MSP App for $($Tenant.defaultDomainName) to queue. " - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant.defaultDomainName -message "MSP Application $($intunebody.Displayname) added to queue" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant.defaultDomainName -message "MSP Application $($intunebody.Displayname) added to queue" -Sev 'Info' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant.defaultDomainName -message "Failed to add MSP Application $($intunebody.Displayname) to queue" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant.defaultDomainName -message "Failed to add MSP Application $($intunebody.Displayname) to queue" -Sev 'Error' "Failed to add MSP app for $($Tenant.defaultDomainName) to queue" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddOfficeApp.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddOfficeApp.ps1 index 907410fbe500..f2162cf98ff7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddOfficeApp.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddOfficeApp.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddOfficeApp { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Input bindings are passed in via param block. @@ -71,16 +71,16 @@ Function Invoke-AddOfficeApp { "Office deployment already exists for $($Tenant)" Continue } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenant) -message "Added Office profile to $($tenant)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $($tenant) -message "Added Office profile to $($tenant)" -Sev 'Info' if ($AssignTo) { $AssignO365 = if ($AssignTo -ne 'AllDevicesAndUsers') { '{"mobileAppAssignments":[{"@odata.type":"#microsoft.graph.mobileAppAssignment","target":{"@odata.type":"#microsoft.graph.' + $($AssignTo) + 'AssignmentTarget"},"intent":"Required"}]}' } else { '{"mobileAppAssignments":[{"@odata.type":"#microsoft.graph.mobileAppAssignment","target":{"@odata.type":"#microsoft.graph.allDevicesAssignmentTarget"},"intent":"Required"},{"@odata.type":"#microsoft.graph.mobileAppAssignment","target":{"@odata.type":"#microsoft.graph.allLicensedUsersAssignmentTarget"},"intent":"Required"}]}' } Write-Host ($AssignO365) New-graphPostRequest -Uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($OfficeAppID.id)/assign" -tenantid $tenant -Body $AssignO365 -type POST - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenant) -message "Assigned Office to $AssignTo" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $($tenant) -message "Assigned Office to $AssignTo" -Sev 'Info' } "Successfully added Office App for $($Tenant)" } catch { "Failed to add Office App for $($Tenant): $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenant) -message "Failed to add Office App. Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $($tenant) -message "Failed to add Office App. Error: $($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddStoreApp.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddStoreApp.ps1 index ef098ff7b0d8..960560e29b5e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddStoreApp.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-AddStoreApp.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddStoreApp { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host 'PowerShell HTTP trigger function processed a request.' $WinGetApp = $request.body @@ -48,9 +48,9 @@ Function Invoke-AddStoreApp { status = 'Not Deployed yet' } "Successfully added Store App for $($Tenant) to queue." - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Successfully added Store App $($intunebody.Displayname) to queue" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant -message "Successfully added Store App $($intunebody.Displayname) to queue" -Sev 'Info' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Failed to add Store App $($intunebody.Displayname) to queue" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant -message "Failed to add Store App $($intunebody.Displayname) to queue" -Sev 'Error' "Failed added Store App for $($Tenant) to queue" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAppUpload.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAppUpload.ps1 index d57088b5a4e2..49dd04da6a61 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAppUpload.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAppUpload.ps1 @@ -16,7 +16,7 @@ function Invoke-ExecAppUpload { $ProcessorFunction = [PSCustomObject]@{ PartitionKey = 'Function' RowKey = 'Start-ApplicationOrchestrator' - + FunctionName = 'Start-ApplicationOrchestrator' } $ProcessorQueue = Get-CIPPTable -TableName 'ProcessorQueue' Add-AzDataTableEntity @ProcessorQueue -Entity $ProcessorFunction -Force diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAssignApp.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAssignApp.ps1 index 74a83ce92927..999161fe866b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAssignApp.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ExecAssignApp.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAssignApp { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -45,10 +45,10 @@ Function Invoke-ExecAssignApp { $body = [pscustomobject]@{'Results' = "$($TenantFilter): Assigned app to $assignTo" } try { $GraphRequest = New-Graphpostrequest -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$appFilter/assign" -tenantid $TenantFilter -body $Assignbody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Assigned $($appFilter) to $assignTo" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Assigned $($appFilter) to $assignTo" -Sev 'Info' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Failed to assign app $($appFilter): $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Failed to assign app $($appFilter): $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to assign. $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApplicationQueue.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApplicationQueue.ps1 index 0aa432beff14..9fc4e3200ea5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApplicationQueue.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApplicationQueue.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListApplicationQueue { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApps.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApps.ps1 index d5c13112058f..92c5e188f1aa 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApps.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListApps.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListApps { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListAppsRepository.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListAppsRepository.ps1 index 4f9d60aa52df..685d06eacf37 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListAppsRepository.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Applications/Invoke-ListAppsRepository.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListAppsRepository { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Search = $Request.Body.Search $Repository = $Request.Body.Repository diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAPDevice.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAPDevice.ps1 index 1e1c57118f14..b8fd6eb7aaf0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAPDevice.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAPDevice.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddAPDevice { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -51,7 +51,7 @@ Function Invoke-AddAPDevice { $NewStatus = New-GraphgetRequest -uri "https://api.partnercenter.microsoft.com/v1/$($GraphRequest.Location)" -scope 'https://api.partnercenter.microsoft.com/user_impersonation' } until ($Newstatus.status -eq 'finished' -or $amount -eq 4) if ($NewStatus.status -ne 'finished') { throw 'Could not retrieve status of import - This job might still be running. Check the autopilot device list in 10 minutes for the latest status.' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($Request.body.TenantFilter.value) -message "Created Autopilot devices group. Group ID is $GroupName" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $($Request.body.TenantFilter.value) -message "Created Autopilot devices group. Group ID is $GroupName" -Sev 'Info' [PSCustomObject]@{ Status = 'Import Job Completed' @@ -62,7 +62,7 @@ Function Invoke-AddAPDevice { Status = "$($Request.body.TenantFilter.value): Failed to create autopilot devices. $($_.Exception.Message)" Devices = @() } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($Request.body.TenantFilter.value) -message "Failed to create autopilot devices. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $($Request.body.TenantFilter.value) -message "Failed to create autopilot devices. $($_.Exception.Message)" -Sev 'Error' } $body = [pscustomobject]@{'Results' = $Result } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAutopilotConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAutopilotConfig.ps1 index 1c737749e18a..3834d45e071e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAutopilotConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddAutopilotConfig.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddAutopilotConfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddEnrollment.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddEnrollment.ps1 index 22179704004a..1656c5a69c59 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddEnrollment.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-AddEnrollment.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddEnrollment { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ExecAssignAPDevice.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ExecAssignAPDevice.ps1 index f4d0e10d2526..2318ec44da7c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ExecAssignAPDevice.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ExecAssignAPDevice.ps1 @@ -9,9 +9,9 @@ Function Invoke-ExecAssignAPDevice { #> [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.body.tenantFilter @@ -24,12 +24,12 @@ Function Invoke-ExecAssignAPDevice { addressableUserName = $UserObject.addressableUserName } | ConvertTo-Json New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$($DeviceObject)/UpdateDeviceProperties" -tenantid $TenantFilter -body $body -method POST | Out-Null - Write-LogMessage -user $User -API $APINAME -message "Successfully assigned device: $DeviceObject with Serial: $SerialNumber to $($UserObject.userPrincipalName) for $($TenantFilter)" -Sev Info + Write-LogMessage -Headers $User -API $APINAME -message "Successfully assigned device: $DeviceObject with Serial: $SerialNumber to $($UserObject.userPrincipalName) for $($TenantFilter)" -Sev Info $Results = "Successfully assigned device: $DeviceObject with Serial: $SerialNumber to $($UserObject.userPrincipalName) for $($TenantFilter)" $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Could not assign $($UserObject.userPrincipalName) to $($DeviceObject) for $($TenantFilter) Error: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Could not assign $($UserObject.userPrincipalName) to $($DeviceObject) for $($TenantFilter) Error: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $Results = "Could not assign $($UserObject.userPrincipalName) to $($DeviceObject) for $($TenantFilter) Error: $($ErrorMessage.NormalizedError)" $StatusCode = [HttpStatusCode]::BadRequest } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ListAPDevices.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ListAPDevices.ps1 index ab840b320596..fed6abfc5b13 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ListAPDevices.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Autopilot/Invoke-ListAPDevices.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListAPDevices { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddDefenderDeployment.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddDefenderDeployment.ps1 index f89edf45c78d..95de673985c4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddDefenderDeployment.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddDefenderDeployment.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddDefenderDeployment { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenants = ($Request.body.selectedTenants).value if ('AllTenants' -in $Tenants) { $Tenants = (Get-Tenants).defaultDomainName } @@ -99,7 +99,7 @@ Function Invoke-AddDefenderDeployment { if ($PolicySettings.AssignTo -ne 'None') { $AssignBody = if ($PolicySettings.AssignTo -ne 'AllDevicesAndUsers') { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.' + $($PolicySettings.AssignTo) + 'AssignmentTarget"}}]}' } else { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.allDevicesAssignmentTarget"}},{"id":"","target":{"@odata.type":"#microsoft.graph.allLicensedUsersAssignmentTarget"}}]}' } $assign = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($PolicyRequest.id)')/assign" -tenantid $tenant -type POST -body $AssignBody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $($PolicySettings.AssignTo)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $($PolicySettings.AssignTo)" -Sev 'Info' } "$($Tenant): Successfully set Default AV Policy settings" } @@ -152,7 +152,7 @@ Function Invoke-AddDefenderDeployment { if ($ASR.AssignTo -ne 'none') { $AssignBody = if ($ASR.AssignTo -ne 'AllDevicesAndUsers') { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.' + $($asr.AssignTo) + 'AssignmentTarget"}}]}' } else { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.allDevicesAssignmentTarget"}},{"id":"","target":{"@odata.type":"#microsoft.graph.allLicensedUsersAssignmentTarget"}}]}' } $assign = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($ASRRequest.id)')/assign" -tenantid $tenant -type POST -body $AssignBody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $($ASR.AssignTo)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $($ASR.AssignTo)" -Sev 'Info' } "$($Tenant): Successfully added ASR Settings" } @@ -227,14 +227,14 @@ Function Invoke-AddDefenderDeployment { if ($ASR.AssignTo -ne 'none') { $AssignBody = if ($ASR.AssignTo -ne 'AllDevicesAndUsers') { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.' + $($asr.AssignTo) + 'AssignmentTarget"}}]}' } else { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.allDevicesAssignmentTarget"}},{"id":"","target":{"@odata.type":"#microsoft.graph.allLicensedUsersAssignmentTarget"}}]}' } $assign = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($EDRRequest.id)')/assign" -tenantid $tenant -type POST -body $AssignBody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Assigned EDR policy $($Displayname) to $($ASR.AssignTo)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Assigned EDR policy $($Displayname) to $($ASR.AssignTo)" -Sev 'Info' } "$($Tenant): Successfully added EDR Settings" } } } catch { "Failed to add policy for $($Tenant): $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed adding policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Failed adding policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddIntuneTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddIntuneTemplate.ps1 index 884688b42915..24c00cf0adff 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddIntuneTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddIntuneTemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddIntuneTemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $GUID = (New-Guid).GUID try { @@ -34,14 +34,15 @@ Function Invoke-AddIntuneTemplate { RowKey = "$GUID" PartitionKey = 'IntuneTemplate' } - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -message "Created intune policy template named $($Request.Body.displayName) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created intune policy template named $($Request.Body.displayName) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } else { $TenantFilter = $Request.Body.tenantFilter ?? $Request.Query.tenantFilter $URLName = $Request.Body.URLName ?? $Request.Query.URLName $ID = $Request.Body.ID ?? $Request.Query.ID - $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName $URLName -ID $ID + $ODataType = $Request.Body.ODataType ?? $Request.Query.ODataType + $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName $URLName -ID $ID -ODataType $ODataType Write-Host "Template: $Template" $object = [PSCustomObject]@{ Displayname = $Template.DisplayName @@ -57,12 +58,12 @@ Function Invoke-AddIntuneTemplate { RowKey = "$GUID" PartitionKey = 'IntuneTemplate' } - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -message "Created intune policy template $($Request.Body.displayName) with GUID $GUID using an original policy from a tenant" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created intune policy template $($Request.Body.displayName) with GUID $GUID using an original policy from a tenant" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } } catch { - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -message "Intune Template Deployment failed: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Intune Template Deployment failed: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Intune Template Deployment failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddPolicy.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddPolicy.ps1 index 0408fb793275..5cf66fec102d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddPolicy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-AddPolicy.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddPolicy { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenants = ($Request.Body.tenantFilter.value) if ('AllTenants' -in $Tenants) { $Tenants = (Get-Tenants).defaultDomainName } @@ -27,11 +27,11 @@ Function Invoke-AddPolicy { } try { Write-Host 'Calling Adding policy' - Set-CIPPIntunePolicy -TemplateType $Request.body.TemplateType -Description $description -DisplayName $displayname -RawJSON $RawJSON -AssignTo $AssignTo -tenantFilter $Tenant - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Added policy $($Displayname)" -Sev 'Info' + Set-CIPPIntunePolicy -TemplateType $Request.body.TemplateType -Description $description -DisplayName $displayname -RawJSON $RawJSON -AssignTo $AssignTo -tenantFilter $Tenant -Headers $Request.Headers + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Added policy $($Displayname)" -Sev 'Info' } catch { "$($_.Exception.Message)" - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed adding policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Failed adding policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditIntuneScript.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditIntuneScript.ps1 new file mode 100644 index 000000000000..902e39cb3102 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditIntuneScript.ps1 @@ -0,0 +1,48 @@ +using namespace System.Net + +function Invoke-EditIntuneScript { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + Endpoint.MEM.ReadWrite + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev Debug + + $graphUrl = "https://graph.microsoft.com/beta" + switch($Request.Method) { + "GET" { + $parms = @{ + uri = "$graphUrl/deviceManagement/deviceManagementScripts/$($Request.Query.ScriptId)" + tenantid = $Request.Query.TenantFilter + } + + $intuneScript = New-GraphGetRequest @parms + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $intuneScript + }) + } + "PATCH" { + $parms = @{ + uri = "$graphUrl/deviceManagement/deviceManagementScripts/$($Request.Body.ScriptId)" + tenantid = $Request.Body.TenantFilter + body = $Request.Body.IntuneScript + } + $patchResult = New-GraphPOSTRequest @parms -type "PATCH" + $body = [pscustomobject]@{'Results' = $patchResult } + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $body + }) + } + "POST" { + Write-Output "Adding script" + } + } +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditPolicy.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditPolicy.ps1 index 066e83cf11df..aa987198a3ee 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditPolicy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-EditPolicy.ps1 @@ -10,8 +10,8 @@ Function Invoke-EditPolicy { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenant = $request.body.tenantid $ID = $request.body.groupid @@ -22,17 +22,17 @@ Function Invoke-EditPolicy { $results = try { $CreateBody = '{"description":"' + $description + '","displayName":"' + $displayname + '","roleScopeTagIds":["0"]}' $Request = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations('$ID')" -tenantid $tenant -type PATCH -body $CreateBody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Edited policy $($Displayname)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Edited policy $($Displayname)" -Sev 'Info' if ($AssignTo) { $AssignBody = if ($AssignTo -ne 'AllDevicesAndUsers') { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.' + $($AssignTo) + 'AssignmentTarget"}}]}' } else { '{"assignments":[{"id":"","target":{"@odata.type":"#microsoft.graph.allDevicesAssignmentTarget"}},{"id":"","target":{"@odata.type":"#microsoft.graph.allLicensedUsersAssignmentTarget"}}]}' } $assign = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations('$($ID)')/assign" -tenantid $tenant -type POST -body $AssignBody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $AssignTo" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $AssignTo" -Sev 'Info' } "Successfully edited policy for $($Tenant)" } catch { "Failed to add policy for $($Tenant): $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed editing policy $($Displayname). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Failed editing policy $($Displayname). Error:$($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecAssignPolicy.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecAssignPolicy.ps1 index 4af8ca501a15..44bd7e8a7438 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecAssignPolicy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecAssignPolicy.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAssignPolicy { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenant = $request.body.tenantfilter $ID = $request.body.id @@ -21,12 +21,12 @@ Function Invoke-ExecAssignPolicy { $results = try { if ($AssignTo) { $assign = Set-CIPPAssignedPolicy -PolicyId $ID -TenantFilter $tenant -GroupName $AssignTo -Type $Request.body.Type - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $AssignTo" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Assigned policy $($Displayname) to $AssignTo" -Sev 'Info' } "Successfully edited policy for $($Tenant)" } catch { "Failed to add policy for $($Tenant): $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed editing policy $($Displayname). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Failed editing policy $($Displayname). Error:$($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecDeviceAction.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecDeviceAction.ps1 index 7d5dfc2b29bc..5057a2d7470f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecDeviceAction.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecDeviceAction.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecDeviceAction { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with Body parameters or the body of the request. @@ -29,7 +29,7 @@ Function Invoke-ExecDeviceAction { ActionBody = $ActionBody DeviceFilter = $Request.Body.GUID TenantFilter = $Request.Body.TenantFilter - ExecutingUser = $request.headers.'x-ms-client-principal' + Headers = $Request.Headers APINAME = $APINAME } $ActionResult = New-CIPPDeviceAction @cmdparams diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetLocalAdminPassword.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetLocalAdminPassword.ps1 index 46af5fc50f77..4a361359e20f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetLocalAdminPassword.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetLocalAdminPassword.ps1 @@ -10,10 +10,10 @@ Function Invoke-ExecGetLocalAdminPassword { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint try { - $GraphRequest = Get-CIPPLapsPassword -device $($request.body.guid) -tenantFilter $Request.body.TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $GraphRequest = Get-CIPPLapsPassword -device $($request.body.guid) -tenantFilter $Request.body.TenantFilter -APIName $APINAME -Headers $Request.Headers $Body = [pscustomobject]@{'Results' = $GraphRequest } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetRecoveryKey.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetRecoveryKey.ps1 index 46df4d780496..9d7eed11b7fb 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetRecoveryKey.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ExecGetRecoveryKey.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecGetRecoveryKey { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -20,7 +20,7 @@ Function Invoke-ExecGetRecoveryKey { # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter try { - $GraphRequest = Get-CIPPBitlockerKey -device $Request.query.GUID -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $GraphRequest = Get-CIPPBitlockerKey -device $Request.query.GUID -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers $Body = [pscustomobject]@{'Results' = $GraphRequest } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ListIntuneScript.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ListIntuneScript.ps1 new file mode 100644 index 000000000000..e53611befd00 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-ListIntuneScript.ps1 @@ -0,0 +1,72 @@ +using namespace System.Net + +function Invoke-ListIntuneScript { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + Endpoint.MEM.Read + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev Debug + + Write-Host 'PowerShell HTTP trigger function processed a request.' + + $TenantFilter = $Request.Query.TenantFilter + $Results = [System.Collections.Generic.List[System.Object]]::new() + + $BulkRequests = [PSCustomObject]@( + @{ + id = 'Windows' + method = 'GET' + url = '/deviceManagement/deviceManagementScripts' + } + @{ + id = 'MacOS' + method = 'GET' + url = '/deviceManagement/deviceShellScripts' + } + @{ + id = 'Remediation' + method = 'GET' + url = '/deviceManagement/deviceHealthScripts' + } + @{ + id = 'Linux' + method = 'GET' + url = '/deviceManagement/configurationPolicies' + } + ) + + try { + $BulkResults = New-GraphBulkRequest -Requests $BulkRequests -tenantid $TenantFilter + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-Host "Failed to retrieve scripts. Error: $($ErrorMessage.NormalizedError)" + } + + foreach ($scriptId in @('Windows', 'MacOS', 'Remediation', 'Linux')) { + $scripts = ($BulkResults | Where-Object { $_.id -eq $scriptId }).body.value + + if ($scriptId -eq 'Linux') { + $scripts = $scripts | Where-Object { $_.platforms -eq 'linux' -and $_.templateReference.templateFamily -eq 'deviceConfigurationScripts' } + $scripts | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name displayName -Value $_.name -Force } + } + + $scripts | Add-Member -MemberType NoteProperty -Name scriptType -Value $scriptId + Write-Host "$scriptId scripts count: $($scripts.Count)" + $Results.AddRange(@($scripts)) + } + + + # Associate values to output bindings by calling 'Push-OutputBinding'. + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = @($Results) + }) + +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-RemoveIntuneScript.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-RemoveIntuneScript.ps1 new file mode 100644 index 000000000000..4770fbe1638a --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/MEM/Invoke-RemoveIntuneScript.ps1 @@ -0,0 +1,58 @@ +using namespace System.Net + +function Invoke-RemoveIntuneScript { + <# + .FUNCTIONALITY + Entrypoint + .ROLE + Endpoint.MEM.ReadWrite + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev Debug + + Write-Host 'PowerShell HTTP trigger function processed a request.' + + $TenantFilter = $Request.body.TenantFilter + $ID = $Request.body.ID + $ScriptType = $Request.body.ScriptType + $DisplayName = $Request.body.DisplayName + + try { + + $URI = switch ($ScriptType) { + 'Windows' { + "https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts/$($ID)" + } + 'MacOS' { + "https://graph.microsoft.com/beta/deviceManagement/deviceShellScripts/$($ID)" + } + 'Remediation' { + "https://graph.microsoft.com/beta/deviceManagement/deviceHealthScripts/$($ID)" + } + 'Linux' { + "https://graph.microsoft.com/beta/deviceManagement/ConfigurationPolicies('$($ID)')" + } + Default { $null } + } + + $null = New-GraphPOSTRequest -uri $URI -type DELETE -tenantid $TenantFilter + $Result = "Deleted $($ScriptType) script $($DisplayName) with ID: $($ID)" + $StatusCode = [HttpStatusCode]::OK + } catch { + $ErrorMessage = Get-CippException -Exception $_ + $Result = "Failed to delete $($ScriptType) script $($DisplayName). Error: $($ErrorMessage.NormalizedError)" + $StatusCode = [HttpStatusCode]::Forbidden + } + + $body = [pscustomobject]@{'Results' = "$Result" } + # Associate values to output bindings by calling 'Push-OutputBinding'. + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = $StatusCode + Body = $body + }) + +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Reports/Invoke-ListDevices.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Reports/Invoke-ListDevices.ps1 index d4ed67595239..79b0cd5cb55b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Reports/Invoke-ListDevices.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Endpoint/Reports/Invoke-ListDevices.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListDevices { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Devices/Invoke-ExecDeviceDelete.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Devices/Invoke-ExecDeviceDelete.ps1 index 7fd95cdeb8f4..1916328d51da 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Devices/Invoke-ExecDeviceDelete.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Devices/Invoke-ExecDeviceDelete.ps1 @@ -10,9 +10,9 @@ Function Invoke-ExecDeviceDelete { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with body parameters or the body of the request. $TenantFilter = $Request.body.tenantFilter ?? $Request.Query.tenantFilter @@ -20,7 +20,7 @@ Function Invoke-ExecDeviceDelete { $DeviceID = $Request.body.ID ?? $Request.Query.ID try { - $Results = Set-CIPPDeviceState -Action $Action -DeviceID $DeviceID -TenantFilter $TenantFilter -ExecutingUser $ExecutingUser -APIName $APINAME + $Results = Set-CIPPDeviceState -Action $Action -DeviceID $DeviceID -TenantFilter $TenantFilter -Headers $Request.Headers -APIName $APINAME $StatusCode = [HttpStatusCode]::OK } catch { $Results = $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroup.ps1 index b4e419b986cd..c43275d2167e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroup.ps1 @@ -10,81 +10,77 @@ Function Invoke-AddGroup { [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 = $Request.Params.CIPPEndpoint + $SelectedTenants = if ('AllTenants' -in $SelectedTenants) { (Get-Tenants).defaultDomainName } else { $Request.body.tenantFilter.value ? $Request.body.tenantFilter.value : $Request.body.tenantFilter } + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Accessed this API' -Sev Debug - $groupobj = $Request.body - $SelectedTenants = $request.body.tenantfilter.value ? $request.body.tenantfilter.value : $request.body.tenantfilter - if ('AllTenants' -in $SelectedTenants) { $SelectedTenants = (Get-Tenants).defaultDomainName } - # Write to the Azure Functions log stream. - Write-Host 'PowerShell HTTP trigger function processed a request.' - $results = foreach ($tenant in $SelectedTenants) { + $GroupObject = $Request.body + + $Results = foreach ($tenant in $SelectedTenants) { try { - $email = if ($groupobj.primDomain.value) { "$($groupobj.username)@$($groupobj.primDomain.value)" } else { "$($groupobj.username)@$($tenant)" } - if ($groupobj.groupType -in 'Generic', 'azurerole', 'dynamic', 'm365') { + $Email = if ($GroupObject.primDomain.value) { "$($GroupObject.username)@$($GroupObject.primDomain.value)" } else { "$($GroupObject.username)@$($tenant)" } + if ($GroupObject.groupType -in 'Generic', 'azurerole', 'dynamic', 'm365') { - $BodyToship = [pscustomobject] @{ - 'displayName' = $groupobj.Displayname - 'description' = $groupobj.Description - 'mailNickname' = $groupobj.username + $BodyParams = [pscustomobject] @{ + 'displayName' = $GroupObject.displayName + 'description' = $GroupObject.description + 'mailNickname' = $GroupObject.username mailEnabled = [bool]$false securityEnabled = [bool]$true - isAssignableToRole = [bool]($groupobj | Where-Object -Property groupType -EQ 'AzureRole') + isAssignableToRole = [bool]($GroupObject | Where-Object -Property groupType -EQ 'AzureRole') } - if ($groupobj.membershipRules) { - $BodyToship | Add-Member -NotePropertyName 'membershipRule' -NotePropertyValue ($groupobj.membershipRules) - $BodyToship | Add-Member -NotePropertyName 'groupTypes' -NotePropertyValue @('DynamicMembership') - $BodyToship | Add-Member -NotePropertyName 'membershipRuleProcessingState' -NotePropertyValue 'On' + if ($GroupObject.membershipRules) { + $BodyParams | Add-Member -NotePropertyName 'membershipRule' -NotePropertyValue ($GroupObject.membershipRules) + $BodyParams | Add-Member -NotePropertyName 'groupTypes' -NotePropertyValue @('DynamicMembership') + $BodyParams | Add-Member -NotePropertyName 'membershipRuleProcessingState' -NotePropertyValue 'On' } - if ($groupobj.groupType -eq 'm365') { - $BodyToship | Add-Member -NotePropertyName 'groupTypes' -NotePropertyValue @('Unified') + if ($GroupObject.groupType -eq 'm365') { + $BodyParams | Add-Member -NotePropertyName 'groupTypes' -NotePropertyValue @('Unified') } - if ($groupobj.owners -AND $groupobj.groupType -in 'generic', 'azurerole', 'security') { - $BodyToship | Add-Member -NotePropertyName 'owners@odata.bind' -NotePropertyValue (($groupobj.AddOwner) | ForEach-Object { "https://graph.microsoft.com/v1.0/users/$($_.value)" }) - $bodytoship.'owners@odata.bind' = @($bodytoship.'owners@odata.bind') + if ($GroupObject.owners -AND $GroupObject.groupType -in 'generic', 'azurerole', 'security') { + $BodyParams | Add-Member -NotePropertyName 'owners@odata.bind' -NotePropertyValue (($GroupObject.AddOwner) | ForEach-Object { "https://graph.microsoft.com/v1.0/users/$($_.value)" }) + $BodyParams.'owners@odata.bind' = @($BodyParams.'owners@odata.bind') } - if ($groupobj.members -AND $groupobj.groupType -in 'generic', 'azurerole', 'security') { - $BodyToship | Add-Member -NotePropertyName 'members@odata.bind' -NotePropertyValue (($groupobj.AddMember) | ForEach-Object { "https://graph.microsoft.com/v1.0/users/$($_.value)" }) - $BodyToship.'members@odata.bind' = @($BodyToship.'members@odata.bind') + if ($GroupObject.members -AND $GroupObject.groupType -in 'generic', 'azurerole', 'security') { + $BodyParams | Add-Member -NotePropertyName 'members@odata.bind' -NotePropertyValue (($GroupObject.AddMember) | ForEach-Object { "https://graph.microsoft.com/v1.0/users/$($_.value)" }) + $BodyParams.'members@odata.bind' = @($BodyParams.'members@odata.bind') } - $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/groups' -tenantid $tenant -type POST -body (ConvertTo-Json -InputObject $BodyToship -Depth 10) -verbose + $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/groups' -tenantid $tenant -type POST -body (ConvertTo-Json -InputObject $BodyParams -Depth 10) -Verbose } else { - if ($groupobj.groupType -eq 'dynamicdistribution') { - $Params = @{ - Name = $groupobj.Displayname - RecipientFilter = $groupobj.membershipRules - PrimarySmtpAddress = $email + if ($GroupObject.groupType -eq 'dynamicDistribution') { + $ExoParams = @{ + Name = $GroupObject.displayName + RecipientFilter = $GroupObject.membershipRules + PrimarySmtpAddress = $Email } - $GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'New-DynamicDistributionGroup' -cmdParams $params + $GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'New-DynamicDistributionGroup' -cmdParams $ExoParams } else { - $Params = @{ - Name = $groupobj.Displayname - Alias = $groupobj.username - Description = $groupobj.Description - PrimarySmtpAddress = $email - Type = $groupobj.groupType - RequireSenderAuthenticationEnabled = [bool]!$groupobj.AllowExternal + $ExoParams = @{ + Name = $GroupObject.displayName + Alias = $GroupObject.username + Description = $GroupObject.description + PrimarySmtpAddress = $Email + Type = $GroupObject.groupType + RequireSenderAuthenticationEnabled = [bool]!$GroupObject.allowExternal } - $GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'New-DistributionGroup' -cmdParams $params + $GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'New-DistributionGroup' -cmdParams $ExoParams } - #$GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'New-DistributionGroup' -cmdParams $params - # At some point add logic to use AddOwner/AddMember for New-DistributionGroup, but idk how we're going to brr that - rvdwegen } - "Successfully created group $($groupobj.displayname) for $($tenant)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Created group $($groupobj.displayname) with id $($GraphRequest.id)" -Sev 'Info' + "Successfully created group $($GroupObject.displayName) for $($tenant)" + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $tenant -message "Created group $($GroupObject.displayName) with id $($GraphRequest.id)" -Sev Info } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Group creation API failed. $($_.Exception.Message)" -Sev 'Error' - "Failed to create group. $($groupobj.displayname) for $($tenant) $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $tenant -message "Group creation API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + "Failed to create group. $($GroupObject.displayName) for $($tenant) $($ErrorMessage.NormalizedError)" } } - $body = [pscustomobject]@{'Results' = @($results) } + $ResponseBody = [pscustomobject]@{'Results' = @($Results) } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK - Body = $Body + Body = $ResponseBody }) - } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroupTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroupTemplate.ps1 index ba41d2e6ed0d..5b9344e720a7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroupTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-AddGroupTemplate.ps1 @@ -9,8 +9,8 @@ Function Invoke-AddGroupTemplate { #> [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $GUID = (New-Guid).GUID try { @@ -32,11 +32,11 @@ Function Invoke-AddGroupTemplate { RowKey = "$GUID" PartitionKey = 'GroupTemplate' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created Group template named $($Request.body.displayname) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created Group template named $($Request.body.displayname) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Group Template Creation failed: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Group Template Creation failed: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Group Template Creation failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-EditGroup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-EditGroup.ps1 index 2a56ba875dca..a2ac5ca43077 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-EditGroup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-EditGroup.ps1 @@ -10,8 +10,8 @@ Function Invoke-EditGroup { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Results = [System.Collections.ArrayList]@() $userobj = $Request.body @@ -38,10 +38,10 @@ Function Invoke-EditGroup { } else { New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)" -tenantid $TenantId -type patch -body $addmemberbody -Verbose } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Added $member to $($GroupName) group" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Added $member to $($GroupName) group" -Sev 'Info' $null = $results.add("Success. $member has been added to $($GroupName)") } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Failed to add member $member to $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Failed to add member $member to $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' $null = $results.add("Failed to add member $member to $($GroupName): $($_.Exception.Message)") } } @@ -56,10 +56,10 @@ Function Invoke-EditGroup { if ($GroupType -eq 'Distribution list' -or $GroupType -eq 'Mail-Enabled Security') { $Params = @{ Identity = $userobj.groupid; Member = $member; BypassSecurityGroupManagerCheck = $true } New-ExoRequest -tenantid $TenantId -cmdlet 'Add-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true - Write-LogMessage -API $APINAME -tenant $TenantId -user $request.headers.'x-ms-client-principal' -message "Added $member to $($GroupName) group" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $TenantId -headers $Request.Headers -message "Added $member to $($GroupName) group" -Sev 'Info' $null = $results.add("Success. $member has been added to $($GroupName)") } else { - Write-LogMessage -API $APINAME -tenant $TenantId -user $request.headers.'x-ms-client-principal' -message 'You cannot add a contact to a security group' -Sev 'Error' + Write-LogMessage -API $APINAME -tenant $TenantId -headers $Request.Headers -message 'You cannot add a contact to a security group' -Sev 'Error' $null = $results.add('You cannot add a contact to a security group') } } catch { @@ -82,12 +82,12 @@ Function Invoke-EditGroup { $MemberInfo = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($_)" -tenantid $TenantId) New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/members/$($MemberInfo.id)/`$ref" -tenantid $TenantId -type DELETE } - Write-LogMessage -API $APINAME -tenant $TenantId -user $request.headers.'x-ms-client-principal' -message "Removed $member from $($GroupName) group" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $TenantId -headers $Request.Headers -message "Removed $member from $($GroupName) group" -Sev 'Info' $null = $results.add("Success. Member $member has been removed from $($GroupName)") } } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Failed to remove $RemoveContact from $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Failed to remove $RemoveContact from $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' $null = $results.add("Could not remove $RemoveContact from $($GroupName). $($_.Exception.Message)") } @@ -105,12 +105,12 @@ Function Invoke-EditGroup { $MemberInfo = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($_)" -tenantid $TenantId) New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/members/$($MemberInfo.id)/`$ref" -tenantid $TenantId -type DELETE } - Write-LogMessage -API $APINAME -tenant $TenantId -user $request.headers.'x-ms-client-principal' -message "Removed $member from $($GroupName) group" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $TenantId -headers $Request.Headers -message "Removed $member from $($GroupName) group" -Sev 'Info' $null = $results.add("Success. Member $member has been removed from $($GroupName)") } } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Failed to remove $RemoveMembers from $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Failed to remove $RemoveMembers from $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' $null = $results.add("Could not remove $RemoveMembers from $($GroupName). $($_.Exception.Message)") } @@ -122,7 +122,7 @@ Function Invoke-EditGroup { $ID = 'https://graph.microsoft.com/beta/users/' + (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($_)" -tenantid $TenantId).id Write-Host $ID $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/owners/`$ref" -tenantid $TenantId -type POST -body ('{"@odata.id": "' + $ID + '"}') - Write-LogMessage -API $APINAME -tenant $TenantId -user $request.headers.'x-ms-client-principal' -message "Added owner $_ to $($GroupName) group" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $TenantId -headers $Request.Headers -message "Added owner $_ to $($GroupName) group" -Sev 'Info' $null = $results.add("Success. $_ has been added $($GroupName)") } catch { $null = $results.add("Failed to add owner $_ to $($GroupName): Error:$($_.Exception.Message)") @@ -132,7 +132,7 @@ Function Invoke-EditGroup { } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $TenantId -API $APINAME -message "Add member API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -tenant $TenantId -API $APINAME -message "Add member API failed. $($_.Exception.Message)" -Sev 'Error' } $RemoveOwners = ($userobj.RemoveOwner).value @@ -142,7 +142,7 @@ Function Invoke-EditGroup { try { $MemberInfo = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($_)" -tenantid $TenantId) New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/owners/$($MemberInfo.id)/`$ref" -tenantid $TenantId -type DELETE - Write-LogMessage -API $APINAME -tenant $TenantId -user $request.headers.'x-ms-client-principal' -message "Removed $($MemberInfo.UserPrincipalname) from $($userobj.displayname) group" -Sev 'Info' + Write-LogMessage -API $APINAME -tenant $TenantId -headers $Request.Headers -message "Removed $($MemberInfo.UserPrincipalname) from $($userobj.displayname) group" -Sev 'Info' $null = $results.add("Success. Member $_ has been removed from $($GroupName)") } catch { $null = $results.add("Failed to remove $_ from $($GroupName): $($_.Exception.Message)") @@ -150,17 +150,17 @@ Function Invoke-EditGroup { } } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Failed to remove $RemoveMembers from $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Failed to remove $RemoveMembers from $($GroupName). Error:$($_.Exception.Message)" -Sev 'Error' $body = $results.add("Could not remove $RemoveMembers from $($GroupName). $($_.Exception.Message)") } if ($userobj.allowExternal -eq 'true') { try { - Set-CIPPGroupAuthentication -ID $userobj.mail -GroupType $GroupType -tenantFilter $TenantId -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + Set-CIPPGroupAuthentication -ID $userobj.mail -GroupType $GroupType -tenantFilter $TenantId -APIName $APINAME -Headers $Request.Headers $body = $results.add("Allowed external senders to send to $($userobj.mail).") } catch { $body = $results.add("Failed to allow external senders to send to $($userobj.mail).") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Failed to allow external senders for $($userobj.mail). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Failed to allow external senders for $($userobj.mail). Error:$($_.Exception.Message)" -Sev 'Error' } } @@ -180,10 +180,10 @@ Function Invoke-EditGroup { $body = $results.add("Send Copies of team emails and events to team members inboxes for $($userobj.mail) enabled.") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Send Copies of team emails and events to team members inboxes for $($userobj.mail) enabled." -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Send Copies of team emails and events to team members inboxes for $($userobj.mail) enabled." -Sev 'Info' } catch { $body = $results.add("Failed to Send Copies of team emails and events to team members inboxes for $($userobj.mail).") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $TenantId -message "Failed to Send Copies of team emails and events to team members inboxes for $($userobj.mail). Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $TenantId -message "Failed to Send Copies of team emails and events to team members inboxes for $($userobj.mail). Error:$($_.Exception.Message)" -Sev 'Error' } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-ListGroupSenderAuthentication.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-ListGroupSenderAuthentication.ps1 index 97ca6fe52147..11d70a0f2f8a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-ListGroupSenderAuthentication.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Groups/Invoke-ListGroupSenderAuthentication.ps1 @@ -4,8 +4,8 @@ Function Invoke-ListGroupSenderAuthentication { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -19,17 +19,17 @@ Function Invoke-ListGroupSenderAuthentication { Identity = $groupid } - + try { switch ($GroupType) { 'Distribution List' { Write-Host 'Checking DL' - $State = (New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-DistributionGroup' -cmdParams $params -UseSystemMailbox $true).RequireSenderAuthenticationEnabled + $State = (New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-DistributionGroup' -cmdParams $params -UseSystemMailbox $true).RequireSenderAuthenticationEnabled } 'Microsoft 365' { Write-Host 'Checking M365 Group' - $State = (New-ExoRequest -tenantid $TenantFilter -cmdlet 'get-unifiedgroup' -cmdParams $params -UseSystemMailbox $true).RequireSenderAuthenticationEnabled - + $State = (New-ExoRequest -tenantid $TenantFilter -cmdlet 'get-unifiedgroup' -cmdParams $params -UseSystemMailbox $true).RequireSenderAuthenticationEnabled + } default { $state = $true } } @@ -40,7 +40,7 @@ Function Invoke-ListGroupSenderAuthentication { # We flip the value because the API is asking if the group is allowed to receive external mail Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK + StatusCode = [HttpStatusCode]::OK Body = @{ allowedToReceiveExternal = !$state } }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddGuest.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddGuest.ps1 index 440d8c3d2865..31cae1bd1f10 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddGuest.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddGuest.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddGuest { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Results = [System.Collections.ArrayList]@() $userobj = $Request.body @@ -37,13 +37,13 @@ Function Invoke-AddGuest { $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/invitations' -tenantid $Userobj.tenantFilter -type POST -body $BodyToship -verbose if ($Userobj.sendInvite -eq 'true') { $results.add('Invited Guest. Invite Email sent') - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantFilter) -message "Invited Guest $($userobj.displayname) with Email Invite " -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantFilter) -message "Invited Guest $($userobj.displayname) with Email Invite " -Sev 'Info' } else { $results.add('Invited Guest. No Invite Email was sent') - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantFilter) -message "Invited Guest $($userobj.displayname) with no Email Invite " -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantFilter) -message "Invited Guest $($userobj.displayname) with no Email Invite " -Sev 'Info' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantFilter) -message "Guest Invite API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantFilter) -message "Guest Invite API failed. $($_.Exception.Message)" -Sev 'Error' $body = $results.add("Failed to Invite Guest. $($_.Exception.Message)" ) } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUser.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUser.ps1 index 0d4f7f24a488..c3233b0bf8f6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUser.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUser.ps1 @@ -11,7 +11,7 @@ Function Invoke-AddUser { param($Request, $TriggerMetadata) $APIName = 'AddUser' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $UserObj = $Request.body @@ -31,12 +31,12 @@ Function Invoke-AddUser { PSA = [bool]$Request.Body.PostExecution.PSA } } - Add-CIPPScheduledTask -Task $TaskBody -hidden $false -DisallowDuplicateName $true + Add-CIPPScheduledTask -Task $TaskBody -hidden $false -DisallowDuplicateName $true -Headers $Request.Headers $body = [pscustomobject] @{ 'Results' = @("Successfully created scheduled task to create user $($UserObj.DisplayName)") } } else { - $CreationResults = New-CIPPUserTask -userobj $UserObj -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $CreationResults = New-CIPPUserTask -userobj $UserObj -APIName $APINAME -Headers $Request.Headers $body = [pscustomobject] @{ 'Results' = $CreationResults.Results 'Username' = $CreationResults.username diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUserBulk.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUserBulk.ps1 index 25150677f7cd..834f3ea75238 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUserBulk.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-AddUserBulk.ps1 @@ -11,7 +11,7 @@ Function Invoke-AddUserBulk { param($Request, $TriggerMetadata) $APIName = 'AddUserBulk' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.body.TenantFilter $Body = foreach ($userobj in $request.body.BulkUser) { if ($userobj.usageLocation.value) { @@ -32,7 +32,7 @@ Function Invoke-AddUserBulk { Write-Host "Our body to ship is $bodyToShip" $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/users' -tenantid $TenantFilter -type POST -body $BodyToship Write-Host "Graph request is $GraphRequest" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Created user $($userobj.displayname) with id $($GraphRequest.id) " -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($TenantFilter) -message "Created user $($userobj.displayname) with id $($GraphRequest.id) " -Sev 'Info' #PWPush $PasswordLink = New-PwPushLink -Payload $password @@ -42,7 +42,7 @@ Function Invoke-AddUserBulk { $results = "Created user $($UserprincipalName). Password is $password" } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Failed to create user. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($TenantFilter) -message "Failed to create user. Error:$($_.Exception.Message)" -Sev 'Error' $results = "Failed to create user $($UserprincipalName). $($_.Exception.Message)" } [PSCustomObject]@{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-EditUser.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-EditUser.ps1 index 4ed2b204bfc1..aaf0fd5f0a15 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-EditUser.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-EditUser.ps1 @@ -10,9 +10,9 @@ Function Invoke-EditUser { [CmdletBinding()] param($Request, $TriggerMetadata) - $ApiName = $TriggerMetadata.FunctionName - $User = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $ApiName -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -headers $Request.headers -API $ApiName -message 'Accessed this API' -Sev 'Debug' $UserObj = $Request.body if ($UserObj.id -eq '') { @@ -59,27 +59,28 @@ Function Invoke-EditUser { $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 { - $null = $results.Add("Edited property $($_.Key) with value $($_.Value)") - $bodytoShip | Add-Member -NotePropertyName $_.Key -NotePropertyValue $_.Value -Force + if ($UserObj.defaultAttributes) { + $UserObj.defaultAttributes | Get-Member -MemberType NoteProperty | ForEach-Object { + Write-Host "Editing user and adding $($_.Name) with value $($UserObj.defaultAttributes.$($_.Name).value)" + if (-not [string]::IsNullOrWhiteSpace($UserObj.defaultAttributes.$($_.Name).value)) { + Write-Host 'adding body to ship' + $BodyToShip | Add-Member -NotePropertyName $_.Name -NotePropertyValue $UserObj.defaultAttributes.$($_.Name).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 $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 + Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -headers $Request.Headers -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 $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 + Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -headers $Request.Headers -message "Reset $($UserObj.DisplayName)'s Password" -Sev Info } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "User edit API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -headers $Request.Headers -message "User edit API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $null = $results.Add( "Failed to edit user. $($ErrorMessage.NormalizedError)") } @@ -95,12 +96,12 @@ Function Invoke-EditUser { $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 + $licResults = Set-CIPPUserLicense -UserId $UserObj.id -TenantFilter $UserObj.tenantFilter -RemoveLicenses $CurrentLicenses.assignedLicenses.skuId -Headers $Request.Headers $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 + $licResults = Set-CIPPUserLicense -UserId $UserObj.id -TenantFilter $UserObj.tenantFilter -RemoveLicenses $RemoveLicenses -AddLicenses $licenses -Headers $Request.headers $null = $results.Add($licResults) } @@ -109,7 +110,7 @@ Function Invoke-EditUser { } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "License assign API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -headers $Request.Headers -message "License assign API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $null = $results.Add( "We've failed to assign the license. $($ErrorMessage.NormalizedError)") } @@ -121,18 +122,18 @@ Function Invoke-EditUser { $null = 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`": `"$UserPrincipalName`"}" -Verbose - Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "Added Aliases to $($UserObj.DisplayName)" -Sev Info + Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -headers $Request.Headers -message "Added Aliases to $($UserObj.DisplayName)" -Sev Info $null = $results.Add( 'Success. added aliases to user.') } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -user $User -message "Alias API failed. $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -API $ApiName -tenant ($UserObj.tenantFilter) -headers $Request.Headers -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 $User -CopyFromId $Request.body.CopyFrom.value -UserID $UserPrincipalName -TenantFilter $UserObj.tenantFilter + $CopyFrom = Set-CIPPCopyGroupMembers -Headers $User -CopyFromId $Request.body.CopyFrom.value -UserID $UserPrincipalName -TenantFilter $UserObj.tenantFilter $null = $results.AddRange(@($CopyFrom)) } @@ -163,11 +164,11 @@ Function Invoke-EditUser { } - Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Added $($UserObj.DisplayName) to $GroupName group" -Sev Info + Write-LogMessage -headers $Request.Headers -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 { $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 + Write-LogMessage -headers $Request.Headers -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)") } @@ -177,7 +178,7 @@ Function Invoke-EditUser { $ManagerBody = [PSCustomObject]@{'@odata.id' = "https://graph.microsoft.com/beta/users/$($Request.body.setManager.value)" } $ManagerBodyJSON = ConvertTo-Json -Compress -Depth 10 -InputObject $ManagerBody $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 + Write-LogMessage -headers $Request.Headers -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)") } @@ -204,11 +205,11 @@ Function Invoke-EditUser { } - Write-LogMessage -user $User -API $ApiName -tenant $UserObj.tenantFilter -message "Removed $($UserObj.DisplayName) from $GroupName group" -Sev Info + Write-LogMessage -headers $Request.Headers -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 { $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 + Write-LogMessage -headers $Request.Headers -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)") } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecBECRemediate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecBECRemediate.ps1 index f8bd672e0c43..20927bbfa3ec 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecBECRemediate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecBECRemediate.ps1 @@ -10,10 +10,10 @@ Function Invoke-ExecBECRemediate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host 'PowerShell HTTP trigger function processed a request.' $TenantFilter = $request.body.tenantfilter @@ -23,13 +23,13 @@ Function Invoke-ExecBECRemediate { Write-Host $SuspectUser $Results = try { $Step = 'Reset Password' - Set-CIPPResetPassword -UserID $username -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $User + Set-CIPPResetPassword -UserID $username -tenantFilter $TenantFilter -APIName $APINAME -Headers $User $Step = 'Disable Account' - Set-CIPPSignInState -userid $username -AccountEnabled $false -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $User + Set-CIPPSignInState -userid $username -AccountEnabled $false -tenantFilter $TenantFilter -APIName $APINAME -Headers $User $Step = 'Revoke Sessions' - Revoke-CIPPSessions -userid $SuspectUser -username $username -ExecutingUser $User -APIName $APINAME -tenantFilter $TenantFilter + Revoke-CIPPSessions -userid $SuspectUser -username $username -Headers $User -APIName $APINAME -tenantFilter $TenantFilter $Step = 'Remove MFA methods' - Remove-CIPPUserMFA -UserPrincipalName $username -TenantFilter $TenantFilter -ExecutingUser $User + Remove-CIPPUserMFA -UserPrincipalName $username -TenantFilter $TenantFilter -Headers $User $Step = 'Disable Inbox Rules' $Rules = New-ExoRequest -anchor $username -tenantid $TenantFilter -cmdlet 'Get-InboxRule' -cmdParams @{Mailbox = $username; IncludeHidden = $true } $RuleDisabled = 0 diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecClrImmId.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecClrImmId.ps1 index 6ebf2e66750b..50374bc33a1b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecClrImmId.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecClrImmId.ps1 @@ -10,29 +10,24 @@ Function Invoke-ExecClrImmId { [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 = $Request.Params.CIPPEndpoint + $TenantFilter = $Request.Query.tenantFilter ?? $Request.Body.tenantFilter + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Accessed this API' -Sev Debug + $UserID = $Request.Query.ID ?? $Request.Body.ID - # Write to the Azure Functions log stream. - Write-Host 'PowerShell HTTP trigger function processed a request.' - - # Interact with query parameters or the body of the request. Try { - $TenantFilter = $Request.Query.TenantFilter - $UserID = $Request.Query.ID - $Body = [pscustomobject]@{ onPremisesImmutableId = $null } - $Body = ConvertTo-Json -InputObject $Body -Depth 5 -Compress - $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$UserID" -tenantid $TenantFilter -type PATCH -body $Body - $Results = [pscustomobject]@{'Results' = 'Successfully Cleared ImmutableId' } + $Result = Clear-CIPPImmutableId -userid $UserID -TenantFilter $TenantFilter -Headers $Request.Headers -APIName $APIName + $StatusCode = [HttpStatusCode]::OK } catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception - $Results = [pscustomobject]@{'Results' = "Failed. $ErrorMessage"; colour = 'danger' } - $_.Exception + $ErrorMessage = Get-CippException -Exception $_ + $Result = $ErrorMessage.NormalizedError + $StatusCode = [HttpStatusCode]::InternalServerError } + $Results = [pscustomobject]@{'Results' = $Result } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK + StatusCode = $StatusCode Body = $Results }) } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecCreateTAP.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecCreateTAP.ps1 index 5aa1ac84f245..4fc76d7300a6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecCreateTAP.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecCreateTAP.ps1 @@ -10,12 +10,12 @@ Function Invoke-ExecCreateTAP { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. try { - $TAP = New-CIPPTAP -userid $Request.query.ID -TenantFilter $Request.query.tenantfilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $TAP = New-CIPPTAP -userid $Request.query.ID -TenantFilter $Request.query.tenantfilter -APIName $APINAME -Headers $Request.Headers $Results = [pscustomobject]@{'Results' = $TAP } } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDisableUser.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDisableUser.ps1 index b5b80a86d7c8..31aeb9f5d45f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDisableUser.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDisableUser.ps1 @@ -10,9 +10,9 @@ Function Invoke-ExecDisableUser { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint try { - $State = Set-CIPPSignInState -userid $Request.query.ID -TenantFilter $Request.Query.TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' -AccountEnabled ([System.Convert]::ToBoolean($Request.Query.Enable)) + $State = Set-CIPPSignInState -userid $Request.query.ID -TenantFilter $Request.Query.TenantFilter -APIName $APINAME -Headers $Request.Headers -AccountEnabled ([System.Convert]::ToBoolean($Request.Query.Enable)) $Results = [pscustomobject]@{'Results' = "$State" } } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDismissRiskyUser.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDismissRiskyUser.ps1 index 9d4a9e2e55e4..53cdc664fa6c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDismissRiskyUser.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecDismissRiskyUser.ps1 @@ -8,8 +8,8 @@ function Invoke-ExecDismissRiskyUser { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host 'PowerShell HTTP trigger function processed a request.' $TenantFilter = $Request.Query.tenantfilter diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 index 1ef908304c17..ac6b85aaf80a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 @@ -11,9 +11,9 @@ Function Invoke-ExecJITAdmin { param($Request, $TriggerMetadata) $APIName = 'ExecJITAdmin' - $User = $Request.Headers.'x-ms-client-principal' + $User = $Request.Headers $TenantFilter = $Request.body.TenantFilter.value ? $Request.body.TenantFilter.value : $Request.body.TenantFilter - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($Request.Query.Action -eq 'List') { $Schema = Get-CIPPSchemaExtensions | Where-Object { $_.id -match '_cippUser' } @@ -63,14 +63,14 @@ Function Invoke-ExecJITAdmin { if ($Request.Body.existingUser.value -match '^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$') { $Username = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($Request.Body.existingUser.value)" -tenantid $TenantFilter).userPrincipalName } - Write-LogMessage -user $User -API $APINAME -message "Executing JIT Admin for $Username" -tenant $TenantFilter -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Executing JIT Admin for $Username" -tenant $TenantFilter -Sev 'Info' $Start = ([System.DateTimeOffset]::FromUnixTimeSeconds($Request.Body.StartDate)).DateTime.ToLocalTime() $Expiration = ([System.DateTimeOffset]::FromUnixTimeSeconds($Request.Body.EndDate)).DateTime.ToLocalTime() $Results = [System.Collections.Generic.List[string]]::new() if ($Request.Body.useraction -eq 'Create') { - Write-LogMessage -user $User -API $APINAME -tenant $TenantFilter -message "Creating JIT Admin user $($Request.Body.Username)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $TenantFilter -message "Creating JIT Admin user $($Request.Body.Username)" -Sev 'Info' Write-Information "Creating JIT Admin user $($Request.Body.username)" $JITAdmin = @{ User = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 index c692f729818d..0a4b40bba8e8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 @@ -14,7 +14,7 @@ Function Invoke-ExecOffboardUser { $Results = foreach ($username in $AllUsers) { try { $APIName = 'ExecOffboardUser' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($Request.body.Scheduled.enabled) { $taskObject = [PSCustomObject]@{ @@ -36,9 +36,9 @@ Function Invoke-ExecOffboardUser { PSA = [bool]$Request.Body.PostExecution.psa } } - Add-CIPPScheduledTask -Task $taskObject -hidden $false + Add-CIPPScheduledTask -Task $taskObject -hidden $false -Headers $Request.Headers } else { - Invoke-CIPPOffboardingJob -Username $Username -TenantFilter $Tenantfilter -Options $Request.body -APIName $APIName -ExecutingUser $request.headers.'x-ms-client-principal' + Invoke-CIPPOffboardingJob -Username $Username -TenantFilter $Tenantfilter -Options $Request.body -APIName $APIName -Headers $Request.Headers } $StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboard_Mailboxpermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboard_Mailboxpermissions.ps1 index 02e60ca462d0..10b4c8576330 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboard_Mailboxpermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboard_Mailboxpermissions.ps1 @@ -11,7 +11,7 @@ Function Invoke-ExecOffboard_Mailboxpermissions { param($Request, $TriggerMetadata) foreach ($Mailbox in $Mailboxes) { - Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid $Mailbox.UserPrincipalName -AccessUser $QueueItem.User -TenantFilter $QueueItem.TenantFilter -APIName $APINAME -ExecutingUser $QueueItem.ExecutingUser + Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid $Mailbox.UserPrincipalName -AccessUser $QueueItem.User -TenantFilter $QueueItem.TenantFilter -APIName $APINAME -Headers $QueueItem.Headers } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOneDriveShortCut.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOneDriveShortCut.ps1 index d34101aa3923..7030dac2a4da 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOneDriveShortCut.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOneDriveShortCut.ps1 @@ -10,11 +10,11 @@ Function Invoke-ExecOneDriveShortCut { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Try { - $MessageResult = New-CIPPOneDriveShortCut -username $Request.Body.username -userid $Request.Body.userid -TenantFilter $Request.Body.tenantFilter -URL $Request.Body.siteUrl.value -ExecutingUser $request.headers.'x-ms-client-principal' + $MessageResult = New-CIPPOneDriveShortCut -username $Request.Body.username -userid $Request.Body.userid -TenantFilter $Request.Body.tenantFilter -URL $Request.Body.siteUrl.value -Headers $Request.Headers $Results = [pscustomobject]@{ 'Results' = "$MessageResult" } } catch { $Results = [pscustomobject]@{'Results' = "OneDrive Shortcut creation failed: $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOnedriveProvision.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOnedriveProvision.ps1 index bc84330fccef..d86806c39f68 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOnedriveProvision.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOnedriveProvision.ps1 @@ -10,10 +10,10 @@ Function Invoke-ExecOneDriveProvision { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $Params = $Request.Body ?? $Request.Query try { - $State = Request-CIPPSPOPersonalSite -TenantFilter $Params.TenantFilter -UserEmails $Params.UserPrincipalName -ExecutingUser $Request.Headers.'x-ms-client-principal' -APIName $APINAME + $State = Request-CIPPSPOPersonalSite -TenantFilter $Params.TenantFilter -UserEmails $Params.UserPrincipalName -Headers $Request.Headers -APIName $APINAME $Results = [pscustomobject]@{'Results' = "$State" } } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFA.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFA.ps1 index 58155d6fa8e3..5dbea9130edd 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFA.ps1 @@ -15,7 +15,7 @@ function Invoke-ExecPerUserMFA { userId = $Request.Body.userId TenantFilter = $Request.Body.TenantFilter State = $Request.Body.State.value ? $Request.Body.State.value : $Request.Body.State - executingUser = $Request.Headers.'x-ms-client-principal' + Headers = $Request.Headers } $Result = Set-CIPPPerUserMFA @Request $Body = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFAAllUsers.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFAAllUsers.ps1 index f91b1f3a5a89..f1eec308807f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFAAllUsers.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecPerUserMFAAllUsers.ps1 @@ -16,7 +16,7 @@ function Invoke-ExecPerUserMFAAllUsers { userId = $Users.id TenantFilter = $tenantfilter State = $Request.query.State - executingUser = $Request.Headers.'x-ms-client-principal' + Headers = $Request.Headers } $Result = Set-CIPPPerUserMFA @Request $Body = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetMFA.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetMFA.ps1 index ee9e9b65487c..f7ecd21d59e9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetMFA.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetMFA.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecResetMFA { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter @@ -19,11 +19,11 @@ Function Invoke-ExecResetMFA { try { $Body = @{ - Results = Remove-CIPPUserMFA -UserPrincipalName $UserID -TenantFilter $TenantFilter -ExecutingUser $request.headers.'x-ms-client-principal' + Results = Remove-CIPPUserMFA -UserPrincipalName $UserID -TenantFilter $TenantFilter -Headers $Request.Headers } } catch { $Body = [pscustomobject]@{'Results' = "Failed to reset MFA methods for $($Request.Query.ID): $(Get-NormalizedError -message $_.Exception.Message)" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to reset MFA for user $($Request.Query.ID): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to reset MFA for user $($Request.Query.ID): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetPass.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetPass.ps1 index 98be3b461aa4..60f78066ef3b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetPass.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecResetPass.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecResetPass { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -22,11 +22,11 @@ Function Invoke-ExecResetPass { $mustChange = [System.Convert]::ToBoolean($request.query.MustChange) try { - $Reset = Set-CIPPResetPassword -userid $Request.query.ID -tenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' -forceChangePasswordNextSignIn $mustChange + $Reset = Set-CIPPResetPassword -userid $Request.query.ID -tenantFilter $TenantFilter -APIName $APINAME -Headers $Request.Headers -forceChangePasswordNextSignIn $mustChange $Results = [pscustomobject]@{'Results' = $Reset } } catch { $Results = [pscustomobject]@{'Results' = "Failed to reset password for $($Request.query.displayName): $($_.Exception.Message)" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to reset password for $($Request.query.displayName): $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to reset password for $($Request.query.displayName): $($_.Exception.Message)" -Sev 'Error' } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecRevokeSessions.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecRevokeSessions.ps1 index a17b40139b05..0c1b8bc5210d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecRevokeSessions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecRevokeSessions.ps1 @@ -10,13 +10,13 @@ Function Invoke-ExecRevokeSessions { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter try { - $RevokeSessions = Revoke-CIPPSessions -userid $Request.Query.id -tenantFilter $TenantFilter -username $Request.Query.Username -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $RevokeSessions = Revoke-CIPPSessions -userid $Request.Query.id -tenantFilter $TenantFilter -username $Request.Query.Username -APIName $APINAME -Headers $Request.Headers $Results = [pscustomobject]@{'Results' = $RevokeSessions } } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecSendPush.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecSendPush.ps1 index 38ca6d3d876e..d077f97949bb 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecSendPush.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecSendPush.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecSendPush { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.body.TenantFilter $UserEmail = $Request.body.UserEmail @@ -114,7 +114,7 @@ Function Invoke-ExecSendPush { } $Results = [pscustomobject]@{'Results' = $Body; severity = $colour } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Sent push request to $UserEmail - Result: $($obj.BeginTwoWayAuthenticationResponse.result.value | Out-String)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Sent push request to $UserEmail - Result: $($obj.BeginTwoWayAuthenticationResponse.result.value | Out-String)" -Sev 'Info' Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListPerUserMFA.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListPerUserMFA.ps1 index 39bbcd9bc268..7bc8db4c1fd7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListPerUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListPerUserMFA.ps1 @@ -10,9 +10,9 @@ function Invoke-ListPerUserMFA { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserConditionalAccessPolicies.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserConditionalAccessPolicies.ps1 index c717f77589f1..e2399fabe5c0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserConditionalAccessPolicies.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserConditionalAccessPolicies.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListUserConditionalAccessPolicies { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserCounts.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserCounts.ps1 index d67251b461e0..fbbdde8aa359 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserCounts.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserCounts.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListUserCounts { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserDevices.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserDevices.ps1 index 0c36e75712fd..52e841377b01 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserDevices.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserDevices.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListUserDevices { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserGroups.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserGroups.ps1 index 26676aec5623..870d2a755d48 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserGroups.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserGroups.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListUserGroups { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxDetails.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxDetails.ps1 index f6581a8abaf6..512ca633f54f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxDetails.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxDetails.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListUserMailboxDetails { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxRules.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxRules.ps1 index 4ea9b6d8a35a..a264dc39f8c6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxRules.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserMailboxRules.ps1 @@ -10,9 +10,9 @@ Function Invoke-ListUserMailboxRules { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -26,7 +26,7 @@ Function Invoke-ListUserMailboxRules { $GraphRequest = New-ExoRequest -Anchor $UserID -tenantid $TenantFilter -cmdlet 'Get-InboxRule' -cmdParams @{mailbox = $UserID; IncludeHidden = $true } | Where-Object { $_.Name -ne 'Junk E-Mail Rule' -and $_.Name -notlike 'Microsoft.Exchange.OOF.*' } | Select-Object * -ExcludeProperty RuleIdentity } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to retrieve mailbox rules $($UserEmail): $($ErrorMessage.NormalizedError) " -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to retrieve mailbox rules $($UserEmail): $($ErrorMessage.NormalizedError) " -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = '500' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSettings.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSettings.ps1 index 85b59ec479fd..b8e3acf588d0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSettings.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSettings.ps1 @@ -9,8 +9,8 @@ function Invoke-ListUserSettings { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($request.headers.'x-ms-client-principal')) | ConvertFrom-Json).userDetails try { @@ -30,4 +30,4 @@ function Invoke-ListUserSettings { Body = $Results }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSigninLogs.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSigninLogs.ps1 index d92d6e241df5..9df706720a68 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSigninLogs.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUserSigninLogs.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListUserSigninLogs { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $top = $Request.Query.top ? $Request.Query.top : 50 # Write to the Azure Functions log stream. @@ -31,7 +31,7 @@ Function Invoke-ListUserSigninLogs { Body = @($GraphRequest) }) } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to retrieve Sign In report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to retrieve Sign In report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = '500' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUsers.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUsers.ps1 index e138cc02e470..0f6ff909234f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUsers.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ListUsers.ps1 @@ -10,7 +10,7 @@ Function Invoke-ListUsers { [CmdletBinding()] param($Request, $TriggerMetadata) - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Reports/Invoke-ListBasicAuth.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Reports/Invoke-ListBasicAuth.ps1 index aacc1676381a..59771940285b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Reports/Invoke-ListBasicAuth.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Reports/Invoke-ListBasicAuth.ps1 @@ -13,7 +13,7 @@ Function Invoke-ListBasicAuth { # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter $currentTime = Get-Date -Format 'yyyy-MM-ddTHH:MM:ss' @@ -26,7 +26,7 @@ Function Invoke-ListBasicAuth { try { $GraphRequest = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/auditLogs/signIns?api-version=beta&filter=$($filters)" -tenantid $TenantFilter -erroraction stop | Select-Object userPrincipalName, clientAppUsed, Status | Sort-Object -Unique -Property userPrincipalName $response = $GraphRequest - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Retrieved basic authentication report' -Sev 'Debug' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Retrieved basic authentication report' -Sev 'Debug' -tenant $TenantFilter # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ @@ -34,7 +34,7 @@ Function Invoke-ListBasicAuth { Body = @($response) }) } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to retrieve basic authentication report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to retrieve basic authentication report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = '500' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecAlertsList.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecAlertsList.ps1 index 2fad771b8707..dc7f3459a58c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecAlertsList.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecAlertsList.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAlertsList { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecIncidentsList.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecIncidentsList.ps1 index bf31040b83a8..fbe9ed284818 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecIncidentsList.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecIncidentsList.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecIncidentsList { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityAlert.ps1 index da3bc31ab858..3cefd1b913f7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityAlert.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecSetSecurityAlert { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $tenantfilter = $Request.Query.TenantFilter @@ -20,11 +20,11 @@ Function Invoke-ExecSetSecurityAlert { $AssignBody = '{"status":"' + $Status + '","vendorInformation":{"provider":"' + $Request.query.provider + '","vendor":"' + $Request.query.vendor + '"}}' try { $GraphRequest = New-Graphpostrequest -uri "https://graph.microsoft.com/beta/security/alerts/$AlertFilter" -type PATCH -tenantid $TenantFilter -body $Assignbody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Set alert $AlertFilter to status $Status" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Set alert $AlertFilter to status $Status" -Sev 'Info' $body = [pscustomobject]@{'Results' = "Set status for alert to $Status" } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Failed to update alert $($AlertFilter): $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Failed to update alert $($AlertFilter): $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to change status: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityIncident.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityIncident.ps1 index b1065f721a29..25892d30b508 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityIncident.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Security/Invoke-ExecSetSecurityIncident.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecSetSecurityIncident { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $first = '' # Interact with query parameters or the body of the request. @@ -60,15 +60,15 @@ Function Invoke-ExecSetSecurityIncident { $ResponseBody = [pscustomobject]@{'Results' = $BodyBuild } New-Graphpostrequest -uri "https://graph.microsoft.com/beta/security/incidents/$IncidentFilter" -type PATCH -tenantid $TenantFilter -body $Assignbody -asApp $true - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Update incident $IncidentFilter with values $Assignbody" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Update incident $IncidentFilter with values $Assignbody" -Sev 'Info' } else { $ResponseBody = [pscustomobject]@{'Results' = 'Cannot update redirected incident' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Refuse to pdate incident $IncidentFilter with values $Assignbody because it is redirected to another incident" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Refuse to pdate incident $IncidentFilter with values $Assignbody because it is redirected to another incident" -Sev 'Info' } $body = $ResponseBody } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Failed to update alert $($AlertFilter): $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantfilter) -message "Failed to update alert $($AlertFilter): $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to update incident: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSite.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSite.ps1 index ab7474163cdc..be7dc4e714b3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSite.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSite.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddSite { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $SharePointObj = $Request.body @@ -19,7 +19,7 @@ Function Invoke-AddSite { $SharePointSite = New-CIPPSharepointSite -SiteName $SharePointObj.siteName -SiteDescription $SharePointObj.siteDescription -SiteOwner $SharePointObj.siteOwner.value -TemplateName $SharePointObj.templateName.value -SiteDesign $SharePointObj.siteDesign.value -SensitivityLabel $SharePointObj.sensitivityLabel -TenantFilter $SharePointObj.tenantFilter $body = [pscustomobject]@{'Results' = $SharePointSite } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Adding SharePoint Site failed. Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantid) -message "Adding SharePoint Site failed. Error: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. Error message: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSiteBulk.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSiteBulk.ps1 index ff9eb3cfce9e..049af0fbd648 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSiteBulk.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddSiteBulk.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddSiteBulk { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Results = [System.Collections.ArrayList]@() @@ -21,7 +21,7 @@ Function Invoke-AddSiteBulk { $SharePointSite = New-CIPPSharepointSite -SiteName $SharePointObj.siteName -SiteDescription $SharePointObj.siteDescription -SiteOwner $SharePointObj.siteOwner -TemplateName $SharePointObj.templateName -SiteDesign $SharePointObj.siteDesign -SensitivityLabel $SharePointObj.sensitivityLabel -TenantFilter $Request.body.TenantFilter $Results.add($SharePointSite) } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Adding SharePoint Site failed. Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantid) -message "Adding SharePoint Site failed. Error: $($_.Exception.Message)" -Sev 'Error' $Results.add("Failed to create $($sharepointObj.siteName) Error message: $($_.Exception.Message)") } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddTeam.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddTeam.ps1 index ffeb0da53459..6c00d43d4bb2 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddTeam.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-AddTeam.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddTeam { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $userobj = $Request.body @@ -43,11 +43,11 @@ Function Invoke-AddTeam { Write-Host $TeamsSettings New-GraphPostRequest -AsApp $true -uri 'https://graph.microsoft.com/beta/teams' -tenantid $Userobj.tenantid -type POST -body $TeamsSettings -verbose - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Added Team $($userobj.displayname)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantid) -message "Added Team $($userobj.displayname)" -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Success. Team has been added' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Adding Team failed. Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($userobj.tenantid) -message "Adding Team failed. Error: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. Error message: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecRemoveTeamsVoicePhoneNumberAssignment.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecRemoveTeamsVoicePhoneNumberAssignment.ps1 index 55619f07deb5..4af90af25044 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecRemoveTeamsVoicePhoneNumberAssignment.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecRemoveTeamsVoicePhoneNumberAssignment.ps1 @@ -10,18 +10,18 @@ Function Invoke-ExecRemoveTeamsVoicePhoneNumberAssignment { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $tenantFilter = $Request.Body.TenantFilter try { $null = New-TeamsRequest -TenantFilter $TenantFilter -Cmdlet 'Remove-CsPhoneNumberAssignment' -CmdParams @{Identity = $Request.Body.AssignedTo; PhoneNumber = $Request.Body.PhoneNumber; PhoneNumberType = $Request.Body.PhoneNumberType; ErrorAction = 'stop'} $Results = [pscustomobject]@{'Results' = "Successfully unassigned $($Request.Body.PhoneNumber) from $($Request.Body.AssignedTo)"} - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev 'Info' } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $Results = [pscustomobject]@{'Results' = $ErrorMessage} - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSetSharePointMember.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSetSharePointMember.ps1 index e5851ab0fd44..0894c81fbdf1 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSetSharePointMember.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSetSharePointMember.ps1 @@ -11,9 +11,9 @@ Function Invoke-ExecSetSharePointMember { param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.body.tenantFilter @@ -21,10 +21,10 @@ Function Invoke-ExecSetSharePointMember { if ($Request.body.SharePointType -eq 'Group') { $GroupId = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/groups?`$filter=mail eq '$($Request.Body.GroupID)' or proxyAddresses/any(x:endsWith(x,'$($Request.Body.GroupID)'))&`$count=true" -ComplexFilter -tenantid $TenantFilter).id if ($Request.body.Add -eq $true) { - $Results = Add-CIPPGroupMember -GroupType 'Team' -GroupID $GroupID -Member $Request.Body.user.value -TenantFilter $TenantFilter -ExecutingUser $ExecutingUser + $Results = Add-CIPPGroupMember -GroupType 'Team' -GroupID $GroupID -Member $Request.Body.user.value -TenantFilter $TenantFilter -Headers $Request.Headers } else { $UserID = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($Request.Body.user.value)" -tenantid $TenantFilter).id - $Results = Remove-CIPPGroupMember -GroupType 'Team' -GroupID $GroupID -Member $UserID -TenantFilter $TenantFilter -ExecutingUser $ExecutingUser + $Results = Remove-CIPPGroupMember -GroupType 'Team' -GroupID $GroupID -Member $UserID -TenantFilter $TenantFilter -Headers $Request.Headers } } else { $Results = 'This type of SharePoint site is not supported.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSharePointPerms.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSharePointPerms.ps1 index 40934b0bb546..8f6e939440fb 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSharePointPerms.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecSharePointPerms.ps1 @@ -10,11 +10,11 @@ Function Invoke-ExecSharePointPerms { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $tenantFilter = $Request.Body.tenantFilter - $ExecutingUser = $Request.Headers.'x-ms-client-principal' + $Headers = $Request.Headers - Write-LogMessage -user $ExecutingUser -API $APIName -message 'Accessed this API' -Sev Debug + Write-LogMessage -Headers $Headers -API $APIName -message 'Accessed this API' -Sev Debug # The UPN or ID of the users OneDrive we are changing permissions on $UserId = $Request.body.UPN @@ -26,7 +26,7 @@ Function Invoke-ExecSharePointPerms { $State = Set-CIPPSharePointPerms -tenantFilter $tenantFilter ` -UserId $UserId ` -OnedriveAccessUser $OnedriveAccessUser ` - -ExecutingUser $ExecutingUser ` + -Headers $Request.Headers ` -APIName $APIName ` -RemovePermission $Request.body.RemovePermission ` -URL $Request.Body.URL diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecTeamsVoicePhoneNumberAssignment.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecTeamsVoicePhoneNumberAssignment.ps1 index 4714c300685a..acc53b79f4c3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecTeamsVoicePhoneNumberAssignment.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ExecTeamsVoicePhoneNumberAssignment.ps1 @@ -10,9 +10,9 @@ Function Invoke-ExecTeamsVoicePhoneNumberAssignment { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Identity = $Request.Body.input.value $tenantFilter = $Request.Body.TenantFilter @@ -24,12 +24,12 @@ Function Invoke-ExecTeamsVoicePhoneNumberAssignment { $null = New-TeamsRequest -TenantFilter $TenantFilter -Cmdlet 'Set-CsPhoneNumberAssignment' -CmdParams @{Identity = $Identity; PhoneNumber = $Request.Body.PhoneNumber; PhoneNumberType = $Request.Body.PhoneNumberType; ErrorAction = 'stop' } $Results = [pscustomobject]@{'Results' = "Successfully assigned $($Request.Body.PhoneNumber) to $($Identity)" } } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev Info + Write-LogMessage -Headers $Headers -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev Info $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ $Results = [pscustomobject]@{'Results' = $ErrorMessage.NormalizedError } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -tenant $($TenantFilter) -message $($Results.Results) -Sev Error -LogData $ErrorMessage $StatusCode = [HttpStatusCode]::Forbidden } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListSharepointSettings.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListSharepointSettings.ps1 index 2b04807cd4e1..5316c2cec66c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListSharepointSettings.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListSharepointSettings.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListSharepointSettings { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeams.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeams.ps1 index 743568fe8bed..82acc236796f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeams.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeams.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListTeams { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsLisLocation.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsLisLocation.ps1 index 198f83c4680a..d8b0f95656dd 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsLisLocation.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsLisLocation.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListTeamsLisLocation { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Query.TenantFilter try { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsVoice.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsVoice.ps1 index 5dd1c14a4ede..6e996b99c4fd 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsVoice.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Teams-Sharepoint/Invoke-ListTeamsVoice.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListTeamsVoice { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -24,31 +24,27 @@ Function Invoke-ListTeamsVoice { $users = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users?`$top=999&`$select=id,userPrincipalName,displayName" -tenantid $TenantFilter) $skip = 0 $GraphRequest = do { + Write-Host "Getting page $skip" $data = (New-TeamsAPIGetRequest -uri "https://api.interfaces.records.teams.microsoft.com/Skype.TelephoneNumberMgmt/Tenants/$($Tenantid)/telephone-numbers?skip=$($skip)&locale=en-US&top=999" -tenantid $TenantFilter).TelephoneNumbers | ForEach-Object { - try { - $CompleteRequest = $_ | Select-Object *, 'AssignedTo', 'AcquisitionDate' -ErrorAction SilentlyContinue - $CompleteRequest.AcquisitionDate = $CompleteRequest.AcquisitionDate -split 'T' | Select-Object -First 1 - } catch { - $CompleteRequest = $_ | Select-Object *, 'AssignedTo' -ErrorAction SilentlyContinue - } - - if ($CompleteRequest.TargetId -eq '00000000-0000-0000-0000-000000000000') { - $CompleteRequest.AssignedTo = 'Unassigned' - } else { - $CompleteRequest.AssignedTo = ($users | Where-Object -Property Id -EQ $CompleteRequest.TargetId).userPrincipalName - } + Write-Host 'Reached the loop' + $CompleteRequest = $_ | Select-Object *, @{Name = 'AssignedTo'; Expression = { $users | Where-Object -Property id -EQ $_.AssignedTo.id } } + $CompleteRequest.AcquisitionDate ? ($CompleteRequest.AcquisitionDate = $CompleteRequest.AcquisitionDate -split 'T' | Select-Object -First 1) : ($CompleteRequest | Add-Member -NotePropertyName 'AcquisitionDate' -NotePropertyValue 'Unknown' -Force) + $CompleteRequest.AssignedTo ? $null : ($CompleteRequest | Add-Member -NotePropertyName 'AssignedTo' -NotePropertyValue 'Unassigned' -Force) $CompleteRequest } + Write-Host 'Finished the loop' $skip = $skip + 999 $Data - } while ( $Data.count % 999 -eq 0 ) + } while ($data.Count -eq 999) + Write-Host 'Exiting the Do.' $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $StatusCode = [HttpStatusCode]::Forbidden $GraphRequest = $ErrorMessage } - # Associate values to output bindings by calling 'Push-OutputBinding'. + Write-Host "Graph request is: $($GraphRequest)" + Write-Host 'Returning the response' Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = $StatusCode Body = @($GraphRequest) diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-AddAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-AddAlert.ps1 index abbb442d17fa..c61665949c05 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-AddAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-AddAlert.ps1 @@ -9,8 +9,8 @@ Function Invoke-AddAlert { #> [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenants = $request.body.tenantFilter $Conditions = $request.body.conditions | ConvertTo-Json -Compress -Depth 10 | Out-String $TenantsJson = $Tenants | ConvertTo-Json -Compress -Depth 10 | Out-String diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAlertsQueue.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAlertsQueue.ps1 index fe7aaa7ebc88..460a36ad70a5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAlertsQueue.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAlertsQueue.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListAlertsQueue { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAuditLogs.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAuditLogs.ps1 index c70fdcb98bdb..9915eef063b7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAuditLogs.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListAuditLogs.ps1 @@ -9,7 +9,7 @@ function Invoke-ListAuditLogs { param($Request, $TriggerMetadata) $APIName = 'ListAuditLogs' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Query.TenantFilter $FilterConditions = [System.Collections.Generic.List[string]]::new() diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListWebhookAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListWebhookAlert.ps1 index 1741ed98fcaf..7511b8c4e408 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListWebhookAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-ListWebhookAlert.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListWebhookAlert { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = get-cipptable -TableName 'SchedulerConfig' $WebhookRow = foreach ($Webhook in Get-CIPPAzDataTableEntity @Table | Where-Object -Property PartitionKey -EQ 'WebhookAlert') { $Webhook.If = $Webhook.If | ConvertFrom-Json diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-RemoveQueuedAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-RemoveQueuedAlert.ps1 index f916f4436a04..2442dbcf934a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-RemoveQueuedAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Alerts/Invoke-RemoveQueuedAlert.ps1 @@ -10,8 +10,8 @@ Function Invoke-RemoveQueuedAlert { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($Request.query.EventType -eq 'Audit log Alert') { $Table = 'WebhookRules' @@ -25,11 +25,11 @@ Function Invoke-RemoveQueuedAlert { $Filter = "RowKey eq '{0}'" -f $ID $Alert = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $Alert - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed application queue for $ID." -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Removed application queue for $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed from queue.' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove from queue $ID. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to remove from queue $ID. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to remove alert from queue $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAddMultiTenantApp.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAddMultiTenantApp.ps1 index f614bee7290e..f7f661064f5c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAddMultiTenantApp.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAddMultiTenantApp.ps1 @@ -9,8 +9,8 @@ function Invoke-ExecAddMultiTenantApp { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $DelegateResources = $request.body.permissions | Where-Object -Property origin -EQ 'Delegated' | ForEach-Object { @{ id = $_.id; type = 'Scope' } } $DelegateResourceAccess = @{ ResourceAppId = '00000003-0000-0000-c000-000000000000'; resourceAccess = $DelegateResources } $ApplicationResources = $request.body.permissions | Where-Object -Property origin -EQ 'Application' | ForEach-Object { @{ id = $_.id; type = 'Role' } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppApproval.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppApproval.ps1 index b79ef41afb72..34ca07d3228a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppApproval.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppApproval.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAppApproval { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppPermissionTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppPermissionTemplate.ps1 index a095252512f4..1549381f3f50 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppPermissionTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Application Approval/Invoke-ExecAppPermissionTemplate.ps1 @@ -28,7 +28,7 @@ function Invoke-ExecAppPermissionTemplate { 'Results' = 'Template Saved' 'TemplateId' = $Entity.RowKey } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'ExecAppPermissionTemplate' -message "Permissions Saved for template: $($Request.Body.TemplateName)" -Sev 'Info' -LogData $Permissions + Write-LogMessage -headers $Request.Headers -API 'ExecAppPermissionTemplate' -message "Permissions Saved for template: $($Request.Body.TemplateName)" -Sev 'Info' -LogData $Permissions } catch { $Body = @{ 'Results' = $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecAddSPN.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecAddSPN.ps1 index b52867e7f0da..ce498176528c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecAddSPN.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecAddSPN.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAddSPN { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $Body = if ($Request.Query.Enable) { '{"accountEnabled":"true"}' } else { '{"accountEnabled":"false"}' } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOffboardTenant.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOffboardTenant.ps1 index c256f36c97e0..dc69176e989e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOffboardTenant.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOffboardTenant.ps1 @@ -9,10 +9,12 @@ Function Invoke-ExecOffboardTenant { #> [CmdletBinding()] param($Request, $TriggerMetadata) + $APIName = $Request.Params.CIPPEndpoint try { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantQuery = $Request.Body.TenantFilter.value ?? $Request.Body.TenantFilter + $Tenant = Get-Tenants -IncludeAll -TenantFilter $TenantQuery $TenantId = $Tenant.customerId $TenantFilter = $Tenant.defaultDomainName @@ -20,150 +22,157 @@ Function Invoke-ExecOffboardTenant { $results = [System.Collections.ArrayList]@() $errors = [System.Collections.ArrayList]@() - if ($request.body.RemoveCSPGuestUsers -eq $true) { - # Delete guest users who's domains match the CSP tenants - try { + if (!$Tenant) { + $results.Add('Tenant has already been offboarded') + } elseif ($TenantId -eq $env:TenantID) { + $errors.Add('You cannot offboard the CSP tenant') + } else { + if ($request.body.RemoveCSPGuestUsers -eq $true) { + # Delete guest users who's domains match the CSP tenants try { - $domains = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/domains?`$select=id" -tenantid $env:TenantID -NoAuthCheck:$true).id - $CSPGuestUsers = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/users?`$select=id,mail&`$filter=userType eq 'Guest' and $(($domains | ForEach-Object { "endswith(mail, '$_')" }) -join ' or ')&`$count=true" -tenantid $Tenantfilter -ComplexFilter) - } catch { - $errors.Add("Failed to retrieve guest users: $($_.Exception.message)") - } + try { + $domains = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/domains?`$select=id" -tenantid $env:TenantID -NoAuthCheck:$true).id + $DomainFilter = ($Domains | ForEach-Object { "endswith(mail, '$_')" }) -join ' or ' + $CSPGuestUsers = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/users?`$select=id,mail&`$filter=userType eq 'Guest' and ($DomainFilter)&`$count=true" -tenantid $Tenantfilter -ComplexFilter) + } catch { + $errors.Add("Failed to retrieve guest users: $($_.Exception.message)") + } - if ($CSPGuestUsers) { - [System.Collections.Generic.List[PSCustomObject]]$BulkRequests = @($CSPGuestUsers | ForEach-Object { - @{ - id = $($_.id) - method = 'DELETE' - url = "/users/$($_.id)" - } - }) - - $BulkResults = New-GraphBulkRequest -Requests $BulkRequests -tenantid $TenantFilter - - $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') + if ($CSPGuestUsers) { + [System.Collections.Generic.List[PSCustomObject]]$BulkRequests = @($CSPGuestUsers | ForEach-Object { + @{ + id = $($_.id) + method = 'DELETE' + url = "/users/$($_.id)" + } + }) + + $BulkResults = New-GraphBulkRequest -Requests $BulkRequests -tenantid $TenantFilter + + $results.Add('Successfully removed guest users') + Write-LogMessage -headers $Request.Headers -API $APIName -message 'CSP Guest users were removed' -Sev 'Info' -tenant $TenantFilter + } else { + $results.Add('No guest users found to remove') + } + } catch { + $errors.Add("Something went wrong while deleting guest users: $($_.Exception.message)") } - } catch { - $errors.Add("Something went wrong while deleting guest users: $($_.Exception.message)") } - } - if ($request.body.RemoveCSPnotificationContacts -eq $true) { - # Remove all email adresses that match the CSP tenants domains from the contact properties in /organization - try { + if ($request.body.RemoveCSPnotificationContacts -eq $true) { + # Remove all email adresses that match the CSP tenants domains from the contact properties in /organization try { - $domains = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/domains?`$select=id" -tenantid $env:TenantID -NoAuthCheck:$true).id - } catch { - throw "Failed to retrieve CSP domains: $($_.Exception.message)" - } + try { + $domains = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/domains?`$select=id" -tenantid $env:TenantID -NoAuthCheck:$true).id + } catch { + throw "Failed to retrieve CSP domains: $($_.Exception.message)" + } - try { - # Get /organization data - $orgContacts = New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/organization?`$select=id,marketingNotificationEmails,securityComplianceNotificationMails,technicalNotificationMails" -tenantid $TenantFilter + try { + # Get /organization data + $orgContacts = New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/organization?`$select=id,marketingNotificationEmails,securityComplianceNotificationMails,technicalNotificationMails" -tenantid $TenantFilter + } catch { + throw "Failed to retrieve CSP domains: $($_.Exception.message)" + } } catch { - throw "Failed to retrieve CSP domains: $($_.Exception.message)" + $errors.Add("$($_.Exception.message)") } - } catch { - $errors.Add("$($_.Exception.message)") - } - - # foreach through the properties we want to check/update - @('marketingNotificationEmails', 'securityComplianceNotificationMails', 'technicalNotificationMails') | ForEach-Object { - $property = $_ - $propertyContacts = $orgContacts.($($property)) - if ($propertyContacts -AND ($domains -notcontains ($propertyContacts | ForEach-Object { $_.Split('@')[1] }))) { - $newPropertyContent = [System.Collections.Generic.List[object]]($propertyContacts | Where-Object { $domains -notcontains $_.Split('@')[1] }) - - $patchContactBody = if (!($newPropertyContent)) { "{ `"$($property)`" : [] }" } else { [pscustomobject]@{ $property = $newPropertyContent } | ConvertTo-Json } + # foreach through the properties we want to check/update + @('marketingNotificationEmails', 'securityComplianceNotificationMails', 'technicalNotificationMails') | ForEach-Object { + $property = $_ + $propertyContacts = $orgContacts.($($property)) + + if ($propertyContacts -AND ($domains -notcontains ($propertyContacts | ForEach-Object { $_.Split('@')[1] }))) { + $newPropertyContent = [System.Collections.Generic.List[object]]($propertyContacts | Where-Object { $domains -notcontains $_.Split('@')[1] }) + + $patchContactBody = if (!($newPropertyContent)) { "{ `"$($property)`" : [] }" } else { [pscustomobject]@{ $property = $newPropertyContent } | ConvertTo-Json } + + try { + New-GraphPostRequest -type PATCH -body $patchContactBody -Uri "https://graph.microsoft.com/v1.0/organization/$($orgContacts.id)" -tenantid $Tenantfilter -ContentType 'application/json' + $results.Add("Successfully removed notification contacts from $($property): $(($propertyContacts | Where-Object { $domains -contains $_.Split('@')[1] }))") + Write-LogMessage -headers $Request.Headers -API $APIName -message "Contacts were removed from $($property)" -Sev 'Info' -tenant $TenantFilter + } catch { + $errors.Add("Failed to update property $($property): $($_.Exception.message)") + } + } else { + $results.Add("No notification contacts found in $($property)") + } + } + # Add logic for privacyProfile later - rvdwegen + } + $VendorApps = $Request.Body.vendorApplications + if ($VendorApps) { + $VendorApps | ForEach-Object { try { - New-GraphPostRequest -type PATCH -body $patchContactBody -Uri "https://graph.microsoft.com/v1.0/organization/$($orgContacts.id)" -tenantid $Tenantfilter -ContentType 'application/json' - $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 + $delete = (New-GraphPostRequest -type 'DELETE' -Uri "https://graph.microsoft.com/v1.0/serviceprincipals/$($_.value)" -tenantid $Tenantfilter) + $results.Add("Successfully removed app $($_.label)") + Write-LogMessage -headers $Request.Headers -API $APIName -message "App $($_.label) was removed" -Sev 'Info' -tenant $TenantFilter } catch { - $errors.Add("Failed to update property $($property): $($_.Exception.message)") + #$results.Add("Failed to removed app $($_.displayName)") + $errors.Add("Failed to removed app $($_.label)") } - } else { - $results.Add("No notification contacts found in $($property)") } } - # Add logic for privacyProfile later - rvdwegen - } - $VendorApps = $Request.Body.vendorApplications - if ($VendorApps) { - $VendorApps | ForEach-Object { + # All customer tenant specific actions ALWAYS have to be completed before this action! + if ($request.body.RemoveMultitenantCSPApps -eq $true) { + # Remove multi-tenant apps with the CSP tenant as origin try { - $delete = (New-GraphPostRequest -type 'DELETE' -Uri "https://graph.microsoft.com/v1.0/serviceprincipals/$($_.value)" -tenantid $Tenantfilter) - $results.Add("Successfully removed app $($_.label)") - Write-LogMessage -user $ExecutingUser -API $APIName -message "App $($_.label) was removed" -Sev 'Info' -tenant $TenantFilter + $multitenantCSPApps = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$count=true&`$select=displayName,appId,id,appOwnerOrganizationId&`$filter=appOwnerOrganizationId eq $($env:TenantID)" -tenantid $Tenantfilter -ComplexFilter) + $sortedArray = $multitenantCSPApps | Sort-Object @{Expression = { if ($_.appId -eq $ENV:ApplicationID) { 1 } else { 0 } }; Ascending = $true } + $sortedArray | ForEach-Object { + try { + $delete = (New-GraphPostRequest -type 'DELETE' -Uri "https://graph.microsoft.com/v1.0/serviceprincipals/$($_.id)" -tenantid $Tenantfilter) + $results.Add("Successfully removed app $($_.displayName)") + Write-LogMessage -headers $Request.Headers -API $APIName -message "App $($_.displayName) was removed" -Sev 'Info' -tenant $TenantFilter + } catch { + #$results.Add("Failed to removed app $($_.displayName)") + $errors.Add("Failed to removed app $($_.displayName)") + } + } } catch { - #$results.Add("Failed to removed app $($_.displayName)") - $errors.Add("Failed to removed app $($_.label)") + #$results.Add("Failed to retrieve multitenant apps, no apps have been removed: $($_.Exception.message)") + $errors.Add("Failed to retrieve multitenant CSP apps, no apps have been removed: $($_.Exception.message)") } } - } - - # All customer tenant specific actions ALWAYS have to be completed before this action! - if ($request.body.RemoveMultitenantCSPApps -eq $true) { - # Remove multi-tenant apps with the CSP tenant as origin - try { - $multitenantCSPApps = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$count=true&`$select=displayName,appId,id,appOwnerOrganizationId&`$filter=appOwnerOrganizationId eq $($env:TenantID)" -tenantid $Tenantfilter -ComplexFilter) - $sortedArray = $multitenantCSPApps | Sort-Object @{Expression = { if ($_.appId -eq $ENV:ApplicationID) { 1 } else { 0 } }; Ascending = $true } - $sortedArray | ForEach-Object { - try { - $delete = (New-GraphPostRequest -type 'DELETE' -Uri "https://graph.microsoft.com/v1.0/serviceprincipals/$($_.id)" -tenantid $Tenantfilter) - $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)") - $errors.Add("Failed to removed app $($_.displayName)") + $ClearCache = $false + if ($request.body.TerminateGDAP -eq $true) { + # Terminate GDAP relationships + $ClearCache = $true + try { + $delegatedAdminRelationships = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/tenantRelationships/delegatedAdminRelationships?`$filter=(status eq 'active') AND (customer/tenantId eq '$tenantid')" -tenantid $env:TenantID) + $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("Successfully terminated GDAP relationship $($_.displayName) from tenant $TenantFilter") + Write-LogMessage -headers $Request.Headers -API $APIName -message "GDAP Relationship $($_.displayName) has been terminated" -Sev 'Info' -tenant $TenantFilter + + } catch { + $($_.Exception.message) + #$results.Add("Failed to terminate GDAP relationship $($_.displayName): $($_.Exception.message)") + $errors.Add("Failed to terminate GDAP relationship $($_.displayName): $($_.Exception.message)") + } } + } catch { + $($_.Exception.message) + #$results.Add("Failed to retrieve GDAP relationships, no relationships have been terminated: $($_.Exception.message)") + $errors.Add("Failed to retrieve GDAP relationships, no relationships have been terminated: $($_.Exception.message)") } - } catch { - #$results.Add("Failed to retrieve multitenant apps, no apps have been removed: $($_.Exception.message)") - $errors.Add("Failed to retrieve multitenant CSP apps, no apps have been removed: $($_.Exception.message)") } - } - $ClearCache = $false - if ($request.body.TerminateGDAP -eq $true) { - # Terminate GDAP relationships - $ClearCache = $true - try { - $delegatedAdminRelationships = (New-GraphGETRequest -Uri "https://graph.microsoft.com/v1.0/tenantRelationships/delegatedAdminRelationships?`$filter=(status eq 'active') AND (customer/tenantId eq '$tenantid')" -tenantid $env:TenantID) - $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("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) - #$results.Add("Failed to terminate GDAP relationship $($_.displayName): $($_.Exception.message)") - $errors.Add("Failed to terminate GDAP relationship $($_.displayName): $($_.Exception.message)") - } + if ($request.body.TerminateContract -eq $true) { + # 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('Successfully terminated contract relationship') + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Contract relationship terminated' -Sev 'Info' -tenant $TenantFilter + } catch { + #$results.Add("Failed to terminate contract relationship: $($_.Exception.message)") + $errors.Add("Failed to terminate contract relationship: $($_.Exception.message)") } - } catch { - $($_.Exception.message) - #$results.Add("Failed to retrieve GDAP relationships, no relationships have been terminated: $($_.Exception.message)") - $errors.Add("Failed to retrieve GDAP relationships, no relationships have been terminated: $($_.Exception.message)") - } - } - - if ($request.body.TerminateContract -eq $true) { - # 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('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)") - $errors.Add("Failed to terminate contract relationship: $($_.Exception.message)") } } @@ -172,6 +181,7 @@ Function Invoke-ExecOffboardTenant { $Results.Add('Tenant cache has been cleared') } + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Offboarding completed' -Sev 'Info' -tenant $TenantFilter $StatusCode = [HttpStatusCode]::OK $body = [pscustomobject]@{ 'Results' = @($results) diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOnboardTenant.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOnboardTenant.ps1 index 70576362b561..ad61daf3ddd2 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOnboardTenant.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecOnboardTenant.ps1 @@ -10,7 +10,7 @@ function Invoke-ExecOnboardTenant { param($Request, $TriggerMetadata) $APIName = 'ExecOnboardTenant' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Id = $Request.Body.id if ($Id) { try { @@ -84,6 +84,7 @@ function Invoke-ExecOnboardTenant { Batch = @($Item) } $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5 -Compress) + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Onboarding job $Id started" -Sev 'Info' -LogData @{ 'InstanceId' = $InstanceId } } $Steps = $TenantOnboarding.OnboardingSteps | ConvertFrom-Json diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecUpdateSecureScore.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecUpdateSecureScore.ps1 index cef9df318e34..ec89669aefcc 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecUpdateSecureScore.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ExecUpdateSecureScore.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecUpdateSecureScore { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $Body = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ListAppConsentRequests.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ListAppConsentRequests.ps1 index 7e8a8603896d..55f5fdd82b76 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ListAppConsentRequests.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-ListAppConsentRequests.ps1 @@ -9,9 +9,9 @@ function Invoke-ListAppConsentRequests { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $TenantFilter = $Request.Query.TenantFilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { if ($Request.Query.TenantFilter -eq 'AllTenants') { @@ -50,7 +50,7 @@ function Invoke-ListAppConsentRequests { $StatusCode = [HttpStatusCode]::OK } catch { $StatusCode = [HttpStatusCode]::OK - Write-LogMessage -user $ExecutingUser -API $APIName -message 'app consent request list failed' -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -Headers $Headers -API $APIName -message 'app consent request list failed' -Sev 'Error' -tenant $TenantFilter $Results = @{ appDisplayName = "Error: $($_.Exception.Message)" } } @@ -58,4 +58,4 @@ function Invoke-ListAppConsentRequests { StatusCode = $StatusCode Body = @($Results) }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-SetAuthMethod.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-SetAuthMethod.ps1 index 2b00af589c58..26653bf43648 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-SetAuthMethod.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Invoke-SetAuthMethod.ps1 @@ -5,28 +5,23 @@ function Invoke-SetAuthMethod { .ROLE Tenant.Administration.ReadWrite #> - Param( - $Request, - $TriggerMetadata - ) + Param($Request, $TriggerMetadata) - $APIName = "Set Authentication Policy" - $state = if ($Request.Body.state -eq 'enabled') { $true } else { $false } - $Tenantfilter = $Request.Body.TenantFilter + $APIName = $Request.Params.CIPPEndpoint + $State = if ($Request.Body.state -eq 'enabled') { $true } else { $false } + $TenantFilter = $Request.Body.tenantFilter try { - Set-CIPPAuthenticationPolicy -Tenant $Tenantfilter -APIName $APIName -AuthenticationMethodId $($Request.Body.Id) -Enabled $state + $Result = Set-CIPPAuthenticationPolicy -Tenant $TenantFilter -APIName $APIName -AuthenticationMethodId $($Request.Body.Id) -Enabled $State -Headers $Request.Headers $StatusCode = [HttpStatusCode]::OK - $SuccessMessage = "Authentication Policy for $($Request.Body.Id) has been set to $state" } catch { - $ErrorMsg = Get-NormalizedError -message $($_.Exception.Message) - $SuccessMessage = "Function Error: $($_.InvocationInfo.ScriptLineNumber) - $ErrorMsg" - $StatusCode = [HttpStatusCode]::BadRequest + $Result = $_ + $StatusCode = [HttpStatusCode]::Forbidden } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = $StatusCode - Body = [pscustomobject]@{'Results' = "$SuccessMessage" } + Body = [pscustomobject]@{'Results' = "$Result" } }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenantDetails.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenantDetails.ps1 index 2b63da2523bd..b02f0f48d4e2 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenantDetails.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenantDetails.ps1 @@ -10,9 +10,9 @@ Function Invoke-ListTenantDetails { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $tenantfilter = $Request.Query.TenantFilter @@ -29,7 +29,7 @@ Function Invoke-ListTenantDetails { }) } catch { # Log the exception message - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Error: $($_.Exception.Message)" -Sev 'Error' # Respond with a 500 error and include the exception message in the response body Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenants.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenants.ps1 index 4227a6f78be8..1fd2fd8f97a8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenants.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Administration/Tenant/Invoke-ListTenants.ps1 @@ -10,9 +10,9 @@ Function Invoke-ListTenants { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint - Write-LogMessage -user $Request.Headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantAccess = Test-CIPPAccess -Request $Request -TenantList Write-Host "Tenant Access: $TenantAccess" @@ -92,9 +92,9 @@ Function Invoke-ListTenants { $body = $Tenants | Where-Object -Property defaultDomainName -EQ $Tenantfilter } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $Tenantfilter -API $APINAME -message 'Listed Tenant Details' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -tenant $Tenantfilter -API $APINAME -message 'Listed Tenant Details' -Sev 'Debug' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $Tenantfilter -API $APINAME -message "List Tenant failed. The error is: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -tenant $Tenantfilter -API $APINAME -message "List Tenant failed. The error is: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{ 'Results' = "Failed to retrieve tenants: $($_.Exception.Message)" defaultDomainName = '' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCAPolicy.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCAPolicy.ps1 index e1f21ae1e974..1b7b990ecb1a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCAPolicy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCAPolicy.ps1 @@ -10,20 +10,20 @@ Function Invoke-AddCAPolicy { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenants = $Request.body.tenantFilter.value if ('AllTenants' -in $Tenants) { $Tenants = (Get-Tenants).defaultDomainName } $results = foreach ($Tenant in $tenants) { try { - $CAPolicy = New-CIPPCAPolicy -replacePattern $Request.body.replacename -Overwrite $request.body.overwrite -TenantFilter $tenant -state $request.body.NewState -RawJSON $Request.body.RawJSON -APIName $APIName -ExecutingUser $request.headers.'x-ms-client-principal' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($Displayname)" -Sev 'Info' + $CAPolicy = New-CIPPCAPolicy -replacePattern $Request.body.replacename -Overwrite $request.body.overwrite -TenantFilter $tenant -state $request.body.NewState -RawJSON $Request.body.RawJSON -APIName $APIName -Headers $Request.Headers + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($Displayname)" -Sev 'Info' "Successfully added Conditional Access Policy for $($Tenant)" } catch { "Failed to add policy for $($Tenant): $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed to add Conditional Access Policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Failed to add Conditional Access Policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCATemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCATemplate.ps1 index ade9db4a3232..02200e39dc04 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCATemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddCATemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddCATemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Body.TenantFilter try { @@ -25,11 +25,11 @@ Function Invoke-AddCATemplate { PartitionKey = 'CATemplate' GUID = "$GUID" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created CA Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created CA Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create CA Template: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to create CA Template: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Intune Template Deployment failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddNamedLocation.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddNamedLocation.ps1 index bdf30b746d29..538599a246ac 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddNamedLocation.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-AddNamedLocation.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddNamedLocation { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -43,11 +43,11 @@ Function Invoke-AddNamedLocation { $Body = ConvertTo-Json -InputObject $ObjBody $GraphRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/namedLocations' -body $body -Type POST -tenantid $tenant "Successfully added Named Location for $($Tenant)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Added Named Location $($Displayname)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant -message "Added Named Location $($Displayname)" -Sev 'Info' } catch { "Failed to add Named Location $($Tenant): $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Failed adding Named Location$($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $tenant -message "Failed adding Named Location$($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' continue } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-EditCAPolicy.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-EditCAPolicy.ps1 index 56bdb6a64bea..1e8d5662663a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-EditCAPolicy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-EditCAPolicy.ps1 @@ -10,19 +10,19 @@ Function Invoke-EditCAPolicy { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenant = $request.query.tenantFilter $ID = $request.query.guid $results = try { $EditBody = "{`"state`": `"$($request.query.state)`"}" $Request = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta//identity/conditionalAccess/policies/$($id)" -tenantid $tenant -type PATCH -body $EditBody -asapp $true - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Edited CA policy: $($ID)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Edited CA policy: $($ID)" -Sev 'Info' "Successfully edited CA policy: $($ID)" } catch { "Failed to add CA policy: $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed editing CA policy $($ID). Error: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($Tenant) -message "Failed editing CA policy $($ID). Error: $($_.Exception.Message)" -Sev 'Error' } $body = [pscustomobject]@{'Results' = $results } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCACheck.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCACheck.ps1 index 9bdd61686269..04a138b3f97f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCACheck.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCACheck.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecCaCheck { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenant = $request.body.tenantFilter $UserID = $request.body.userId.value diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 index 0ee8ffc437db..003dd4e9a2b6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecCAExclusion { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' #If UserId is a guid, get the user's UPN if ($Request.body.UserId -match '^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$') { $Username = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($Request.body.UserId)" -tenantid $Request.body.TenantFilter).userPrincipalName @@ -41,7 +41,7 @@ Function Invoke-ExecCAExclusion { Add-CIPPScheduledTask -Task $TaskBody -hidden $false $body = @{ Results = "Successfully added vacation mode schedule for $Username." } } else { - Set-CIPPCAExclusion -TenantFilter $Request.body.TenantFilter -ExclusionType $Request.body.ExclusionType -UserID $Request.body.UserID -PolicyId $Request.body.PolicyId -executingUser $request.headers.'x-ms-client-principal' -UserName $Username + Set-CIPPCAExclusion -TenantFilter $Request.body.TenantFilter -ExclusionType $Request.body.ExclusionType -UserID $Request.body.UserID -PolicyId $Request.body.PolicyId -Headers $Request.Headers -UserName $Username } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecNamedLocation.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecNamedLocation.ps1 index 833586fb2298..8cd1f2341fd4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecNamedLocation.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecNamedLocation.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecNamedLocation { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -23,10 +23,10 @@ Function Invoke-ExecNamedLocation { $content = $Request.Body.input ?? $Request.Query.input try { - $results = Set-CIPPNamedLocation -NamedLocationId $NamedLocationId -TenantFilter $TenantFilter -change $change -content $content -ExecutingUser $request.headers.'x-ms-client-principal' + $results = Set-CIPPNamedLocation -NamedLocationId $NamedLocationId -TenantFilter $TenantFilter -change $change -content $content -Headers $Request.Headers } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -message "Failed to edit named location: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Request.Headers -API $APIName -message "Failed to edit named location: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage $results = "Failed to edit named location. Error: $($ErrorMessage.NormalizedError)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListCAtemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListCAtemplates.ps1 index 41cbaaa0b1ca..b76cb67f4d8c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListCAtemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListCAtemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListCAtemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicies.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicies.ps1 index 63d372e6c1c7..25b28cc46a09 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicies.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicies.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListConditionalAccessPolicies { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' function Get-LocationNameFromId { diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicyChanges.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicyChanges.ps1 index 22f708cfb080..b21fbe522b11 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicyChanges.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ListConditionalAccessPolicyChanges.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListConditionalAccessPolicyChanges { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -38,7 +38,7 @@ Function Invoke-ListConditionalAccessPolicyChanges { } catch { $StatusCode = [HttpStatusCode]::BadRequest Write-Host $($_.Exception.message) - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -message "Failed to request audit logs for policy $($policyDisplayName): $($_.Exception.message)" -Sev "Error" -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APIName -message "Failed to request audit logs for policy $($policyDisplayName): $($_.Exception.message)" -Sev "Error" -tenant $TenantFilter } # Associate values to output bindings by calling 'Push-OutputBinding'. @@ -46,4 +46,4 @@ Function Invoke-ListConditionalAccessPolicyChanges { StatusCode = $StatusCode Body = $changes }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecAddGDAPRole.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecAddGDAPRole.ps1 index 922357511af4..2b574a6e3c71 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecAddGDAPRole.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecAddGDAPRole.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecAddGDAPRole { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $CippDefaults = @( @{ label = 'Application Administrator'; value = '9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3' }, diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRelationship.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRelationship.ps1 index 2d0c88112d0b..18c1c6efdef4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRelationship.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRelationship.ps1 @@ -10,15 +10,15 @@ Function Invoke-ExecDeleteGDAPRelationship { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $GDAPID = $Request.Query.GDAPId ?? $Request.Body.GDAPId try { $DELETE = New-GraphPostRequest -NoAuthCheck $True -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships/$($GDAPID)/requests" -type POST -body '{"action":"terminate"}' -tenantid $env:TenantID $Results = [pscustomobject]@{'Results' = "Success. GDAP relationship for $($GDAPID) been revoked" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Success. GDAP relationship for $($GDAPID) been revoked" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Success. GDAP relationship for $($GDAPID) been revoked" -Sev 'Info' } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRoleMapping.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRoleMapping.ps1 index a2758b8e8341..e9bfe1645f10 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRoleMapping.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecDeleteGDAPRoleMapping.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecDeleteGDAPRoleMapping { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable -TableName 'GDAPRoles' $GroupId = $Request.Query.GroupId ?? $Request.Body.GroupId @@ -20,7 +20,7 @@ Function Invoke-ExecDeleteGDAPRoleMapping { $Entity = Get-CIPPAzDataTableEntity @Table -Filter $Filter Remove-AzDataTableEntity -Force @Table -Entity $Entity $Results = [pscustomobject]@{'Results' = 'Success. GDAP relationship mapping deleted' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "GDAP relationship mapping deleted for $($GroupId)" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "GDAP relationship mapping deleted for $($GroupId)" -Sev 'Info' } catch { $Results = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInvite.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInvite.ps1 index e46e64443e1e..04e76f5997d0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInvite.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInvite.ps1 @@ -10,7 +10,7 @@ Function Invoke-ExecGDAPInvite { param($Request, $TriggerMetadata) $APIName = 'ExecGDAPInvite' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $RoleMappings = $Request.Body.roleMappings @@ -77,12 +77,12 @@ Function Invoke-ExecGDAPInvite { $Message = 'Error creating GDAP relationship request' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created GDAP Invite - $InviteUrl" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created GDAP Invite - $InviteUrl" -Sev 'Info' } } catch { $Message = 'Error creating GDAP relationship, failed at step: ' + $Step Write-Host "GDAP ERROR: $($_.InvocationInfo.PositionMessage)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $env:TenantID -message "$($Message): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $env:TenantID -message "$($Message): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) } $body = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInviteApproved.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInviteApproved.ps1 index 7430ff9e1ce5..9472e030f0ff 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInviteApproved.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPInviteApproved.ps1 @@ -10,7 +10,7 @@ Function Invoke-ExecGDAPInviteApproved { [CmdletBinding()] param($Request, $TriggerMetadata) - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Set-CIPPGDAPInviteGroups diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPRemoveGArole.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPRemoveGArole.ps1 index 6a41ac39fb5f..37ad9b2022ae 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPRemoveGArole.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ExecGDAPRemoveGArole.ps1 @@ -27,7 +27,7 @@ Function Invoke-ExecGDAPRemoveGArole { New-GraphPOSTRequest -NoAuthCheck $True -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships/$($GDAPID)" -tenantid $env:TenantID -type PATCH -body $RawJSON -AddedHeaders $AddedHeader $Message = "Removed Global Administrator from $($GDAPID)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message $Message -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APINAME -message $Message -Sev 'Info' } else { if ($CheckActive.status -ne 'active') { $Message = "Relationship status is currently $($CheckActive.status), it is not possible to remove the Global Administrator role in this state." @@ -39,7 +39,7 @@ Function Invoke-ExecGDAPRemoveGArole { } catch { $Message = "Unexpected error patching GDAP relationship: $($_.Exception.Message)" Write-Host "GDAP ERROR: $($_.Exception.Message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $env:TenantID -message "$($Message): $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $env:TenantID -message "$($Message): $($_.Exception.Message)" -Sev 'Error' } $body = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPInvite.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPInvite.ps1 index 9242f8da2588..62fbb532c26c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPInvite.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPInvite.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListGDAPInvite { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPQueue.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPQueue.ps1 index d3110cadd8ad..f99e814e04a8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPQueue.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPQueue.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListGDAPQueue { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPRoles.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPRoles.ps1 index f39e16ebd1fc..61fb65f4b084 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPRoles.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/GDAP/Invoke-ListGDAPRoles.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListGDAPRoles { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsDeploy.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsDeploy.ps1 index 091d903054b7..edf89698769d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsDeploy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsDeploy.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddStandardsDeploy { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $user = $request.headers.'x-ms-client-principal' $username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($user)) | ConvertFrom-Json).userDetails @@ -48,11 +48,11 @@ Function Invoke-AddStandardsDeploy { RowKey = "$Tenant" PartitionKey = 'standards' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $tenant -API 'Standards' -message 'Successfully added standards deployment' -Sev 'Info' + Write-LogMessage -headers $Request.Headers -tenant $tenant -API 'Standards' -message 'Successfully added standards deployment' -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully added standards deployment' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'Standards' -message "Standards API failed. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API 'Standards' -message "Standards API failed. Error:$($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to add standard: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsTemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsTemplate.ps1 index a901e108b61b..a5e67feddfad 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsTemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-AddStandardsTemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddStandardsTemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $GUID = $Request.body.GUID ? $request.body.GUID : (New-Guid).GUID #updatedBy = $request.headers.'x-ms-client-principal' @@ -20,7 +20,7 @@ Function Invoke-AddStandardsTemplate { $request.body | Add-Member -NotePropertyName 'createdAt' -NotePropertyValue ($Request.body.createdAt ? $Request.body.createdAt : (Get-Date).ToUniversalTime()) -Force $Request.body | Add-Member -NotePropertyName 'updatedBy' -NotePropertyValue ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($request.headers.'x-ms-client-principal')) | ConvertFrom-Json).userDetails -Force $Request.body | Add-Member -NotePropertyName 'updatedAt' -NotePropertyValue (Get-Date).ToUniversalTime() -Force - $JSON = (ConvertTo-Json -Depth 100 -InputObject ($Request.body)) + $JSON = (ConvertTo-Json -Compress -Depth 100 -InputObject ($Request.body)) $Table = Get-CippTable -tablename 'templates' $Table.Force = $true Add-CIPPAzDataTableEntity @Table -Entity @{ @@ -30,7 +30,7 @@ Function Invoke-AddStandardsTemplate { GUID = "$GUID" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created CA Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created CA Template $($Request.body.name) with GUID $GUID" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template'; id = $GUID } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-BestPracticeAnalyser_List.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-BestPracticeAnalyser_List.ps1 index 5bf7c40a6741..fc5d25452c53 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-BestPracticeAnalyser_List.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-BestPracticeAnalyser_List.ps1 @@ -10,8 +10,8 @@ Function Invoke-BestPracticeAnalyser_List { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenants = Get-Tenants $Table = get-cipptable 'cachebpa' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ExecStandardsRun.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ExecStandardsRun.ps1 index 74c88643ce89..735a6f98d219 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ExecStandardsRun.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ExecStandardsRun.ps1 @@ -9,13 +9,19 @@ Function Invoke-ExecStandardsRun { #> [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $tenantfilter = if ($Request.Query.TenantFilter) { $Request.Query.TenantFilter } else { 'allTenants' } $TemplateId = if ($Request.Query.TemplateId) { $Request.Query.TemplateId } else { '*' } $Table = Get-CippTable -tablename 'templates' $Filter = "PartitionKey eq 'StandardsTemplateV2'" - $Templates = (Get-CIPPAzDataTableEntity @Table -Filter $Filter | Sort-Object TimeStamp).JSON | ConvertFrom-Json | Where-Object { + $Templates = (Get-CIPPAzDataTableEntity @Table -Filter $Filter | Sort-Object TimeStamp).JSON | ForEach-Object { + try { + ConvertFrom-Json $_ -ErrorAction SilentlyContinue + } catch { + + } + } | Where-Object { $_.guid -like $TemplateId } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPA.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPA.ps1 index 0df80f7d9f7a..65e7bd78bcf6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPA.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPA.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListBPA { [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 = $Request.Params.CIPPEndpoint + # Write-LogMessage -headers $Request.Headers -API $APINAME -message "Accessed this API" -Sev "Debug" $Table = get-cipptable 'cachebpav2' $name = $Request.query.Report diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPATemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPATemplates.ps1 index 376a1f4e592b..26d39d4773c9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPATemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListBPATemplates.ps1 @@ -10,11 +10,11 @@ Function Invoke-ListBPATemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' Write-Host 'PowerShell HTTP trigger function processed a request.' - + $Table = Get-CippTable -tablename 'templates' $Templates = Get-ChildItem 'Config\*.BPATemplate.json' | ForEach-Object { @@ -28,14 +28,15 @@ Function Invoke-ListBPATemplates { } $Filter = "PartitionKey eq 'BPATemplate'" - $Templates = (Get-CIPPAzDataTableEntity @Table -Filter $Filter).JSON | ConvertFrom-Json + $Templates = Get-CIPPAzDataTableEntity @Table -Filter $Filter if ($Request.Query.RawJson) { $Templates } else { $Templates = $Templates | ForEach-Object { - $Template = $_ + $Template = $_.JSON | ConvertFrom-Json @{ + GUID = $_.GUID Data = $Template.fields Name = $Template.Name Style = $Template.Style diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListDomainHealth.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListDomainHealth.ps1 index fb04e3d547ca..01e66c47bc9c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListDomainHealth.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-ListDomainHealth.ps1 @@ -34,11 +34,11 @@ Function Invoke-ListDomainHealth { } Set-DnsResolver -Resolver $Resolver - + #UNDOREPLACE $UserCreds = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($request.headers.'x-ms-client-principal')) | ConvertFrom-Json) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -143,7 +143,7 @@ Function Invoke-ListDomainHealth { } } } catch { - Write-LogMessage -API $APINAME -tenant $($name) -user $request.headers.'x-ms-client-principal' -message "DNS Helper API failed. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -API $APINAME -tenant $($name) -headers $Request.Headers -message "DNS Helper API failed. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" } $StatusCode = [HttpStatusCode]::InternalServerError } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-listStandardTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-listStandardTemplates.ps1 index ebf7a663e342..8864979ccfad 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-listStandardTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Standards/Invoke-listStandardTemplates.ps1 @@ -13,12 +13,13 @@ Function Invoke-listStandardTemplates { $Table = Get-CippTable -tablename 'templates' $Filter = "PartitionKey eq 'StandardsTemplateV2'" $Templates = (Get-CIPPAzDataTableEntity @Table -Filter $Filter) | ForEach-Object { - $JSON = $_.JSON + $JSON = $_.JSON -replace '"Action":', '"action":' try { $RowKey = $_.RowKey - $data = $_.JSON | ConvertFrom-Json -Depth 100 -ErrorAction SilentlyContinue + $data = $JSON | ConvertFrom-Json -Depth 100 -ErrorAction SilentlyContinue + } catch { - Write-Host "$($RowKey)" + Write-Host "$($RowKey) standard could not be loaded: $($_.Exception.Message)" return } $data | Add-Member -NotePropertyName 'GUID' -NotePropertyValue $_.GUID -Force diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-AddBPATemplate.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-AddBPATemplate.ps1 index 15c2d49afc0d..011839ad6364 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-AddBPATemplate.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-AddBPATemplate.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddBPATemplate { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { @@ -23,11 +23,11 @@ Function Invoke-AddBPATemplate { PartitionKey = 'BPATemplate' GUID = $Request.body.name } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created BPA named $($Request.body.name)" -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Created BPA named $($Request.body.name)" -Sev 'Debug' $body = [pscustomobject]@{'Results' = 'Successfully added template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "BPA Template Creation failed: $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "BPA Template Creation failed: $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "BPA Template Creation failed: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-ExecGraphExplorerPreset.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-ExecGraphExplorerPreset.ps1 index 5019a66c9725..f5d37d2bad3c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-ExecGraphExplorerPreset.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Tools/Invoke-ExecGraphExplorerPreset.ps1 @@ -10,9 +10,9 @@ Function Invoke-ExecGraphExplorerPreset { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' + #UNDOREPLACE $Username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($request.headers.'x-ms-client-principal')) | ConvertFrom-Json).userDetails # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ExecCommunityRepo.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ExecCommunityRepo.ps1 new file mode 100644 index 000000000000..d3ecd953afef --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ExecCommunityRepo.ps1 @@ -0,0 +1,204 @@ +function Invoke-ExecCommunityRepo { + <# + .SYNOPSIS + Make changes to a community repository + .DESCRIPTION + This function makes changes to a community repository in table storage + .FUNCTIONALITY + Entrypoint + .ROLE + CIPP.Core.ReadWrite + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $Action = $Request.Body.Action + $Id = $Request.Body.Id + if ($Request.Body.Id) { + $Filter = "PartitionKey eq 'CommunityRepos' and RowKey eq '$($Id)'" + } elseif ($Request.Body.FullName) { + $Filter = "PartitionKey eq 'CommunityRepos' and FullName eq '$($Request.Body.FullName)'" + } else { + $Results = @( + @{ + resultText = 'Id or FullName required' + state = 'error' + } + ) + $Body = @{ + Results = $Results + } + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $Body + }) + return + } + + $Table = Get-CIPPTable -TableName CommunityRepos + $RepoEntity = Get-CIPPAzDataTableEntity @Table -Filter $Filter + + switch ($Action) { + 'Add' { + $Repo = Invoke-GitHubApiRequest -Path "repositories/$($Id)" + $RepoEntity = @{ + PartitionKey = 'CommunityRepos' + RowKey = [string]$Repo.id + Name = [string]$Repo.name + Description = [string]$Repo.description + URL = [string]$Repo.html_url + FullName = [string]$Repo.full_name + Owner = [string]$Repo.owner.login + Visibility = [string]$Repo.visibility + WriteAccess = [bool]$Repo.permissions.push + DefaultBranch = [string]$Repo.default_branch + Permissions = [string]($Repo.permissions | ConvertTo-Json -Compress) + } + + Add-CIPPAzDataTableEntity @Table -Entity $RepoEntity -Force | Out-Null + + $Results = @{ + resultText = "Community repository '$($Repo.name)' added" + state = 'success' + } + } + 'Update' { + if ($RepoEntity) { + $Repo = Invoke-GitHubApiRequest -Path "repositories/$($Id)" + $Update = @{ + PartitionKey = 'CommunityRepos' + RowKey = [string]$Repo.id + Name = [string]$Repo.name + Description = [string]$Repo.description + URL = [string]$Repo.html_url + FullName = [string]$Repo.full_name + Owner = [string]$Repo.owner.login + Visibility = [string]$Repo.visibility + WriteAccess = [bool]$Repo.permissions.push + DefaultBranch = [string]$Repo.default_branch + Permissions = [string]($Repo.permissions | ConvertTo-Json -Compress) + ETag = $RepoEntity.ETag + } + + Update-CIPPAzDataTableEntity @Table -Entity $Update + + $Results = @{ + resultText = "Repository $($Repo.name) updated" + state = 'success' + } + } else { + $Results = @{ + resultText = "Repository $($Repo.name) not found" + state = 'error' + } + } + } + 'Delete' { + if ($RepoEntity) { + $Delete = $RepoEntity | Select-Object PartitionKey, RowKey, ETag + Remove-AzDataTableEntity @Table -Entity $Delete + } + $Results = @{ + resultText = "Repository $($RepoEntity.Name) deleted" + state = 'success' + } + } + 'UploadTemplate' { + $GUID = $Request.Body.GUID + $TemplateTable = Get-CIPPTable -TableName templates + $TemplateEntity = Get-CIPPAzDataTableEntity @TemplateTable -Filter "RowKey eq '$($GUID)'" + $Branch = $RepoEntity.UploadBranch ?? $RepoEntity.DefaultBranch + if ($TemplateEntity) { + $Template = $TemplateEntity.JSON | ConvertFrom-Json + $DisplayName = $Template.Displayname ?? $Template.templateName ?? $Template.name + if ($Template.tenantFilter) { + $Template.tenantFilter = @(@{ label = 'Template Tenant'; value = 'Template Tenant' }) + } + if ($Template.excludedTenants) { + $Template.excludedTenants = @() + } + $TemplateEntity.JSON = $Template | ConvertTo-Json -Compress -Depth 100 + + $Basename = $DisplayName -replace '\s', '_' -replace '[^\w\d_]', '' + $Path = '{0}/{1}.json' -f $TemplateEntity.PartitionKey, $Basename + $Results = Push-GitHubContent -FullName $Request.Body.FullName -Path $Path -Content ($TemplateEntity | ConvertTo-Json -Compress) -Message $Request.Body.Message -Branch $Branch + + $Results = @{ + resultText = "Template '$($DisplayName)' uploaded" + state = 'success' + } + } else { + $Results = @{ + resultText = "Template '$($GUID)' not found" + state = 'error' + } + } + } + 'SetBranch' { + if (!$RepoEntity) { + $Results = @{ + resultText = "Repository $($Id) not found" + state = 'error' + } + } else { + $Branch = $Request.Body.Branch + if (!$RepoEntity.UploadBranch) { + $RepoEntity | Add-Member -NotePropertyName 'UploadBranch' -NotePropertyValue $Branch + } else { + $RepoEntity.UploadBranch = $Branch + } + $null = Add-CIPPAzDataTableEntity @Table -Entity $RepoEntity -Force + + $Results = @{ + resultText = "Branch set to $Branch" + state = 'success' + } + } + } + 'ImportTemplate' { + $Path = $Request.Body.Path + $FullName = $Request.Body.FullName + $Branch = $Request.Body.Branch + try { + $Template = Get-GitHubFileContents -FullName $FullName -Path $Path -Branch $Branch + + $Content = $Template.content | ConvertFrom-Json + if ($Content.'@odata.type' -like '*conditionalAccessPolicy*') { + $Files = (Get-GitHubFileTree -FullName $FullName -Branch $Branch).tree | Where-Object { $_.path -match '.json$' -and $_.path -notmatch 'NativeImport' } | Select-Object *, @{n = 'html_url'; e = { "https://github.com/$($SplatParams.FullName)/tree/$($SplatParams.Branch)/$($_.path)" } }, @{n = 'name'; e = { ($_.path -split '/')[ -1 ] -replace '\.json$', '' } } + + $MigrationTable = $Files | Where-Object { $_.name -eq 'MigrationTable' } | Select-Object -Last 1 + if ($MigrationTable) { + Write-Host 'Found a migration table, getting contents' + $MigrationTable = (Get-GitHubFileContents -FullName $FullName -Branch $Branch -Path $MigrationTable.path).content | ConvertFrom-Json + } + } + Import-CommunityTemplate -Template $Content -SHA $Template.sha -MigrationTable $MigrationTable + $Results = @{ + resultText = 'Template imported' + state = 'success' + } + } catch { + $Results = @{ + resultText = "Error importing template: $($_.Exception.Message)" + state = 'error' + } + } + } + default { + $Results = @{ + resultText = "Action $Action not supported" + state = 'error' + } + } + } + + $Body = @{ + Results = @($Results) + } + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $Body + }) +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ExecGitHubAction.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ExecGitHubAction.ps1 new file mode 100644 index 000000000000..16e4ec6202b1 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ExecGitHubAction.ps1 @@ -0,0 +1,117 @@ +function Invoke-ExecGitHubAction { + <# + .SYNOPSIS + Invoke GitHub Action + .DESCRIPTION + Call GitHub API + .ROLE + CIPP.Extension.ReadWrite + .FUNCTIONALITY + Entrypoint + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $Action = $Request.Query.Action ?? $Request.Body.Action + + if ($Request.Query.Action) { + $Parameters = $Request.Query + } else { + $Parameters = $Request.Body + } + + $SplatParams = $Parameters | Select-Object -ExcludeProperty Action, TenantFilter | ConvertTo-Json | ConvertFrom-Json -AsHashtable + + $Table = Get-CIPPTable -TableName Extensionsconfig + $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json).GitHub + + if (!$Configuration.Enabled) { + $Response = Invoke-RestMethod -Uri 'https://cippy.azurewebsites.net/api/ExecGitHubAction' -Method POST -Body ($Action | ConvertTo-Json -Depth 10) -ContentType 'application/json' + $Results = $Response.Results + $Metadata = $Response.Metadata + } else { + switch ($Action) { + 'Search' { + $SearchResults = Search-GitHub @SplatParams + $Results = @($SearchResults.items) + $Metadata = $SearchResults | Select-Object -Property total_count, incomplete_results + } + 'GetFileContents' { + $Results = Get-GitHubFileContents @SplatParams + } + 'GetBranches' { + $Results = @(Get-GitHubBranch @SplatParams) + } + 'GetOrgs' { + try { + $Orgs = Invoke-GitHubApiRequest -Path 'user/orgs' + $Results = @($Orgs) + } catch { + $Results = @{ + resultText = 'You may not have permission to view organizations, check your PAT scopes and try again - {0}' -f $_.Exception.Message + state = 'error' + } + } + } + 'GetFileTree' { + $Files = (Get-GitHubFileTree @SplatParams).tree | Where-Object { $_.path -match '.json$' } | Select-Object *, @{n = 'html_url'; e = { "https://github.com/$($SplatParams.FullName)/tree/$($SplatParams.Branch)/$($_.path)" } } + $Results = @($Files) + } + 'ImportTemplate' { + $Results = Import-CommunityTemplate @SplatParams + } + 'CreateRepo' { + try { + Write-Information "Creating repository '$($SplatParams.Name)'" + $Repo = New-GitHubRepo @SplatParams + if ($Repo.id) { + $Table = Get-CIPPTable -TableName CommunityRepos + $RepoEntity = @{ + PartitionKey = 'CommunityRepos' + RowKey = [string]$Repo.id + Name = [string]($Repo.name -replace ' ', '-') + Description = [string]$Repo.description + URL = [string]$Repo.html_url + FullName = [string]$Repo.full_name + Owner = [string]$Repo.owner.login + Visibility = [string]$Repo.visibility + WriteAccess = [bool]$Repo.permissions.push + DefaultBranch = [string]$Repo.default_branch + Permissions = [string]($Repo.permissions | ConvertTo-Json -Compress) + } + Add-CIPPAzDataTableEntity @Table -Entity $RepoEntity -Force | Out-Null + + $Results = @{ + resultText = "Repository '$($Repo.name)' created" + state = 'success' + } + } + } catch { + Write-Information (Get-CippException -Exception $_ | ConvertTo-Json) + $Results = @{ + resultText = 'You may not have permission to create repositories, check your PAT scopes and try again - {0}' -f $_.Exception.Message + state = 'error' + } + } + } + default { + $Results = @{ + resultText = "Unknown action '$Action'" + state = 'error' + } + } + } + } + + $Body = @{ + Results = $Results + } + if ($Metadata) { + $Body.Metadata = $Metadata + } + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $Body + }) +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ListCommunityRepos.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ListCommunityRepos.ps1 new file mode 100644 index 000000000000..b1e33a877336 --- /dev/null +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tools/GitHub/Invoke-ListCommunityRepos.ps1 @@ -0,0 +1,80 @@ +function Invoke-ListCommunityRepos { + <# + .SYNOPSIS + List community repositories in Table Storage + .DESCRIPTION + This function lists community repositories in Table Storage + .FUNCTIONALITY + Entrypoint + .ROLE + CIPP.Core.Read + #> + [CmdletBinding()] + param($Request, $TriggerMetadata) + + $Table = Get-CIPPTable -TableName CommunityRepos + + if ($Request.Query.WriteAccess -eq 'true') { + $Filter = "PartitionKey eq 'CommunityRepos' and WriteAccess eq true" + } else { + $Filter = '' + } + + $Repos = Get-CIPPAzDataTableEntity @Table -Filter $Filter + + if (!$Request.Query.WriteAccess) { + $CIPPRoot = (Get-Item (Get-Module -Name CIPPCore).ModuleBase).Parent.Parent.FullName + $CommunityRepos = Join-Path -Path $CIPPRoot -ChildPath 'CommunityRepos.json' + $DefaultCommunityRepos = Get-Content -Path $CommunityRepos -Raw | ConvertFrom-Json + + $DefaultsMissing = $false + foreach ($Repo in $DefaultCommunityRepos) { + if ($Repos.Url -notcontains $Repo.Url) { + $Entity = [PSCustomObject]@{ + PartitionKey = 'CommunityRepos' + RowKey = $Repo.Id + Name = $Repo.Name + Description = $Repo.Description + URL = $Repo.URL + FullName = $Repo.FullName + Owner = $Repo.Owner + Visibility = $Repo.Visibility + WriteAccess = $Repo.WriteAccess + DefaultBranch = $Repo.DefaultBranch + UploadBranch = $Repo.DefaultBranch + Permissions = [string]($Repo.RepoPermissions | ConvertTo-Json) + } + Add-CIPPAzDataTableEntity @Table -Entity $Entity + $DefaultsMissing = $true + } + } + if ($DefaultsMissing) { + $Repos = Get-CIPPAzDataTableEntity @Table + } + } + + $Repos = $Repos | ForEach-Object { + [pscustomobject]@{ + Id = $_.RowKey + Name = $_.Name + Description = $_.Description + URL = $_.URL + FullName = $_.FullName + Owner = $_.Owner + Visibility = $_.Visibility + WriteAccess = $_.WriteAccess + DefaultBranch = $_.DefaultBranch + UploadBranch = $_.UploadBranch ?? $_.DefaultBranch + RepoPermissions = $_.Permissions | ConvertFrom-Json + } + } + + $Body = @{ + Results = @($Repos | Sort-Object -Property FullName) + } + + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = $Body + }) +} diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-AddTenantAllowBlockList.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-AddTenantAllowBlockList.ps1 index ff1464ea8e3b..9f19cacea091 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-AddTenantAllowBlockList.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-AddTenantAllowBlockList.ps1 @@ -10,8 +10,8 @@ Function Invoke-AddTenantAllowBlockList { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Accessed this API' -Sev 'Debug' $blocklistobj = $Request.body if ($Request.body.tenantId -eq 'AllTenants') { $Tenants = (Get-Tenants).defaultDomainName } else { $Tenants = @($Request.body.tenantId) } @@ -38,11 +38,11 @@ Function Invoke-AddTenantAllowBlockList { New-ExoRequest @ExoRequest $results.add("Successfully added $($blocklistobj.Entries) as type $($blocklistobj.ListType) to the $($blocklistobj.listMethod) list for $tenant") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $Tenant -message $result -Sev 'Info' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $Tenant -message $result -Sev 'Info' } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message $results.add("Failed to create blocklist. Error: $ErrorMessage") - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $Tenant -message $result -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $Tenant -message $result -Sev 'Error' } } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecBreachSearch.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecBreachSearch.ps1 index 5babb8345a72..efc70b91833f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecBreachSearch.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecBreachSearch.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecBreachSearch { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.query.TenantFilter #Move to background job New-BreachTenantSearch -TenantFilter $TenantFilter diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecCSPLicense.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecCSPLicense.ps1 index 3b2a14e1e100..c701bd475f40 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecCSPLicense.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecCSPLicense.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecCSPLicense { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecListAppId.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecListAppId.ps1 index c8fc8085e27e..9036b16620b4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecListAppId.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecListAppId.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecListAppId { [CmdletBinding()] param($Request, $TriggerMetadata) Get-CIPPAuthentication - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ResponseURL = "$(($Request.headers.'x-ms-original-url').replace('/api/ExecListAppId','/api/ExecSAMSetup'))" $Results = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecRestoreDeleted.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecRestoreDeleted.ps1 index 403e4e3dcdfa..3547e651798d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecRestoreDeleted.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecRestoreDeleted.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecRestoreDeleted { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSendOrgMessage.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSendOrgMessage.ps1 index e5293d373605..ca89e41bd579 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSendOrgMessage.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSendOrgMessage.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecSendOrgMessage { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSyncAPDevices.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSyncAPDevices.ps1 index 40b0a18263e2..d29c24ce8bc6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSyncAPDevices.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecSyncAPDevices.ps1 @@ -9,20 +9,20 @@ Function Invoke-ExecSyncAPDevices { #> [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $request.headers.'x-ms-client-principal' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers $TenantFilter = $Request.Body.tenantFilter ?? $Request.Query.tenantFilter - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev Debug + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev Debug try { $null = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotSettings/sync' -tenantid $TenantFilter $Results = "Successfully Started Sync for $($TenantFilter)" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message 'Successfully started Autopilot sync' -Sev Info + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantFilter -message 'Successfully started Autopilot sync' -Sev Info $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ $Results = "Failed to start sync for $TenantFilter. Did you try syncing in the last 10 minutes?" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message 'Failed to start Autopilot sync. Did you try syncing in the last 10 minutes?' -Sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -tenant $TenantFilter -message 'Failed to start Autopilot sync. Did you try syncing in the last 10 minutes?' -Sev Error -LogData $ErrorMessage $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUniversalSearch.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUniversalSearch.ps1 index e5d18b453a87..e07781beb7f2 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUniversalSearch.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUniversalSearch.ps1 @@ -10,8 +10,8 @@ Function Invoke-ExecUniversalSearch { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUserSettings.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUserSettings.ps1 index ec1381e24e45..82d1cb25041a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUserSettings.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecUserSettings.ps1 @@ -9,8 +9,8 @@ function Invoke-ExecUserSettings { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { $object = $request.body.currentSettings | Select-Object * -ExcludeProperty CurrentTenant, pageSizes, sidebarShow, sidebarUnfoldable, _persist | ConvertTo-Json -Compress -Depth 10 @@ -34,4 +34,4 @@ function Invoke-ExecUserSettings { Body = @($Results) }) -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAllTenantDeviceCompliance.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAllTenantDeviceCompliance.ps1 index 31c3e5dd4675..2db62cf8e0c3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAllTenantDeviceCompliance.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAllTenantDeviceCompliance.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListAllTenantDeviceCompliance { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAppStatus.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAppStatus.ps1 index 93a95f880983..10e0590e24c1 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAppStatus.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAppStatus.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListAppStatus { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAutopilotconfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAutopilotconfig.ps1 index 1b4c8f4a1440..a4832e59e1c3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAutopilotconfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAutopilotconfig.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListAutopilotconfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAzureADConnectStatus.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAzureADConnectStatus.ps1 index bd9a6bbd815b..53d468609e5c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAzureADConnectStatus.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListAzureADConnectStatus.ps1 @@ -10,10 +10,10 @@ Function Invoke-ListAzureADConnectStatus { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers $TenantFilter = $Request.Query.TenantFilter - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $DataToReturn = $Request.Query.DataToReturn diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListBreachesAccount.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListBreachesAccount.ps1 index 827a151ded72..4c9f894b3c4e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListBreachesAccount.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListBreachesAccount.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListBreachesAccount { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($request.query.account -like '*@*') { $Results = Get-HIBPRequest "breachedaccount/$($Request.query.account)?truncateResponse=false" diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPLicenses.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPLicenses.ps1 index 4a6959e2b5fc..ecbaecfc54df 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPLicenses.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPLicenses.ps1 @@ -10,14 +10,20 @@ Function Invoke-ListCSPLicenses { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $GraphRequest = Get-SherwebCurrentSubscription -TenantFilter $Request.Query.TenantFilter - - Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK - Body = @($GraphRequest) - }) -Clobber + try { + $GraphRequest = Get-SherwebCurrentSubscription -TenantFilter $Request.Query.TenantFilter + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::OK + Body = @($GraphRequest) + }) -Clobber + } catch { + Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ + StatusCode = [HttpStatusCode]::BadRequest + Body = 'Unable to retrieve CSP licenses, ensure that you have enabled the Sherweb integration and mapped the tenant in the integration settings.' + }) -Clobber + } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPsku.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPsku.ps1 index 07f4ca8897eb..4782121321b5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPsku.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCSPsku.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListCSPsku { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($Request.Query.currentSkuOnly) { $GraphRequest = Get-SherwebCurrentSubscription -TenantFilter $Request.Query.TenantFilter diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCalendarPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCalendarPermissions.ps1 index fbbe6c93bdd2..a4640809048f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCalendarPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListCalendarPermissions.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListCalendarPermissions { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $UserID = $request.Query.UserID $Tenantfilter = $request.Query.tenantfilter diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListContacts.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListContacts.ps1 index 882b546fe579..6fb5562635a4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListContacts.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListContacts.ps1 @@ -10,35 +10,62 @@ Function Invoke-ListContacts { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $selectlist = 'id', 'companyName', 'displayName', 'mail', 'onPremisesSyncEnabled', 'editURL', "givenName", "jobTitle", "surname", "addresses", "phones" + # Define fields to retrieve + $selectList = @( + 'id', + 'companyName', + 'displayName', + 'mail', + 'onPremisesSyncEnabled', + 'editURL', + 'givenName', + 'jobTitle', + 'surname', + 'addresses', + 'phones' + ) - # Write to the Azure Functions log stream. - Write-Host 'PowerShell HTTP trigger function processed a request.' + # Get query parameters + $TenantFilter = $Request.Query.tenantFilter + $ContactID = $Request.Query.id + # Validate required parameters + if (-not $TenantFilter) { + $StatusCode = [HttpStatusCode]::BadRequest + $GraphRequest = 'tenantFilter is required' + Write-Host 'Error: Missing tenantFilter parameter' + } else { + try { + # Construct Graph API URI based on whether an ID is provided + $graphUri = if ([string]::IsNullOrWhiteSpace($ContactID) -eq $false) { + "https://graph.microsoft.com/beta/contacts/$($ContactID)?`$select=$($selectList -join ',')" + } else { + "https://graph.microsoft.com/beta/contacts?`$top=999&`$select=$($selectList -join ',')" + } - # Interact with query parameters or the body of the request. - $TenantFilter = $Request.Query.TenantFilter - $ContactID = $Request.Query.ContactID + # Make the Graph API request + $GraphRequest = New-GraphGetRequest -uri $graphUri -tenantid $TenantFilter - Write-Host "Tenant Filter: $TenantFilter" - Write-Host "This is the Contact ID: $ContactID" - try { - $GraphRequest = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/contacts/$($ContactID)?`$top=999&`$select=$($selectlist -join ',')" -tenantid $TenantFilter | Select-Object $selectlist | ForEach-Object { - $_.editURL = "https://outlook.office365.com/ecp/@$TenantFilter/UsersGroups/EditContact.aspx?exsvurl=1&realm=$($env:TenantID)&mkt=en-US&id=$($_.id)" - $_ + if ([string]::IsNullOrWhiteSpace($ContactID) -eq $false) { + $HiddenFromGAL = New-EXORequest -tenantid $TenantFilter -cmdlet 'Get-Recipient' -cmdParams @{RecipientTypeDetails = 'MailContact' } -Select 'HiddenFromAddressListsEnabled,ExternalDirectoryObjectId' | Where-Object { $_.ExternalDirectoryObjectId -eq $ContactID } + $GraphRequest | Add-Member -NotePropertyName 'hidefromGAL' -NotePropertyValue $HiddenFromGAL.HiddenFromAddressListsEnabled + } + # Ensure single result when ID is provided + if ($ContactID -and $GraphRequest -is [array]) { + $GraphRequest = $GraphRequest | Select-Object -First 1 + } + $StatusCode = [HttpStatusCode]::OK + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + $StatusCode = [HttpStatusCode]::InternalServerError + $GraphRequest = $ErrorMessage } - $StatusCode = [HttpStatusCode]::OK - } catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - $StatusCode = [HttpStatusCode]::Forbidden - $GraphRequest = $ErrorMessage } + + # Return response Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = $StatusCode - Body = @($GraphRequest | Where-Object -Property id -NE $null) + Body = @($GraphRequest | Where-Object { $null -ne $_.id }) }) - } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderState.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderState.ps1 index fdd9388d3d79..fb4efd4a5906 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderState.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderState.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListDefenderState { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $StatusCode = [HttpStatusCode]::OK # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderTVM.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderTVM.ps1 index e61191283062..d699ab7fbb10 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderTVM.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDefenderTVM.ps1 @@ -10,10 +10,10 @@ Function Invoke-ListDefenderTVM { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $TenantFilter = $Request.Query.tenantFilter - $ExecutingUser = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeletedItems.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeletedItems.ps1 index cb763699e04c..b9dbdfb4da4f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeletedItems.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeletedItems.ps1 @@ -10,10 +10,10 @@ Function Invoke-ListDeletedItems { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $TenantFilter = $Request.Query.tenantFilter - $ExecutingUser = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $Types = 'Application', 'User', 'Device', 'Group' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeviceDetails.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeviceDetails.ps1 index 1d561c958f65..2e1aa667bd40 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeviceDetails.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDeviceDetails.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListDeviceDetails { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDomains.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDomains.ps1 index ccc23f75aad7..14b225267ec7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDomains.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListDomains.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListDomains { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExConnectorTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExConnectorTemplates.ps1 index 7fbe2e3ab83c..d16a08c73c98 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExConnectorTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExConnectorTemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListExConnectorTemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CippTable -tablename 'templates' #List new policies diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExchangeConnectors.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExchangeConnectors.ps1 index 95120eab6ac6..9fa161d38f72 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExchangeConnectors.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExchangeConnectors.ps1 @@ -10,13 +10,14 @@ Function Invoke-ListExchangeConnectors { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $Tenantfilter = $request.Query.tenantfilter + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $TenantFilter = $request.Query.tenantFilter $Results = try { - New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Get-OutboundConnector' | Select-Object *, @{n = 'cippconnectortype'; e = { 'outbound' } } - New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Get-InboundConnector' | Select-Object *, @{n = 'cippconnectortype'; e = { 'Inbound' } } + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-OutboundConnector' | Select-Object *, @{n = 'cippconnectortype'; e = { 'outbound' } } + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-InboundConnector' | Select-Object *, @{n = 'cippconnectortype'; e = { 'Inbound' } } $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExtensionsConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExtensionsConfig.ps1 index e2feff0542d7..008ae6398f9e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExtensionsConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExtensionsConfig.ps1 @@ -10,13 +10,27 @@ Function Invoke-ListExtensionsConfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable -TableName Extensionsconfig try { $Body = (Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json -Depth 10 -ErrorAction Stop + if ($Body.HaloPSA.TicketType -and !$Body.HaloPSA.TicketType.value) { + # translate ticket type to autocomplete format + Write-Information "Ticket Type: $($Body.HaloPSA.TicketType)" + $Types = Get-HaloTicketType + $Type = $Types | Where-Object { $_.id -eq $Body.HaloPSA.TicketType } + #Write-Information ($Type | ConvertTo-Json) + if ($Type) { + $Body.HaloPSA.TicketType = @{ + label = $Type.name + value = $Type.id + } + } + } } catch { + Write-Information (Get-CippException -Exception $_ | ConvertTo-Json) $Body = @{} } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExternalTenantInfo.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExternalTenantInfo.ps1 index f5c773792ce2..bb37f00360f8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExternalTenantInfo.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListExternalTenantInfo.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListExternalTenantInfo { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionParameters.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionParameters.ps1 index 4f70f3c53929..a79dd3782dd0 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionParameters.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionParameters.ps1 @@ -9,11 +9,8 @@ function Invoke-ListFunctionParameters { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - - # Write to the Azure Functions log stream. - Write-Information 'PowerShell HTTP trigger function processed a request.' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $Module = $Request.Query.Module @@ -27,7 +24,7 @@ function Invoke-ListFunctionParameters { $CommandQuery.Name = $Function } $IgnoreList = 'entryPoint', 'internal' - $CommonParameters = @('Verbose', 'Debug', 'ErrorAction', 'WarningAction', 'InformationAction', 'ErrorVariable', 'WarningVariable', 'InformationVariable', 'OutVariable', 'OutBuffer', 'PipelineVariable', 'TenantFilter', 'APIName', 'ExecutingUser', 'ProgressAction', 'WhatIf', 'Confirm') + $CommonParameters = @('Verbose', 'Debug', 'ErrorAction', 'WarningAction', 'InformationAction', 'ErrorVariable', 'WarningVariable', 'InformationVariable', 'OutVariable', 'OutBuffer', 'PipelineVariable', 'TenantFilter', 'APIName', 'Headers', 'ProgressAction', 'WhatIf', 'Confirm', 'Headers', 'NoAuthCheck') $TemporaryBlacklist = 'Get-CIPPAuthentication', 'Invoke-CippWebhookProcessing', 'Invoke-ListFunctionParameters', 'New-CIPPAPIConfig', 'New-CIPPGraphSubscription' try { if ($Module -eq 'ExchangeOnlineManagement') { @@ -40,7 +37,7 @@ function Invoke-ListFunctionParameters { $ExoRequest.Compliance = $true } $Functions = New-ExoRequest @ExoRequest - Write-Host $Functions + #Write-Host $Functions } else { $Functions = Get-Command @CommandQuery | Where-Object { $_.Visibility -eq 'Public' } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionStats.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionStats.ps1 index 037801e25962..26c014d0c8d5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionStats.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListFunctionStats.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListFunctionStats { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGenericTestFunction.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGenericTestFunction.ps1 index 8cfed503e5cb..cea9da93182e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGenericTestFunction.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGenericTestFunction.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListGenericTestFunction { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $graphRequest = ($request.headers.'x-ms-original-url').split('/api') | Select-Object -First 1 Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGraphExplorerPresets.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGraphExplorerPresets.ps1 index e023ee91f0be..86153e7e1fc9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGraphExplorerPresets.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGraphExplorerPresets.ps1 @@ -10,9 +10,9 @@ Function Invoke-ListGraphExplorerPresets { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $Username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($request.headers.'x-ms-client-principal')) | ConvertFrom-Json).userDetails + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $Username = $Request.Headers['x-ms-client-principal-name'] try { $Table = Get-CIPPTable -TableName 'GraphPresets' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroupTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroupTemplates.ps1 index 6a6bc6b12248..7d5d7c38cdad 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroupTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroupTemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListGroupTemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroups.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroups.ps1 index 00d3d8eb9606..da1c6c362f6c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroups.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListGroups.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListGroups { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Query.TenantFilter $selectstring = "id,createdDateTime,displayName,description,mail,mailEnabled,mailNickname,resourceProvisioningOptions,securityEnabled,visibility,organizationId,onPremisesSamAccountName,membershipRule,grouptypes,onPremisesSyncEnabled,resourceProvisioningOptions,userPrincipalName&`$expand=members(`$select=userPrincipalName)" diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListHaloClients.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListHaloClients.ps1 index e00ba611aa67..3d9397b985e4 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListHaloClients.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListHaloClients.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListHaloClients { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListInactiveAccounts.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListInactiveAccounts.ps1 index 5a36bb089ff0..a880849cafe5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListInactiveAccounts.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListInactiveAccounts.ps1 @@ -10,9 +10,9 @@ Function Invoke-ListInactiveAccounts { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneIntents.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneIntents.ps1 index b7043311731c..6e9d14f81319 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneIntents.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneIntents.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListIntuneIntents { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntunePolicy.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntunePolicy.ps1 index c2ad60650959..d8febbcf029b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntunePolicy.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntunePolicy.ps1 @@ -9,8 +9,9 @@ Function Invoke-ListIntunePolicy { [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 = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -Headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. @@ -19,12 +20,12 @@ Function Invoke-ListIntunePolicy { # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter $id = $Request.Query.ID - $urlname = $Request.Query.URLName + $URLName = $Request.Query.URLName try { if ($ID) { - $GraphRequest = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$($urlname)('$ID')" -tenantid $tenantfilter + $GraphRequest = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$($URLName)('$ID')" -tenantid $TenantFilter } else { - $Groups = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/groups?$top=999' -tenantid $tenantfilter | Select-Object -Property id, displayName + $Groups = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/groups?$top=999' -tenantid $TenantFilter | Select-Object -Property id, displayName $BulkRequests = [PSCustomObject]@( @{ @@ -57,49 +58,52 @@ Function Invoke-ListIntunePolicy { $BulkResults = New-GraphBulkRequest -Requests $BulkRequests -tenantid $TenantFilter $GraphRequest = $BulkResults | ForEach-Object { - $URLName = $_.Id - $_.body.Value | ForEach-Object { - $policyTypeName = switch -Wildcard ($_.'assignments@odata.context') { - '*microsoft.graph.windowsIdentityProtectionConfiguration*' { 'Identity Protection' } - '*microsoft.graph.windows10EndpointProtectionConfiguration*' { 'Endpoint Protection' } - '*microsoft.graph.windows10CustomConfiguration*' { 'Custom' } - '*microsoft.graph.windows10DeviceFirmwareConfigurationInterface*' { 'Firmware Configuration' } - '*groupPolicyConfigurations*' { 'Administrative Templates' } - '*windowsDomainJoinConfiguration*' { 'Domain Join configuration' } - '*windowsUpdateForBusinessConfiguration*' { 'Update Configuration' } - '*windowsHealthMonitoringConfiguration*' { 'Health Monitoring' } - '*microsoft.graph.macOSGeneralDeviceConfiguration*' { 'MacOS Configuration' } - '*microsoft.graph.macOSEndpointProtectionConfiguration*' { 'MacOS Endpoint Protection' } - '*microsoft.graph.androidWorkProfileGeneralDeviceConfiguration*' { 'Android Configuration' } - default { $_.'assignments@odata.context' } - } - $Assignments = $_.assignments.target | Select-Object -Property '@odata.type', groupId - $PolicyAssignment = [System.Collections.Generic.List[string]]::new() - $PolicyExclude = [System.Collections.Generic.List[string]]::new() - ForEach ($target in $Assignments) { - switch ($target.'@odata.type') { - '#microsoft.graph.allDevicesAssignmentTarget' { $PolicyAssignment.Add('All Devices') } - '#microsoft.graph.exclusionallDevicesAssignmentTarget' { $PolicyExclude.Add('All Devices') } - '#microsoft.graph.allUsersAssignmentTarget' { $PolicyAssignment.Add('All Users') } - '#microsoft.graph.allLicensedUsersAssignmentTarget' { $PolicyAssignment.Add('All Licenced Users') } - '#microsoft.graph.exclusionallUsersAssignmentTarget' { $PolicyExclude.Add('All Users') } - '#microsoft.graph.groupAssignmentTarget' { $PolicyAssignment.Add($Groups.Where({ $_.id -eq $target.groupId }).displayName) } - '#microsoft.graph.exclusionGroupAssignmentTarget' { $PolicyExclude.Add($Groups.Where({ $_.id -eq $target.groupId }).displayName) } - default { - $PolicyAssignment.Add($null) - $PolicyExclude.Add($null) + $URLName = $_.Id + $_.body.Value | ForEach-Object { + $policyTypeName = switch -Wildcard ($_.'assignments@odata.context') { + '*microsoft.graph.windowsIdentityProtectionConfiguration*' { 'Identity Protection' } + '*microsoft.graph.windows10EndpointProtectionConfiguration*' { 'Endpoint Protection' } + '*microsoft.graph.windows10CustomConfiguration*' { 'Custom' } + '*microsoft.graph.windows10DeviceFirmwareConfigurationInterface*' { 'Firmware Configuration' } + '*groupPolicyConfigurations*' { 'Administrative Templates' } + '*windowsDomainJoinConfiguration*' { 'Domain Join configuration' } + '*windowsUpdateForBusinessConfiguration*' { 'Update Configuration' } + '*windowsHealthMonitoringConfiguration*' { 'Health Monitoring' } + '*microsoft.graph.macOSGeneralDeviceConfiguration*' { 'MacOS Configuration' } + '*microsoft.graph.macOSEndpointProtectionConfiguration*' { 'MacOS Endpoint Protection' } + '*microsoft.graph.androidWorkProfileGeneralDeviceConfiguration*' { 'Android Configuration' } + default { $_.'assignments@odata.context' } + } + $Assignments = $_.assignments.target | Select-Object -Property '@odata.type', groupId + $PolicyAssignment = [System.Collections.Generic.List[string]]::new() + $PolicyExclude = [System.Collections.Generic.List[string]]::new() + ForEach ($target in $Assignments) { + switch ($target.'@odata.type') { + '#microsoft.graph.allDevicesAssignmentTarget' { $PolicyAssignment.Add('All Devices') } + '#microsoft.graph.exclusionallDevicesAssignmentTarget' { $PolicyExclude.Add('All Devices') } + '#microsoft.graph.allUsersAssignmentTarget' { $PolicyAssignment.Add('All Users') } + '#microsoft.graph.allLicensedUsersAssignmentTarget' { $PolicyAssignment.Add('All Licenced Users') } + '#microsoft.graph.exclusionallUsersAssignmentTarget' { $PolicyExclude.Add('All Users') } + '#microsoft.graph.groupAssignmentTarget' { $PolicyAssignment.Add($Groups.Where({ $_.id -eq $target.groupId }).displayName) } + '#microsoft.graph.exclusionGroupAssignmentTarget' { $PolicyExclude.Add($Groups.Where({ $_.id -eq $target.groupId }).displayName) } + default { + $PolicyAssignment.Add($null) + $PolicyExclude.Add($null) + } } } - } - if ($_.displayname -eq $null) { $_ | Add-Member -NotePropertyName displayName -NotePropertyValue $_.name } - $_ | Add-Member -NotePropertyName PolicyTypeName -NotePropertyValue $policyTypeName - $_ | Add-Member -NotePropertyName URLName -NotePropertyValue $URLName - $_ | Add-Member -NotePropertyName PolicyAssignment -NotePropertyValue ($PolicyAssignment -join ', ') - $_ | Add-Member -NotePropertyName PolicyExclude -NotePropertyValue ($PolicyExclude -join ', ') - $_ - } | Where-Object { $_.DisplayName -ne $null } - } + if ($null -eq $_.displayname) { $_ | Add-Member -NotePropertyName displayName -NotePropertyValue $_.name } + $_ | Add-Member -NotePropertyName PolicyTypeName -NotePropertyValue $policyTypeName + $_ | Add-Member -NotePropertyName URLName -NotePropertyValue $URLName + $_ | Add-Member -NotePropertyName PolicyAssignment -NotePropertyValue ($PolicyAssignment -join ', ') + $_ | Add-Member -NotePropertyName PolicyExclude -NotePropertyValue ($PolicyExclude -join ', ') + $_ + } | Where-Object { $null -ne $_.DisplayName } + } } + + # Filter the results to sort out linux scripts + $GraphRequest = $GraphRequest | Where-Object { $_.platforms -ne 'linux' -and $_.templateReference.templateFamily -ne 'deviceConfigurationScripts' } $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneTemplates.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneTemplates.ps1 index 240d12d26d98..7ffcbf6cdd43 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneTemplates.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListIntuneTemplates.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListIntuneTemplates { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CippTable -tablename 'templates' $Imported = Get-CIPPAzDataTableEntity @Table -Filter "PartitionKey eq 'settings'" @@ -37,16 +37,21 @@ Function Invoke-ListIntuneTemplates { $RawTemplates = (Get-CIPPAzDataTableEntity @Table -Filter $Filter) if ($Request.query.View) { $Templates = $RawTemplates | ForEach-Object { - $JSONData = $_.JSON | ConvertFrom-Json - $data = $JSONData.RAWJson | ConvertFrom-Json -Depth 100 - $data | Add-Member -NotePropertyName 'displayName' -NotePropertyValue $JSONData.Displayname -Force - $data | Add-Member -NotePropertyName 'description' -NotePropertyValue $JSONData.Description -Force - $data | Add-Member -NotePropertyName 'Type' -NotePropertyValue $JSONData.Type -Force - $data | Add-Member -NotePropertyName 'GUID' -NotePropertyValue $_.RowKey -Force - $data + try { + $JSONData = $_.JSON | ConvertFrom-Json -Depth 100 -ErrorAction SilentlyContinue + $data = $JSONData.RAWJson | ConvertFrom-Json -Depth 100 -ErrorAction SilentlyContinue + $data | Add-Member -NotePropertyName 'displayName' -NotePropertyValue $JSONData.Displayname -Force + $data | Add-Member -NotePropertyName 'description' -NotePropertyValue $JSONData.Description -Force + $data | Add-Member -NotePropertyName 'Type' -NotePropertyValue $JSONData.Type -Force + $data | Add-Member -NotePropertyName 'GUID' -NotePropertyValue $_.RowKey -Force + $data + } catch { + + } + } | Sort-Object -Property displayName } else { - $Templates = $RawTemplates.JSON | ConvertFrom-Json + $Templates = $RawTemplates.JSON | ForEach-Object { try { ConvertFrom-Json -InputObject $_ -Depth 100 -ErrorAction SilentlyContinue } catch {} } } if ($Request.query.ID) { $Templates = $Templates | Where-Object -Property guid -EQ $Request.query.id } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListKnownIPDb.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListKnownIPDb.ps1 index 09f488be2304..e336eddbc938 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListKnownIPDb.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListKnownIPDb.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListKnownIPDb { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLicenses.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLicenses.ps1 index d6580cab36d2..59b8b8817d71 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLicenses.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLicenses.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListLicenses { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLogs.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLogs.ps1 index 56d168243bd4..c6fc0c2a88ac 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLogs.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListLogs.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListLogs { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable @@ -61,13 +61,15 @@ Function Invoke-ListLogs { } else { 'None' } + AppId = $Row.AppId + IP = $Row.IP } } } Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK - Body = @($ReturnedLog) + Body = @($ReturnedLog | Sort-Object -Property DateTime -Descending) }) } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMFAUsers.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMFAUsers.ps1 index 0cdf963febe6..8225f0b603da 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMFAUsers.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMFAUsers.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListMFAUsers { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxCAS.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxCAS.ps1 index 4386157564d4..c088305a95c1 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxCAS.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxCAS.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListMailboxCAS { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxMobileDevices.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxMobileDevices.ps1 index d1bab545e7a8..b09540ed117f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxMobileDevices.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxMobileDevices.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListMailboxMobileDevices { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxRestores.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxRestores.ps1 index 35d44175e0a5..1ffe8b543310 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxRestores.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxRestores.ps1 @@ -7,8 +7,8 @@ function Invoke-ListMailboxRestores { #> param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxes.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxes.ps1 index 44dafe01e001..bcbc251c921b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxes.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListMailboxes.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListMailboxes { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNamedLocations.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNamedLocations.ps1 index c1fb2e5c731a..a683b78a8347 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNamedLocations.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNamedLocations.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListNamedLocations { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNotificationConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNotificationConfig.ps1 index a375c65deb04..4d991c9d466a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNotificationConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListNotificationConfig.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListNotificationConfig { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Table = Get-CIPPTable -TableName SchedulerConfig $Filter = "RowKey eq 'CippNotifications' and PartitionKey eq 'CippNotifications'" diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOAuthApps.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOAuthApps.ps1 index 2183317e991d..4d720cdf9122 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOAuthApps.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOAuthApps.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListOAuthApps { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOrg.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOrg.ps1 index feb6de0d2f74..e94737a79274 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOrg.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListOrg.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListOrg { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPartnerRelationships.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPartnerRelationships.ps1 index 6ca16cfe8fd9..927d63b7067e 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPartnerRelationships.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPartnerRelationships.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListPartnerRelationships { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { $GraphRequestList = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPendingWebhooks.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPendingWebhooks.ps1 index 96c4a6eeb13a..ddad3aa638a7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPendingWebhooks.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPendingWebhooks.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListPendingWebhooks { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPotentialApps.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPotentialApps.ps1 index 0dfbeaa01642..0d95d6bffb71 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPotentialApps.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListPotentialApps.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListPotentialApps { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($request.body.type -eq 'WinGet') { $body = @" diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoles.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoles.ps1 index b56c40828a63..6d57f2daa1f9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoles.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoles.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListRoles { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoomLists.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoomLists.ps1 index 6f586800d8d0..93ac7fb9041c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoomLists.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRoomLists.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListRoomLists { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRooms.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRooms.ps1 index b99a00ae4c83..916364ef0f6c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRooms.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListRooms.ps1 @@ -10,23 +10,133 @@ Function Invoke-ListRooms { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - - - # Write to the Azure Functions log stream. - Write-Host 'PowerShell HTTP trigger function processed a request.' + $APIName = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. - $TenantFilter = $Request.Query.TenantFilter + $TenantFilter = $Request.Query.tenantFilter + $RoomId = $Request.Query.roomId + # I dont like that i had to change it to EXO commands, but the waiting time for the Rooms to sync to Graph is too long :( -Bobby try { - $params = @{ - uri = 'https://graph.microsoft.com/beta/places/microsoft.graph.room' - tenantid = $TenantFilter - AsApp = $true + if ($RoomId) { + # Get specific room mailbox + $RoomMailbox = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-Mailbox' -cmdParams @{ + Identity = $RoomId + RecipientTypeDetails = 'RoomMailbox' + } | Select-Object -ExcludeProperty *@odata.type* + + # Get place details + $PlaceDetails = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-Place' -cmdParams @{ + Identity = $RoomId + } | Select-Object -ExcludeProperty *@odata.type* + + if ($RoomMailbox -and $PlaceDetails) { + $GraphRequest = @( + [PSCustomObject]@{ + # Core Mailbox Properties + id = $RoomMailbox.ExternalDirectoryObjectId + displayName = $RoomMailbox.DisplayName + mail = $RoomMailbox.PrimarySmtpAddress + mailNickname = $RoomMailbox.Alias + accountDisabled = $RoomMailbox.AccountDisabled + hiddenFromAddressListsEnabled = $RoomMailbox.HiddenFromAddressListsEnabled + isDirSynced = $RoomMailbox.IsDirSynced + + # Room Booking Settings + bookingType = $PlaceDetails.BookingType + resourceDelegates = $PlaceDetails.ResourceDelegates + capacity = [int]($PlaceDetails.Capacity ?? $RoomMailbox.ResourceCapacity ?? 0) + + # Location Information + building = $PlaceDetails.Building + floor = $PlaceDetails.Floor + floorLabel = $PlaceDetails.FloorLabel + street = if ([string]::IsNullOrWhiteSpace($PlaceDetails.Street)) { $null } else { $PlaceDetails.Street } + city = if ([string]::IsNullOrWhiteSpace($PlaceDetails.City)) { $null } else { $PlaceDetails.City } + state = if ([string]::IsNullOrWhiteSpace($PlaceDetails.State)) { $null } else { $PlaceDetails.State } + postalCode = if ([string]::IsNullOrWhiteSpace($PlaceDetails.PostalCode)) { $null } else { $PlaceDetails.PostalCode } + countryOrRegion = if ([string]::IsNullOrWhiteSpace($PlaceDetails.CountryOrRegion)) { $null } else { $PlaceDetails.CountryOrRegion } + + # Room Equipment + audioDeviceName = $PlaceDetails.AudioDeviceName + videoDeviceName = $PlaceDetails.VideoDeviceName + displayDeviceName = $PlaceDetails.DisplayDeviceName + mtrEnabled = $PlaceDetails.MTREnabled + + # Room Features + isWheelChairAccessible = $PlaceDetails.IsWheelChairAccessible + phone = if ([string]::IsNullOrWhiteSpace($PlaceDetails.Phone)) { $null } else { $PlaceDetails.Phone } + tags = $PlaceDetails.Tags + spaceType = $PlaceDetails.SpaceType + } + ) + } + } else { + # Get all room mailboxes in one call + $RoomMailboxes = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-Mailbox' -cmdParams @{ + RecipientTypeDetails = 'RoomMailbox' + ResultSize = 'Unlimited' + } | Select-Object -ExcludeProperty *@odata.type* + + # Get all places in one call + $Places = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-Place' -cmdParams @{ + ResultSize = 'Unlimited' + } | Select-Object -ExcludeProperty *@odata.type* + + # Create hashtable for quick place lookups + $PlacesLookup = @{} + foreach ($Place in $Places) { + if ($Place.Identity) { + $PlacesLookup[$Place.Identity] = $Place + } + } + + $GraphRequest = @( + foreach ($Room in $RoomMailboxes) { + $PlaceDetails = $PlacesLookup[$Room.UserPrincipalName] ?? $PlacesLookup[$Room.PrimarySmtpAddress] + + [PSCustomObject]@{ + # Core Mailbox Properties + id = $Room.ExternalDirectoryObjectId + displayName = $Room.DisplayName + mail = $Room.PrimarySmtpAddress + mailNickname = $Room.Alias + accountDisabled = $Room.AccountDisabled + hiddenFromAddressListsEnabled = $Room.HiddenFromAddressListsEnabled + isDirSynced = $RoomMailbox.IsDirSynced + + # Room Booking Settings + bookingType = $PlaceDetails.BookingType + resourceDelegates = $PlaceDetails.ResourceDelegates + capacity = [int]($PlaceDetails.Capacity ?? $Room.ResourceCapacity ?? 0) + + # Location Information + building = $PlaceDetails.Building + floor = $PlaceDetails.Floor + floorLabel = $PlaceDetails.FloorLabel + street = if ([string]::IsNullOrWhiteSpace($PlaceDetails.Street)) { $null } else { $PlaceDetails.Street } + city = if ([string]::IsNullOrWhiteSpace($PlaceDetails.City)) { $null } else { $PlaceDetails.City } + state = if ([string]::IsNullOrWhiteSpace($PlaceDetails.State)) { $null } else { $PlaceDetails.State } + postalCode = if ([string]::IsNullOrWhiteSpace($PlaceDetails.PostalCode)) { $null } else { $PlaceDetails.PostalCode } + countryOrRegion = if ([string]::IsNullOrWhiteSpace($PlaceDetails.CountryOrRegion)) { $null } else { $PlaceDetails.CountryOrRegion } + + + # Room Equipment + audioDeviceName = $PlaceDetails.AudioDeviceName + videoDeviceName = $PlaceDetails.VideoDeviceName + displayDeviceName = $PlaceDetails.DisplayDeviceName + mtrEnabled = $PlaceDetails.MTREnabled + + # Room Features + isWheelChairAccessible = $PlaceDetails.IsWheelChairAccessible + phone = if ([string]::IsNullOrWhiteSpace($PlaceDetails.Phone)) { $null } else { $PlaceDetails.Phone } + tags = $PlaceDetails.Tags + spaceType = $PlaceDetails.SpaceType + } + } + ) } - $GraphRequest = New-GraphGetRequest @params $StatusCode = [HttpStatusCode]::OK } catch { @@ -34,10 +144,10 @@ Function Invoke-ListRooms { $StatusCode = [HttpStatusCode]::Forbidden $GraphRequest = $ErrorMessage } + # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = $StatusCode Body = @($GraphRequest | Sort-Object displayName) }) - } diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListServiceHealth.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListServiceHealth.ps1 index d9242a3e29a3..a7213fbf18b9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListServiceHealth.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListServiceHealth.ps1 @@ -10,7 +10,7 @@ Function Invoke-ListServiceHealth { [CmdletBinding()] param($Request, $TriggerMetadata) - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxAccountEnabled.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxAccountEnabled.ps1 index 4467289996ab..c7d6d401ab1f 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxAccountEnabled.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxAccountEnabled.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListSharedMailboxAccountEnabled { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxStatistics.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxStatistics.ps1 index 4b16ac630c80..996e6f13dc53 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxStatistics.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharedMailboxStatistics.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListSharedMailboxStatistics { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharepointQuota.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharepointQuota.ps1 index 3452764c04d0..233e0ba32654 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharepointQuota.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSharepointQuota.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListSharepointQuota { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSignIns.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSignIns.ps1 index c540e1803567..ddf582b995d5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSignIns.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListSignIns.ps1 @@ -13,7 +13,7 @@ Function Invoke-ListSignIns { # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter $Days = $Request.Query.Days ?? 7 @@ -31,7 +31,7 @@ Function Invoke-ListSignIns { "createdDateTime ge $($endTime) and userDisplayName ne 'On-Premises Directory Synchronization Service Account' $FailedLogons" } Write-Host $Filters - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Retrieved sign in report' -Sev 'Debug' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Retrieved sign in report' -Sev 'Debug' -tenant $TenantFilter $GraphRequest = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/auditLogs/signIns?api-version=beta&`$filter=$($filters)" -tenantid $TenantFilter -erroraction stop $response = $GraphRequest | Select-Object *, @@ -49,7 +49,7 @@ Function Invoke-ListSignIns { Body = @($response) }) } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to retrieve Sign In report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to retrieve Sign In report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = '500' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListStandards.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListStandards.ps1 index 7cea2d2bc1d1..a7a2d8358236 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListStandards.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListStandards.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListStandards { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' if ($Request.Query.ShowConsolidated -eq $true) { $StandardQuery = @{ diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListTenantAllowBlockList.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListTenantAllowBlockList.ps1 index d67651c0bc3f..01dcabaf6174 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListTenantAllowBlockList.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListTenantAllowBlockList.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListTenantAllowBlockList { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListmailboxPermissions.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListmailboxPermissions.ps1 index ae08abddcd8a..449fc929541d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListmailboxPermissions.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListmailboxPermissions.ps1 @@ -10,8 +10,8 @@ Function Invoke-ListmailboxPermissions { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.tenantFilter diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-RemoveTenantAllowBlockList.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-RemoveTenantAllowBlockList.ps1 index 52807bdcc27f..84a81ea0f4cd 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-RemoveTenantAllowBlockList.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-RemoveTenantAllowBlockList.ps1 @@ -10,37 +10,45 @@ Function Invoke-RemoveTenantAllowBlockList { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APIName -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' try { + + $listType = switch -Wildcard ($request.body.entries) { + '*@*' { 'Sender'; break } + '*.*' { 'Url'; break } + default { 'FileHash' } + } + Write-Host "List type is $listType" $ExoRequest = @{ - tenantid = $Request.query.tenantfilter + tenantid = $Request.body.tenantfilter cmdlet = 'Remove-TenantAllowBlockListItems' cmdParams = @{ - Entries = [string[]]$Request.query.entries - ListType = [string]$Request.query.listType + Entries = @($Request.body.entries) + ListType = $ListType } } - New-ExoRequest @ExoRequest + $Results = New-ExoRequest @ExoRequest + Write-Host $Results - $result = "Successfully removed $($Request.query.entries) from Block/Allow list" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $Request.query.tenantfilter -message $result -Sev 'Info' + $result = "Successfully removed $($Request.body.entries) from Block/Allow list" + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $Request.query.tenantfilter -message $result -Sev 'Info' } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - $result = "Failed to remove $($Request.query.entries). Error: $ErrorMessage" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $Request.query.tenantfilter -message $result -Sev 'Error' + $result = "Failed to remove $($Request.body.entries). Error: $ErrorMessage" + Write-LogMessage -headers $Request.Headers -API $APIName -tenant $Request.query.tenantfilter -message $result -Sev 'Error' } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK - Body = @{ - 'Results' = $result - 'Request' = $ExoRequest - } - }) + StatusCode = [HttpStatusCode]::OK + Body = @{ + 'Results' = $result + 'Request' = $ExoRequest + } + }) } diff --git a/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPProcessorQueue.ps1 b/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPProcessorQueue.ps1 index 6f79bcf4a4bc..094cfe4875a5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPProcessorQueue.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPProcessorQueue.ps1 @@ -10,8 +10,9 @@ function Start-CIPPProcessorQueue { $QueueItems = Get-CIPPAzDataTableEntity @QueueTable -Filter "PartitionKey eq 'Function'" foreach ($QueueItem in $QueueItems) { - if ($PSCmdlet.ShouldProcess("Processing function $($QueueItem.FunctionName)")) { - Write-Information "Running queued function $($QueueItem.FunctionName)" + $FunctionName = $QueueItem.FunctionName ?? $QueueItem.RowKey + if ($PSCmdlet.ShouldProcess("Processing function $($FunctionName)")) { + Write-Information "Running queued function $($FunctionName)" if ($QueueItem.Parameters) { try { $Parameters = $QueueItem.Parameters | ConvertFrom-Json -AsHashtable @@ -21,14 +22,14 @@ function Start-CIPPProcessorQueue { } else { $Parameters = @{} } - if (Get-Command -Name $QueueItem.FunctionName -ErrorAction SilentlyContinue) { + if (Get-Command -Name $FunctionName -ErrorAction SilentlyContinue) { try { - Invoke-Command -ScriptBlock { & $QueueItem.FunctionName @Parameters } + Invoke-Command -ScriptBlock { & $FunctionName @Parameters } } catch { - Write-Warning "Failed to run function $($QueueItem.FunctionName). Error: $($_.Exception.Message)" + Write-Warning "Failed to run function $($FunctionName). Error: $($_.Exception.Message)" } } else { - Write-Warning "Function $($QueueItem.FunctionName) not found" + Write-Warning "Function $($FunctionName) not found" } Remove-AzDataTableEntity -Force @QueueTable -Entity $QueueItem } diff --git a/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPStatsTimer.ps1 b/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPStatsTimer.ps1 index d62dcb8fd8ed..f7c53265b9d9 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPStatsTimer.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-CIPPStatsTimer.ps1 @@ -40,6 +40,8 @@ function Start-CIPPStatsTimer { haloPSA = $RawExt.haloPSA.Enabled HIBP = $RawExt.HIBP.Enabled PWPush = $RawExt.PWPush.Enabled + CFZTNA = $RawExt.CFZTNA.Enabled + GitHub = $RawExt.GitHub.Enabled } | ConvertTo-Json Invoke-RestMethod -Uri 'https://management.cipp.app/api/stats' -Method POST -Body $SendingObject -ContentType 'application/json' diff --git a/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 b/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 index b7aed6e35fc0..b7d8b1646468 100644 --- a/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 @@ -5,7 +5,7 @@ function Get-CIPPBitlockerKey { $device, $TenantFilter, $APIName = 'Get Bitlocker key', - $ExecutingUser + $Headers ) try { @@ -15,7 +15,7 @@ function Get-CIPPBitlockerKey { return $GraphRequest } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not retrieve bitlocker recovery key for $($device)" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Headers -API $APIName -message "Could not retrieve bitlocker recovery key for $($device)" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) return "Could not retrieve bitlocker recovery key for $($device). Error: $ErrorMessage" } } diff --git a/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 b/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 index eeac2a740ac2..e7fa518f0b7b 100644 --- a/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 @@ -5,7 +5,7 @@ function Get-CIPPLapsPassword { $device, $TenantFilter, $APIName = 'Get LAPS Password', - $ExecutingUser + $Headers ) try { @@ -17,7 +17,7 @@ function Get-CIPPLapsPassword { if ($GraphRequest) { return $GraphRequest } else { return "No LAPS password found for $device" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not retrieve LAPS password for $($device). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not retrieve LAPS password for $($device). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not retrieve LAPS password for $($device). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 b/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 index 2aaf6964e3ec..017e03fa978b 100644 --- a/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 @@ -4,7 +4,7 @@ function Get-CIPPLicenseOverview { param ( $TenantFilter, $APIName = 'Get License Overview', - $ExecutingUser + $Headers ) diff --git a/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 b/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 index 402543c97d02..68b9e03ae1a3 100644 --- a/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 @@ -4,7 +4,7 @@ function Get-CIPPMFAState { param ( $TenantFilter, $APIName = 'Get MFA Status', - $ExecutingUser + $Headers ) $PerUserMFAState = Get-CIPPPerUserMFA -TenantFilter $TenantFilter -AllUsers $true $users = foreach ($user in (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/users?$top=999&$select=id,UserPrincipalName,DisplayName,accountEnabled,assignedLicenses' -tenantid $TenantFilter)) { diff --git a/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 b/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 index caca21766253..2f5e45739c69 100644 --- a/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 @@ -4,7 +4,7 @@ function Get-CIPPOutOfOffice { $userid, $TenantFilter, $APIName = 'Get Out of Office', - $ExecutingUser + $Headers ) try { diff --git a/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 b/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 index 26a6033055ad..5a83e85f5a6c 100644 --- a/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 @@ -3,7 +3,7 @@ function Get-CIPPPerUserMFA { param( $TenantFilter, $userId, - $executingUser, + $Headers, $AllUsers = $false ) try { diff --git a/Modules/CIPPCore/Public/Get-CIPPTenantCapabilities.ps1 b/Modules/CIPPCore/Public/Get-CIPPTenantCapabilities.ps1 index 3db9c3a60562..5b44f04737e6 100644 --- a/Modules/CIPPCore/Public/Get-CIPPTenantCapabilities.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPTenantCapabilities.ps1 @@ -4,7 +4,7 @@ function Get-CIPPTenantCapabilities { param ( $TenantFilter, $APIName = 'Get Tenant Capabilities', - $ExecutingUser + $Headers ) $Org = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/organization' -tenantid $TenantFilter diff --git a/Modules/CIPPCore/Public/GraphHelper/Get-Tenants.ps1 b/Modules/CIPPCore/Public/GraphHelper/Get-Tenants.ps1 index 6cd3bd8bb5c6..9921b7c869e2 100644 --- a/Modules/CIPPCore/Public/GraphHelper/Get-Tenants.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/Get-Tenants.ps1 @@ -32,7 +32,7 @@ function Get-Tenants { } if ($TenantFilter) { - Write-Information "Getting tenant $TenantFilter" + #Write-Information "Getting tenant $TenantFilter" if ($TenantFilter -match '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') { $Filter = "{0} and customerId eq '{1}'" -f $Filter, $TenantFilter # create where-object scriptblock diff --git a/Modules/CIPPCore/Public/GraphHelper/New-ExoBulkRequest.ps1 b/Modules/CIPPCore/Public/GraphHelper/New-ExoBulkRequest.ps1 index 20a976d1e023..a7e7b08fe6d6 100644 --- a/Modules/CIPPCore/Public/GraphHelper/New-ExoBulkRequest.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/New-ExoBulkRequest.ps1 @@ -64,7 +64,7 @@ function New-ExoBulkRequest { $OnMicrosoft = $Tenant.initialDomainName $Anchor = "UPN:SystemMailbox{8cc370d3-822a-4ab8-a926-bb94bd0641a9}@$($OnMicrosoft)" } - $Headers['X-AnchorMailbox'] = $Anchor + $Headers['X-AnchorMailbox'] = "APP:SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@$($tenant.customerId)" $Headers['X-CmdletName'] = $cmd.CmdletInput.CmdletName $Headers['Accept'] = 'application/json; odata.metadata=minimal' $Headers['Accept-Encoding'] = 'gzip' diff --git a/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 b/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 index cbf6c5dc1d87..dcdb0a3ae7a0 100644 --- a/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 @@ -62,19 +62,7 @@ function New-ExoRequest { } } if (!$Anchor) { - if ($cmdparams.Identity) { $Anchor = $cmdparams.Identity } - if ($cmdparams.anr) { $Anchor = $cmdparams.anr } - if ($cmdparams.User) { $Anchor = $cmdparams.User } - if ($cmdparams.mailbox) { $Anchor = $cmdparams.mailbox } - if (!$Anchor -or $useSystemMailbox) { - if (!$Tenant.initialDomainName -or $Tenant.initialDomainName -notlike '*onmicrosoft.com*') { - $OnMicrosoft = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains?$top=999' -tenantid $tenantid -NoAuthCheck $NoAuthCheck | Where-Object -Property isInitial -EQ $true).id - } else { - $OnMicrosoft = $Tenant.initialDomainName - } - $anchor = "UPN:SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@$($OnMicrosoft)" - if ($cmdlet -in 'Set-AdminAuditLogConfig', 'Get-AdminAuditLogConfig', 'Enable-OrganizationCustomization', 'Get-OrganizationConfig', 'Set-OrganizationConfig') { $anchor = "UPN:SystemMailbox{8cc370d3-822a-4ab8-a926-bb94bd0641a9}@$($OnMicrosoft)" } - } + $anchor = "APP:SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@$($tenant.customerId)" } #if the anchor is a GUID, try looking up the user. if ($Anchor -match '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') { diff --git a/Modules/CIPPCore/Public/GraphHelper/Write-AlertMessage.ps1 b/Modules/CIPPCore/Public/GraphHelper/Write-AlertMessage.ps1 index 4d9fd8095059..5fa4f9633ff4 100644 --- a/Modules/CIPPCore/Public/GraphHelper/Write-AlertMessage.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/Write-AlertMessage.ps1 @@ -10,9 +10,9 @@ function Write-AlertMessage($message, $tenant = 'None', $tenantId = $null) { $ExistingMessage = Get-CIPPAzDataTableEntity @Table -Filter $Filter if (!$ExistingMessage) { Write-Host 'No duplicate message found, writing to log' - Write-LogMessage -message $message -tenant $tenant -sev 'Alert' -tenantId $tenantId -user 'CIPP' -API 'Alerts' + Write-LogMessage -message $message -tenant $tenant -sev 'Alert' -tenantId $tenantId -Headers'CIPP' -API 'Alerts' } else { Write-Host 'Alerts: Duplicate entry found, not writing to log' } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/GraphHelper/Write-LogMessage.ps1 b/Modules/CIPPCore/Public/GraphHelper/Write-LogMessage.ps1 index 27560afaa984..6c8a5f518e20 100644 --- a/Modules/CIPPCore/Public/GraphHelper/Write-LogMessage.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/Write-LogMessage.ps1 @@ -8,14 +8,31 @@ function Write-LogMessage { $tenant = 'None', $API = 'None', $tenantId = $null, + $headers, $user, $sev, $LogData = '' ) - try { + if ($Headers.'x-ms-client-principal-idp' -eq 'azureStaticWebApps' -or !$Headers.'x-ms-client-principal-idp') { + $user = $headers.'x-ms-client-principal' $username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($user)) | ConvertFrom-Json).userDetails - } catch { - $username = $user + } elseif ($Headers.'x-ms-client-principal-idp' -eq 'aad') { + $Table = Get-CIPPTable -TableName 'ApiClients' + $Client = Get-CIPPAzDataTableEntity @Table -Filter "RowKey eq '$($headers.'x-ms-client-principal-name')'" + $username = $Client.AppName ?? 'CIPP-API' + $AppId = $headers.'x-ms-client-principal-name' + } else { + try { + $username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($user)) | ConvertFrom-Json).userDetails + } catch { + $username = $user + } + } + + if ($headers.'x-forwarded-for') { + $ForwardedFor = $headers.'x-forwarded-for' -split ',' | Select-Object -First 1 + $IPRegex = '^(?(?:\d{1,3}(?:\.\d{1,3}){3}|\[[0-9a-fA-F:]+\]|[0-9a-fA-F:]+))(?::\d+)?$' + $IPAddress = $ForwardedFor -replace $IPRegex, '$1' -replace '[\[\]]', '' } if ($LogData) { $LogData = ConvertTo-Json -InputObject $LogData -Depth 10 -Compress } @@ -40,8 +57,12 @@ function Write-LogMessage { 'FunctionNode' = [string]$env:WEBSITE_SITE_NAME 'LogData' = [string]$LogData } - - + if ($IPAddress) { + $TableRow.IP = [string]$IPAddress + } + if ($AppId) { + $TableRow.AppId = [string]$AppId + } if ($tenantId) { $TableRow.Add('TenantID', [string]$tenantId) } diff --git a/Modules/CIPPCore/Public/Invoke-CIPPOffboardingJob.ps1 b/Modules/CIPPCore/Public/Invoke-CIPPOffboardingJob.ps1 index 961df76c6ac6..02d2d21114ea 100644 --- a/Modules/CIPPCore/Public/Invoke-CIPPOffboardingJob.ps1 +++ b/Modules/CIPPCore/Public/Invoke-CIPPOffboardingJob.ps1 @@ -7,7 +7,7 @@ function Invoke-CIPPOffboardingJob { [switch]$RunScheduled, $Options, $APIName = 'Offboard user', - $ExecutingUser + $Headers ) if ($Options -is [string]) { $Options = $Options | ConvertFrom-Json @@ -16,81 +16,74 @@ function Invoke-CIPPOffboardingJob { Write-Host "Running offboarding job for $username with options: $($Options | ConvertTo-Json -Depth 10)" $Return = switch ($Options) { { $_.'ConvertToShared' -eq $true } { - Set-CIPPMailboxType -ExecutingUser $ExecutingUser -tenantFilter $tenantFilter -userid $username -username $username -MailboxType 'Shared' -APIName $APIName + Set-CIPPMailboxType -Headers $Headers -tenantFilter $tenantFilter -userid $username -username $username -MailboxType 'Shared' -APIName $APIName } { $_.RevokeSessions -eq $true } { - Revoke-CIPPSessions -tenantFilter $tenantFilter -username $username -userid $userid -ExecutingUser $ExecutingUser -APIName $APIName + Revoke-CIPPSessions -tenantFilter $tenantFilter -username $username -userid $userid -Headers $Headers -APIName $APIName } { $_.ResetPass -eq $true } { - Set-CIPPResetPassword -tenantFilter $tenantFilter -userid $username -ExecutingUser $ExecutingUser -APIName $APIName + Set-CIPPResetPassword -tenantFilter $tenantFilter -UserID $username -Headers $Headers -APIName $APIName } { $_.RemoveGroups -eq $true } { - Remove-CIPPGroups -userid $userid -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName -Username "$Username" + Remove-CIPPGroups -userid $userid -tenantFilter $Tenantfilter -Headers $Headers -APIName $APIName -Username "$Username" } - { $_.'HideFromGAL' -eq $true } { - Set-CIPPHideFromGAL -tenantFilter $tenantFilter -userid $username -HideFromGAL $true -ExecutingUser $ExecutingUser -APIName $APIName + Set-CIPPHideFromGAL -tenantFilter $tenantFilter -UserID $username -hidefromgal $true -Headers $Headers -APIName $APIName } { $_.'DisableSignIn' -eq $true } { - Set-CIPPSignInState -TenantFilter $tenantFilter -userid $username -AccountEnabled $false -ExecutingUser $ExecutingUser -APIName $APIName + Set-CIPPSignInState -TenantFilter $tenantFilter -userid $username -AccountEnabled $false -Headers $Headers -APIName $APIName } - { $_.'OnedriveAccess' } { - $Options.OnedriveAccess | ForEach-Object { Set-CIPPSharePointPerms -tenantFilter $tenantFilter -userid $username -OnedriveAccessUser $_.value -ExecutingUser $ExecutingUser -APIName $APIName } + $Options.OnedriveAccess | ForEach-Object { Set-CIPPSharePointPerms -tenantFilter $tenantFilter -userid $username -OnedriveAccessUser $_.value -Headers $Headers -APIName $APIName } } - { $_.'AccessNoAutomap' } { - $Options.AccessNoAutomap | ForEach-Object { Set-CIPPMailboxAccess -tenantFilter $tenantFilter -userid $username -AccessUser $_.value -Automap $false -AccessRights @('FullAccess') -ExecutingUser $ExecutingUser -APIName $APIName } + $Options.AccessNoAutomap | ForEach-Object { Set-CIPPMailboxAccess -tenantFilter $tenantFilter -userid $username -AccessUser $_.value -Automap $false -AccessRights @('FullAccess') -Headers $Headers -APIName $APIName } } { $_.'AccessAutomap' } { - $Options.AccessAutomap | ForEach-Object { Set-CIPPMailboxAccess -tenantFilter $tenantFilter -userid $username -AccessUser $_.value -Automap $true -AccessRights @('FullAccess') -ExecutingUser $ExecutingUser -APIName $APIName } + $Options.AccessAutomap | ForEach-Object { Set-CIPPMailboxAccess -tenantFilter $tenantFilter -userid $username -AccessUser $_.value -Automap $true -AccessRights @('FullAccess') -Headers $Headers -APIName $APIName } } - { $_.'OOO' } { - Set-CIPPOutOfOffice -tenantFilter $tenantFilter -userid $username -InternalMessage $Options.OOO -ExternalMessage $Options.OOO -ExecutingUser $ExecutingUser -APIName $APIName -state 'Enabled' + Set-CIPPOutOfOffice -tenantFilter $tenantFilter -userid $username -InternalMessage $Options.OOO -ExternalMessage $Options.OOO -Headers $Headers -APIName $APIName -state 'Enabled' } { $_.'forward' } { if (!$Options.keepCopy) { - Set-CIPPForwarding -userid $userid -username $username -tenantFilter $Tenantfilter -Forward $Options.forward.value -ExecutingUser $ExecutingUser -APIName $APIName + Set-CIPPForwarding -userid $userid -username $username -tenantFilter $Tenantfilter -Forward $Options.forward.value -Headers $Headers -APIName $APIName } else { $KeepCopy = [boolean]$Options.keepCopy - Set-CIPPForwarding -userid $userid -username $username -tenantFilter $Tenantfilter -Forward $Options.forward.value -KeepCopy $KeepCopy -ExecutingUser $ExecutingUser -APIName $APIName + Set-CIPPForwarding -userid $userid -username $username -tenantFilter $Tenantfilter -Forward $Options.forward.value -KeepCopy $KeepCopy -Headers $Headers -APIName $APIName } } { $_.'RemoveLicenses' -eq $true } { - Remove-CIPPLicense -userid $userid -username $Username -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName -Schedule + Remove-CIPPLicense -userid $userid -username $Username -tenantFilter $Tenantfilter -Headers $Headers -APIName $APIName -Schedule } - { $_.'deleteuser' -eq $true } { - Remove-CIPPUser -userid $userid -username $Username -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName + Remove-CIPPUser -userid $userid -username $Username -tenantFilter $Tenantfilter -Headers $Headers -APIName $APIName } - { $_.'removeRules' -eq $true } { Write-Host "Removing rules for $username" - Remove-CIPPMailboxRule -userid $userid -username $Username -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName -RemoveAllRules + Remove-CIPPMailboxRule -userid $userid -username $Username -tenantFilter $Tenantfilter -Headers $Headers -APIName $APIName -RemoveAllRules } - { $_.'removeMobile' -eq $true } { - Remove-CIPPMobileDevice -userid $userid -username $Username -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName + Remove-CIPPMobileDevice -userid $userid -username $Username -tenantFilter $Tenantfilter -Headers $Headers -APIName $APIName } { $_.'removeCalendarInvites' -eq $true } { - Remove-CIPPCalendarInvites -userid $userid -username $Username -tenantFilter $Tenantfilter -ExecutingUser $ExecutingUser -APIName $APIName + Remove-CIPPCalendarInvites -userid $userid -username $Username -tenantFilter $Tenantfilter -Headers $Headers -APIName $APIName } { $_.'removePermissions' } { if ($RunScheduled) { - Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid 'AllUsers' -AccessUser $UserName -TenantFilter $TenantFilter -APIName $APINAME -ExecutingUser $ExecutingUser + Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid 'AllUsers' -AccessUser $UserName -TenantFilter $TenantFilter -APIName $APINAME -Headers $Headers } else { $Queue = New-CippQueueEntry -Name "Offboarding - Mailbox Permissions: $Username" -TotalTasks 1 $InputObject = [PSCustomObject]@{ Batch = @( [PSCustomObject]@{ - 'FunctionName' = 'ExecOffboardingMailboxPermissions' - 'TenantFilter' = $TenantFilter - 'User' = $Username - 'ExecutingUser' = $ExecutingUser - 'APINAME' = $APINAME - 'QueueId' = $Queue.RowKey + 'FunctionName' = 'ExecOffboardingMailboxPermissions' + 'TenantFilter' = $TenantFilter + 'User' = $Username + 'Headers' = $Headers + 'APINAME' = $APINAME + 'QueueId' = $Queue.RowKey } ) OrchestratorName = "OffboardingMailboxPermissions_$Username" @@ -101,9 +94,11 @@ function Invoke-CIPPOffboardingJob { } } { $_.'RemoveMFADevices' } { - Remove-CIPPUserMFA -UserPrincipalName $Username -TenantFilter $TenantFilter -ExecutingUser $ExecutingUser + Remove-CIPPUserMFA -UserPrincipalName $Username -TenantFilter $TenantFilter -Headers $Headers + } + { $_.'ClearImmutableId' -eq $true } { + Clear-CIPPImmutableId -userid $userid -TenantFilter $TenantFilter -Headers $Headers -APIName $APIName } - } return $Return diff --git a/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 index db939b3ee098..c04a4c40b4ed 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 @@ -10,8 +10,8 @@ Function Invoke-RemoveAPDevice { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Write to the Azure Functions log stream. Write-Host 'PowerShell HTTP trigger function processed a request.' @@ -25,11 +25,11 @@ Function Invoke-RemoveAPDevice { } else { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$Deviceid" -tenantid $TenantFilter -type DELETE } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $TenantFilter -API $APINAME -message "Deleted autopilot device $Deviceid" -Sev 'Info' + Write-LogMessage -headers $Request.Headers -tenant $TenantFilter -API $APINAME -message "Deleted autopilot device $Deviceid" -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully deleted the autopilot device' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $TenantFilter -API $APINAME -message "Autopilot Delete API failed for $deviceid. The error is: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Request.Headers -tenant $TenantFilter -API $APINAME -message "Autopilot Delete API failed for $deviceid. The error is: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to delete device: $($ErrorMessage.NormalizedError)" } } #force a sync, this can give "too many requests" if deleleting a bunch of devices though. diff --git a/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 index 10430868b406..b38057ad16ee 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveApp { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter @@ -21,11 +21,11 @@ Function Invoke-RemoveApp { try { #$unAssignRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($policyId)')/assign" -type POST -Body '{"assignments":[]}' -tenant $TenantFilter $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($policyId)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $User -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -Headers $User -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the application' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Could not delete app $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Could not delete app $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Could not delete this application: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 index 1f2046b4ed9e..376e2a02918e 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveBPATemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.TemplateName try { @@ -21,11 +21,11 @@ Function Invoke-RemoveBPATemplate { $Filter = "PartitionKey eq 'BPATemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed BPA Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed BPA Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed BPA Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove BPA template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove BPA template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 index ba2931f410b9..9d5a9380afcb 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveCAPolicy { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter @@ -20,12 +20,12 @@ Function Invoke-RemoveCAPolicy { if (!$policyId) { exit } try { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$($policyId)" -type DELETE -tenant $TenantFilter -asapp $true - Write-LogMessage -user $User -API $APINAME -message "Deleted CA Policy $policyId" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -Headers $User -API $APINAME -message "Deleted CA Policy $policyId" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the policy' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Could not delete CA policy $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Could not delete CA policy $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Could not delete policy: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 index 1d24c2095320..d355cf2a2235 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 @@ -10,10 +10,10 @@ Function Invoke-RemoveCATemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers $ID = $request.query.id - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { $Table = Get-CippTable -tablename 'templates' @@ -21,11 +21,11 @@ Function Invoke-RemoveCATemplate { $Filter = "PartitionKey eq 'CATemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Conditional Access Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Conditional Access Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Conditional Access Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove Conditional Access template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove Conditional Access template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveConnectionfilterTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveConnectionfilterTemplate.ps1 index 19526772e1e6..a36d7a66d94e 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveConnectionfilterTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveConnectionfilterTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveConnectionfilterTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.body.id try { @@ -20,11 +20,11 @@ Function Invoke-RemoveConnectionfilterTemplate { $Filter = "PartitionKey eq 'ConnectionfilterTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Connection Filter Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Connection Filter Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Connection Filter Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove Connection Filter template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove Connection Filter template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 index 3635459a6f1b..1494650832e9 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 @@ -10,10 +10,10 @@ Function Invoke-RemoveContact { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName + $APIName = $Request.Params.CIPPEndpoint $Tenantfilter = $request.Query.tenantfilter - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Params = @{ @@ -25,10 +25,10 @@ Function Invoke-RemoveContact { $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Remove-MailContact' -cmdParams $params -UseSystemMailbox $true $Result = "Deleted $($Request.query.guid)" - Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Deleted contact $($Request.query.guid)" -sev Debug + Write-LogMessage -Headers $User -API $APIName -tenant $tenantfilter -message "Deleted contact $($Request.query.guid)" -sev Debug } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Failed to delete contact $($Request.query.guid). $($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APIName -tenant $tenantfilter -message "Failed to delete contact $($Request.query.guid). $($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage $Result = $ErrorMessage.NormalizedError } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 index f5d3b9b141fd..10327d3e50b0 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 @@ -10,25 +10,29 @@ Function Invoke-RemoveExConnector { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' - $Tenantfilter = $request.Query.tenantfilter ?? $Request.Body.tenantfilter - $Type = $Request.Query.Type ?? $Request.Body.Type + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + $TenantFilter = $request.Query.tenantFilter ?? $Request.Body.tenantFilter + Write-LogMessage -headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' + try { + $Type = $Request.Query.Type ?? $Request.Body.Type $Guid = $Request.Query.GUID ?? $Request.Body.GUID $Params = @{ Identity = $Guid } - $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet "Remove-$($Type)Connector" -cmdParams $params -useSystemMailbox $true - $Result = "Deleted $($Guid)" - Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Deleted transport rule $($Guid)" -sev Debug + + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet "Remove-$($Type)Connector" -cmdParams $params -useSystemMailbox $true + $Result = "Deleted Connector: $($Guid)" + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Deleted connector $($Guid)" -sev Debug + $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Failed deleting transport rule $($Guid). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Failed deleting connector $($Guid). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $Result = $ErrorMessage.NormalizedError + $StatusCode = [HttpStatusCode]::Forbidden } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK + StatusCode = $StatusCode Body = @{Results = $Result } }) diff --git a/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 index 34100f0acb96..72eb798e3930 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveExConnectorTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $Request.Query.ID ?? $Request.Body.ID try { @@ -20,11 +20,11 @@ Function Invoke-RemoveExConnectorTemplate { $Filter = "PartitionKey eq 'ExConnectorTemplate' and RowKey eq '$ID'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Exchange Connector Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Exchange Connector Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Exchange Connector Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove Exchange Connector Template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove Exchange Connector Template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 index d7a330d0bdd9..bf0c45d1f90d 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveGroupTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -23,11 +23,11 @@ Function Invoke-RemoveGroupTemplate { Write-Host $Filter $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove intune template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove intune template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 index 5880b04b7968..636cf3fe7cfc 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveIntuneTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -23,11 +23,11 @@ Function Invoke-RemoveIntuneTemplate { Write-Host $Filter $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Intune Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove intune template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove intune template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 b/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 index aa94e6d3213c..2720fda34755 100644 --- a/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 @@ -10,31 +10,35 @@ Function Invoke-RemovePolicy { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -headers $Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. - $TenantFilter = $Request.Query.TenantFilter - $policyId = $Request.Query.ID - if (!$policyId) { exit } + $TenantFilter = $Request.Query.tenantFilter ?? $Request.body.tenantFilter + $PolicyId = $Request.Query.ID ?? $Request.body.ID + $UrlName = $Request.Query.URLName ?? $Request.body.URLName + + if (!$PolicyId) { exit } try { - #$unAssignRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($policyId)')/assign" -type POST -Body '{"assignments":[]}' -tenant $TenantFilter - $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$($Request.Query.URLName)('$($policyId)')" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $User -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter - $body = [pscustomobject]@{'Results' = 'Successfully deleted the policy' } + #$unAssignRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($PolicyId)')/assign" -type POST -Body '{"assignments":[]}' -tenant $TenantFilter + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$($UrlName)('$($PolicyId)')" -type DELETE -tenant $TenantFilter + $Results = "Successfully deleted the policy with ID: $($PolicyId)" + Write-LogMessage -headers $Headers -API $APINAME -message $Results -Sev Info -tenant $TenantFilter + $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Could not delete policy $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage - $body = [pscustomobject]@{'Results' = "Could not delete policy: $($ErrorMessage.NormalizedError)" } - + $Results = "Could not delete policy: $($ErrorMessage.NormalizedError)" + Write-LogMessage -headers $Headers -API $APINAME -message $Results -Sev Error -tenant $TenantFilter -LogData $ErrorMessage + $StatusCode = [HttpStatusCode]::Forbidden } + $body = [pscustomobject]@{'Results' = "$Results" } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ - StatusCode = [HttpStatusCode]::OK + StatusCode = $StatusCode Body = $body }) diff --git a/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 index 767f49448c3a..d4714f12dc55 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveQueuedApp { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.body.id try { @@ -20,11 +20,11 @@ Function Invoke-RemoveQueuedApp { $Filter = "PartitionKey eq 'apps' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed application queue for $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed application queue for $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed from queue.' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove application queue for $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove application queue for $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove item. $(Get-NormalizedError -message $_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 index 736b834d0d72..c67bf676a579 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveSpamfilter { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter $Params = @{ @@ -25,10 +25,10 @@ Function Invoke-RemoveSpamfilter { $cmdlet = 'Remove-HostedContentFilterPolicy' $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet $cmdlet -cmdParams $params -useSystemmailbox $true $Result = "Deleted $($Request.query.name)" - Write-LogMessage -user $User -API 'TransportRules' -tenant $tenantfilter -message "Deleted transport rule $($Request.query.name)" -sev Debug + Write-LogMessage -Headers $User -API 'TransportRules' -tenant $tenantfilter -message "Deleted transport rule $($Request.query.name)" -sev Debug } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API 'TransportRules' -tenant $tenantfilter -message "Failed deleting transport rule $($Request.query.name). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -Headers $User -API 'TransportRules' -tenant $tenantfilter -message "Failed deleting transport rule $($Request.query.name). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $Result = $ErrorMessage } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 index a6ed62eeabb3..c66447217bff 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveSpamfilterTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.body.id try { @@ -20,11 +20,11 @@ Function Invoke-RemoveSpamfilterTemplate { $Filter = "PartitionKey eq 'SpamfilterTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Spamfilter Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Spamfilter Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully Spamfilter template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove Spam filter Rule template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove Spam filter Rule template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 index af93c7a4cc95..393d6c886c4b 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveStandard { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -20,13 +20,13 @@ Function Invoke-RemoveStandard { $Filter = "PartitionKey eq 'standards' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed standards for $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed standards for $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed standards deployment' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove standard for $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove standard for $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' $body = [pscustomobject]@{'Results' = 'Failed to remove standard)' } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 index 00223f17f7c2..42f436018037 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveStandardTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $Request.Body.ID ?? $Request.Query.ID try { @@ -20,11 +20,11 @@ Function Invoke-RemoveStandardTemplate { $Filter = "PartitionKey eq 'StandardsTemplateV2' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Standards Template named $($ClearRow.name) and id $($id)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Standards Template named $($ClearRow.name) and id $($id)" -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove Standards template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove Standards template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 index fceb370fd81b..12af2322485a 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveTransportRule { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $ExecutingUser = $Request.headers.'x-ms-client-principal' - Write-LogMessage -user $ExecutingUser -API $APIName -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $Headers = $Request.Headers + Write-LogMessage -headers $Headers -API $APIName -message 'Accessed this API' -Sev 'Debug' $TenantFilter = $Request.Query.tenantFilter ?? $Request.body.tenantFilter $Identity = $Request.Query.guid ?? $Request.body.guid @@ -25,11 +25,11 @@ Function Invoke-RemoveTransportRule { $cmdlet = 'Remove-TransportRule' $null = New-ExoRequest -tenantid $TenantFilter -cmdlet $cmdlet -cmdParams $Params -UseSystemMailbox $true $Result = "Deleted $($Identity)" - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Deleted transport rule $($Identity)" -Sev Info + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Deleted transport rule $($Identity)" -Sev Info $StatusCode = [HttpStatusCode]::OK } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed deleting transport rule $($Identity). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Failed deleting transport rule $($Identity). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $Result = $ErrorMessage.NormalizedError $StatusCode = [HttpStatusCode]::Forbidden } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 index 1f32522ecddf..a5b744b89b7f 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveTransportRuleTemplate { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id ?? $request.body.id try { @@ -20,11 +20,11 @@ Function Invoke-RemoveTransportRuleTemplate { $Filter = "PartitionKey eq 'TransportTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity -Force @Table -Entity $clearRow - Write-LogMessage -user $User -API $APINAME -message "Removed Transport Rule Template with ID $ID." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Removed Transport Rule Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Transport Rule Template' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Failed to remove Transport Rule template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Failed to remove Transport Rule template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 index a018e2ffd710..264aeaf9ec9f 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 @@ -10,9 +10,9 @@ Function Invoke-RemoveUser { [CmdletBinding()] param($Request, $TriggerMetadata) - $APIName = $TriggerMetadata.FunctionName - $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $APIName = $Request.Params.CIPPEndpoint + $User = $Request.Headers + Write-LogMessage -Headers $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter @@ -20,12 +20,12 @@ Function Invoke-RemoveUser { if (!$userid) { exit } try { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $User -API $APINAME -message "Deleted $userid" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -Headers $User -API $APINAME -message "Deleted $userid" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the user.' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Could not delete user $userid. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Could not delete user $userid. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = "Could not delete user: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 b/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 deleted file mode 100644 index d09e17561641..000000000000 --- a/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 +++ /dev/null @@ -1,69 +0,0 @@ - - -function New-CIPPAPIConfig { - [CmdletBinding()] - param ( - $APIName = 'CIPP API Config', - $ExecutingUser, - $resetpassword - ) - $null = Connect-AzAccount -Identity - $VaultName = ($ENV:WEBSITE_DEPLOYMENT_ID -split '-')[0] - $currentapp = (Get-AzKeyVaultSecret -VaultName $VaultName -Name 'CIPPAPIAPP' -AsPlainText) - $subscription = $($ENV:WEBSITE_OWNER_NAME).Split('+')[0] - - try { - if ($currentapp) { - $APIApp = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/applications(appid='$($currentapp)')" -NoAuthCheck $true - } else { - $CreateBody = @" -{"api":{"oauth2PermissionScopes":[{"adminConsentDescription":"Allow the application to access CIPP-API on behalf of the signed-in user.","adminConsentDisplayName":"Access CIPP-API","id":"ba7ffeff-96ea-4ac4-9822-1bcfee9adaa4","isEnabled":true,"type":"User","userConsentDescription":"Allow the application to access CIPP-API on your behalf.","userConsentDisplayName":"Access CIPP-API","value":"user_impersonation"}]},"displayName":"CIPP-API","requiredResourceAccess":[{"resourceAccess":[{"id":"e1fe6dd8-ba31-4d61-89e7-88639da4683d","type":"Scope"}],"resourceAppId":"00000003-0000-0000-c000-000000000000"}],"signInAudience":"AzureADMyOrg","web":{"homePageUrl":"https://cipp.app","implicitGrantSettings":{"enableAccessTokenIssuance":false,"enableIdTokenIssuance":true},"redirectUris":["https://$($ENV:Website_hostname)/.auth/login/aad/callback"]}} -"@ - Write-Host 'Creating app' - $APIApp = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/applications' -NoAuthCheck $true -type POST -body $CreateBody - Write-Host 'Creating password' - $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" - Write-Host 'Adding App URL' - $APIIdUrl = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)" -NoAuthCheck $true -type PATCH -body "{`"identifierUris`":[`"api://$($APIApp.appId)`"]}" - Write-Host 'Adding serviceprincipal' - $ServicePrincipal = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/serviceprincipals' -NoAuthCheck $true -type POST -body "{`"accountEnabled`":true,`"appId`":`"$($APIApp.appId)`",`"displayName`":`"CIPP-API`",`"tags`":[`"WindowsAzureActiveDirectoryIntegratedApp`",`"AppServiceIntegratedApp`"]}" - } - if ($resetpassword) { - Write-Host 'Removing all old passwords' - $RemovePasswords = New-GraphPOSTRequest -type Patch -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/" -body '{"passwordCredentials":[]}' -NoAuthCheck $true - $passwordDate = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') - $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message 'Reset CIPP API Password.' -Sev 'info' - } else { - $CurrentSettings = New-GraphGetRequest -uri "https://management.azure.com/subscriptions/$($subscription)/resourceGroups/$ENV:WEBSITE_RESOURCE_GROUP/providers/Microsoft.Web/sites/$ENV:WEBSITE_SITE_NAME/Config/authsettingsV2/list?api-version=2018-11-01" -NoAuthCheck $true -scope 'https://management.azure.com/.default' - Write-Host 'setting settings' - $currentSettings.properties.identityProviders.azureActiveDirectory = @{ - registration = @{ - clientId = $APIApp.appId - openIdIssuer = "https://sts.windows.net/$($ENV:TenantID)/v2.0" - } - validation = @{ - allowedAudiences = @("api://$($APIApp.appId)") - } - } - $currentBody = ConvertTo-Json -Depth 15 -InputObject ($currentSettings | Select-Object Properties) - 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 'Successfully setup CIPP-API Access.' -Sev 'info' - } - return @{ - ApplicationID = $APIApp.AppId - ApplicationSecret = $APIPassword.secretText - Results = "API Enabled. Your API URL is https://$($ENV:Website_hostname). Your Application ID is $($APIApp.AppId) and your Application Secret is $($APIPassword.secretText) - Copy these keys, they are only shown once." - } - - } catch { - $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None' -message "Failed to setup CIPP-API Access: $($ErrorMessage.NormalizedError) Linenumber: $($_.InvocationInfo.ScriptLineNumber)" -Sev 'Error' -LogData $ErrorMessage - return @{ - Results = " but could not set API configuration: $($ErrorMessage.NormalizedError)" - } - - } -} diff --git a/Modules/CIPPCore/Public/New-CIPPBackup.ps1 b/Modules/CIPPCore/Public/New-CIPPBackup.ps1 index 09d441fcbde9..9e67a03f1ba0 100644 --- a/Modules/CIPPCore/Public/New-CIPPBackup.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPBackup.ps1 @@ -1,12 +1,12 @@ function New-CIPPBackup { - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess = $true)] param ( $backupType, $StorageOutput = 'default', $TenantFilter, $ScheduledBackupValues, $APIName = 'CIPP Backup', - $ExecutingUser + $Headers ) $BackupData = switch ($backupType) { @@ -39,17 +39,19 @@ function New-CIPPBackup { } $Table = Get-CippTable -tablename 'CIPPBackup' try { - $Result = Add-CIPPAzDataTableEntity @Table -Entity $entity -Force - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Created CIPP Backup' -Sev 'Debug' + if ($PSCmdlet.ShouldProcess('CIPP Backup', 'Create')) { + $Result = Add-CIPPAzDataTableEntity @Table -Entity $entity -Force + Write-LogMessage -headers $Headers -API $APINAME -message 'Created CIPP Backup' -Sev 'Debug' + } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup for CIPP: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -message "Failed to create backup for CIPP: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage [pscustomobject]@{'Results' = "Backup Creation failed: $($ErrorMessage.NormalizedError)" } } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -message "Failed to create backup: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage [pscustomobject]@{'Results' = "Backup Creation failed: $($ErrorMessage.NormalizedError)" } } } @@ -72,13 +74,13 @@ function New-CIPPBackup { $Table = Get-CippTable -tablename 'ScheduledBackup' try { $Result = Add-CIPPAzDataTableEntity @Table -entity $entity -Force - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Created backup' -Sev 'Debug' + Write-LogMessage -headers $Headers -API $APINAME -message 'Created backup' -Sev 'Debug' $State = 'Backup finished succesfully' $Result } catch { $State = 'Failed to write backup to table storage' $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup for Conditional Access Policies: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -message "Failed to create backup for Conditional Access Policies: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage [pscustomobject]@{'Results' = "Backup Creation failed: $($ErrorMessage.NormalizedError)" } } } diff --git a/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 b/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 index 10f1e81d45dc..11ec25cd0c60 100644 --- a/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 @@ -8,10 +8,10 @@ function New-CIPPCAPolicy { $Overwrite, $ReplacePattern = 'none', $APIName = 'Create CA Policy', - $ExecutingUser + $Headers ) - $User = $request.headers.'x-ms-client-principal' + $User = $Request.Headers function Remove-EmptyArrays ($Object) { if ($Object -is [Array]) { @@ -41,11 +41,11 @@ function New-CIPPCAPolicy { param($groupNames) return $groupNames | ForEach-Object { if (Test-IsGuid $_) { - Write-LogMessage -user $User -API $APINAME -message "Already GUID, no need to replace: $_" -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message "Already GUID, no need to replace: $_" -Sev 'Debug' $_ # it's a GUID, so we keep it } else { $groupId = ($groups | Where-Object -Property displayName -EQ $_).id # it's a display name, so we get the group ID - Write-LogMessage -user $User -API $APINAME -message "Replaced group name $_ with ID $groupId" -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message "Replaced group name $_ with ID $groupId" -Sev 'Debug' $groupId } } @@ -79,7 +79,7 @@ function New-CIPPCAPolicy { $Body = ConvertTo-Json -InputObject $JSONObj.GrantControls.authenticationStrength $GraphRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/authenticationStrength/policies' -body $body -Type POST -tenantid $tenantfilter $JSONObj.GrantControls.authenticationStrength = @{ id = $ExistingStrength.id } - Write-LogMessage -user $User -API $APINAME -message "Created new Authentication Strength Policy: $($JSONObj.GrantControls.authenticationStrength.displayName)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Created new Authentication Strength Policy: $($JSONObj.GrantControls.authenticationStrength.displayName)" -Sev 'Info' } } @@ -94,13 +94,13 @@ function New-CIPPCAPolicy { id = ($CheckExististing | Where-Object -Property displayName -EQ $Location.displayName).id name = ($CheckExististing | Where-Object -Property displayName -EQ $Location.displayName).displayName } - Write-LogMessage -user $User -API $APINAME -message "Matched a CA policy with the existing Named Location: $($location.displayName)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Matched a CA policy with the existing Named Location: $($location.displayName)" -Sev 'Info' } else { if ($location.countriesAndRegions) { $location.countriesAndRegions = @($location.countriesAndRegions) } $Body = ConvertTo-Json -InputObject $Location $GraphRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/namedLocations' -body $body -Type POST -tenantid $tenantfilter - Write-LogMessage -user $User -API $APINAME -message "Created new Named Location: $($location.displayName)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -message "Created new Named Location: $($location.displayName)" -Sev 'Info' [pscustomobject]@{ id = $GraphRequest.id name = $GraphRequest.displayName @@ -193,13 +193,13 @@ function New-CIPPCAPolicy { } else { Write-Host "overwriting $($CheckExististing.id)" $PatchRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/policies/$($CheckExististing.id)" -tenantid $tenantfilter -type PATCH -body $RawJSON - Write-LogMessage -user $User -API $APINAME -tenant $($Tenant) -message "Updated Conditional Access Policy $($JSONObj.Displayname) to the template standard." -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $($Tenant) -message "Updated Conditional Access Policy $($JSONObj.Displayname) to the template standard." -Sev 'Info' return "Updated policy $displayname for $tenantfilter" } } else { Write-Host 'Creating' $CreateRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/policies' -tenantid $tenantfilter -type POST -body $RawJSON - Write-LogMessage -user $User -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($JSONObj.Displayname)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($JSONObj.Displayname)" -Sev 'Info' return "Created policy $displayname for $tenantfilter" } } catch { diff --git a/Modules/CIPPCore/Public/New-CIPPCATemplate.ps1 b/Modules/CIPPCore/Public/New-CIPPCATemplate.ps1 index e2cd6b6a22e8..890fc1247bab 100644 --- a/Modules/CIPPCore/Public/New-CIPPCATemplate.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPCATemplate.ps1 @@ -4,7 +4,7 @@ function New-CIPPCATemplate { $TenantFilter, $JSON, $APIName = 'Add CIPP CA Template', - $ExecutingUser + $Headers ) $JSON = ([pscustomobject]$JSON) | ForEach-Object { diff --git a/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 b/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 index 8a1d2eaf5476..1d60aa3328d0 100644 --- a/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 @@ -5,16 +5,16 @@ function New-CIPPDeviceAction { $ActionBody = '{}', $DeviceFilter, $TenantFilter, - $ExecutingUser, + $Headers, $APINAME ) try { $null = New-Graphpostrequest -uri "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$DeviceFilter')/$($Action)" -type POST -tenantid $TenantFilter -body $ActionBody - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Queued $Action on $DeviceFilter" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $TenantFilter -message "Queued $Action on $DeviceFilter" -Sev 'Info' return "Queued $Action on $DeviceFilter" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Failed to queue action $Action on $DeviceFilter : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -tenant $TenantFilter -message "Failed to queue action $Action on $DeviceFilter : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Failed to queue action $Action on $DeviceFilter $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPIntuneTemplate.ps1 b/Modules/CIPPCore/Public/New-CIPPIntuneTemplate.ps1 index 0707b9824400..25595a59eb51 100644 --- a/Modules/CIPPCore/Public/New-CIPPIntuneTemplate.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPIntuneTemplate.ps1 @@ -4,8 +4,32 @@ function New-CIPPIntuneTemplate { $id, $TenantFilter, $ActionResults, - $CIPPURL + $CIPPURL, + $ODataType ) + Write-Host "These are all bound params: $urlname, $id, $TenantFilter, $ActionResults, $CIPPURL, $ODataType" + if ($ODataType) { + switch -wildcard ($ODataType) { + '*CompliancePolicy' { + $URLName = 'deviceCompliancePolicies' + } + '*managedAppPolicies' { + $URLName = 'managedAppPolicies' + } + '*configurationPolicies' { + $URLName = 'configurationPolicies' + } + '*windowsDriverUpdateProfiles' { + $URLName = 'windowsDriverUpdateProfiles' + } + '*deviceConfigurations' { + $URLName = 'deviceConfigurations' + } + '*groupPolicyConfigurations' { + $URLName = 'groupPolicyConfigurations' + } + } + } switch ($URLName) { 'deviceCompliancePolicies' { $Type = 'deviceCompliancePolicies' diff --git a/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 b/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 index d270b17efde3..2acbe9f71057 100644 --- a/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 @@ -7,7 +7,7 @@ function New-CIPPOneDriveShortCut { $URL, $TenantFilter, $APIName = 'Create OneDrive shortcut', - $ExecutingUser + $Headers ) Write-Host "Received $username and $userid. We're using $url and $TenantFilter" try { @@ -27,11 +27,11 @@ function New-CIPPOneDriveShortCut { '@microsoft.graph.conflictBehavior' = 'rename' } | ConvertTo-Json -Depth 10 New-GraphPOSTRequest -method POST "https://graph.microsoft.com/beta/users/$username/drive/root/children" -body $body -tenantid $TenantFilter -asapp $true - Write-LogMessage -API $APIName -user $ExecutingUser -message "Created OneDrive shortcut called $($SiteInfo.displayName) for $($username)" -Sev 'info' + Write-LogMessage -API $APIName -headers $Headers -message "Created OneDrive shortcut called $($SiteInfo.displayName) for $($username)" -Sev 'info' return "Created OneDrive Shortcut for $username called $($SiteInfo.displayName) " } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add Onedrive shortcut to $username : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not add Onedrive shortcut to $username : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Could not add Onedrive shortcut to $username : $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPRestore.ps1 b/Modules/CIPPCore/Public/New-CIPPRestore.ps1 index f3dd2ca21cbd..ec9ca53e4b12 100644 --- a/Modules/CIPPCore/Public/New-CIPPRestore.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPRestore.ps1 @@ -5,11 +5,11 @@ function New-CIPPRestore { $Type = 'Scheduled', $RestoreValues, $APIName = 'CIPP Restore', - $ExecutingUser + $Headers ) Write-Host "Scheduled Restore psproperties: $(([pscustomobject]$RestoreValues).psobject.Properties)" - Write-LogMessage -user $ExecutingUser -API $APINAME -message 'Restored backup' -Sev 'Debug' + Write-LogMessage -headers $Headers -API $APINAME -message 'Restored backup' -Sev 'Debug' $RestoreData = foreach ($ScheduledBackup in ([pscustomobject]$RestoreValues).psobject.Properties.Name | Where-Object { $_ -notin 'email', 'webhook', 'psa', 'backup', 'overwrite' }) { New-CIPPRestoreTask -Task $ScheduledBackup -TenantFilter $TenantFilter -backup $RestoreValues.backup.value -overwrite $RestoreValues.overwrite } diff --git a/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 b/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 index d7499abfff5d..9364749c54f2 100644 --- a/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 @@ -41,7 +41,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore user $($UPN): $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore user $($UPN): $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore user $($UPN): $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -77,7 +77,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore group $DisplayName : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore group $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore group $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -91,7 +91,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Conditional Access Policy $DisplayName : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Conditional Access Policy $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Conditional Access Policy $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -103,7 +103,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } #Convert the manual method to a function @@ -116,7 +116,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Intune Compliance $DisplayName : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } @@ -130,7 +130,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Intune Protection $DisplayName : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } @@ -146,9 +146,9 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not obtain Anti-Spam Configuration: $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not obtain Anti-Spam Configuration: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not obtain Anti-Spam Configuration: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } - + $policyparams = @( 'AddXHeaderValue', 'AdminDisplayName', @@ -227,7 +227,7 @@ function New-CIPPRestoreTask { $cmdparams = @{ Identity = $policy.Identity } - + foreach ($param in $policyparams) { if ($policy.PSObject.Properties[$param]) { if ($param -eq 'IntraOrgFilterState' -and $policy.$param -eq 'Default') { @@ -237,7 +237,7 @@ function New-CIPPRestoreTask { } } } - + New-ExoRequest -TenantId $Tenantfilter -cmdlet 'Set-HostedContentFilterPolicy' -cmdparams $cmdparams -UseSystemMailbox $true Write-LogMessage -message "Restored $($policy.Identity) from backup" -Sev 'info' @@ -266,7 +266,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Anti-spam policy $($policy.Identity) : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Anti-spam policy $($policy.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Anti-spam policy $($policy.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } @@ -277,7 +277,7 @@ function New-CIPPRestoreTask { $cmdparams = @{ Identity = $rule.Identity } - + foreach ($param in $ruleparams) { if ($rule.PSObject.Properties[$param]) { if ($param -eq 'Enabled') { @@ -287,7 +287,7 @@ function New-CIPPRestoreTask { } } } - + New-ExoRequest -TenantId $Tenantfilter -cmdlet 'Set-HostedContentFilterRule' -cmdparams $cmdparams -UseSystemMailbox $true Write-LogMessage -message "Restored $($rule.Identity) from backup" -Sev 'info' @@ -316,7 +316,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Anti-spam rule $($rule.Identity) : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Anti-spam rule $($rule.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Anti-spam rule $($rule.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -331,9 +331,9 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not obtain Anti-Phishing Configuration: $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not obtain Anti-Phishing Configuration: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not obtain Anti-Phishing Configuration: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } - + $policyparams = @( 'AdminDisplayName', 'AuthenticationFailAction', @@ -392,13 +392,13 @@ function New-CIPPRestoreTask { $cmdparams = @{ Identity = $policy.Identity } - + foreach ($param in $policyparams) { if ($policy.PSObject.Properties[$param]) { $cmdparams[$param] = $policy.$param } } - + New-ExoRequest -TenantId $Tenantfilter -cmdlet 'Set-AntiPhishPolicy' -cmdparams $cmdparams -UseSystemMailbox $true Write-LogMessage -message "Restored $($policy.Identity) from backup" -Sev 'info' @@ -423,7 +423,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Anti-phishing policy $($policy.Identity) : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Anti-phishing policy $($policy.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Anti-phishing policy $($policy.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } @@ -434,7 +434,7 @@ function New-CIPPRestoreTask { $cmdparams = @{ Identity = $rule.Identity } - + foreach ($param in $ruleparams) { if ($rule.PSObject.Properties[$param]) { if ($param -eq 'Enabled') { @@ -444,7 +444,7 @@ function New-CIPPRestoreTask { } } } - + New-ExoRequest -TenantId $Tenantfilter -cmdlet 'Set-AntiPhishRule' -cmdparams $cmdparams -UseSystemMailbox $true Write-LogMessage -message "Restored $($rule.Identity) from backup" -Sev 'info' @@ -473,7 +473,7 @@ function New-CIPPRestoreTask { } catch { $ErrorMessage = Get-CippException -Exception $_ "Could not restore Anti-phishing rule $($rule.Identity) : $($ErrorMessage.NormalizedError) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Anti-phishing rule $($rule.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $Headers -API $APINAME -message "Could not restore Anti-phishing rule $($rule.Identity) : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } diff --git a/Modules/CIPPCore/Public/New-CIPPTAP.ps1 b/Modules/CIPPCore/Public/New-CIPPTAP.ps1 index 27c1a0648046..90df35f9d05c 100644 --- a/Modules/CIPPCore/Public/New-CIPPTAP.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPTAP.ps1 @@ -4,13 +4,13 @@ function New-CIPPTAP { $userid, $TenantFilter, $APIName = 'Create TAP', - $ExecutingUser + $Headers ) try { $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/authentication/temporaryAccessPassMethods" -tenantid $TenantFilter -type POST -body '{}' -verbose - Write-LogMessage -user $ExecutingUser -API $APIName -message "Created Temporary Access Password (TAP) for $userid" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Created Temporary Access Password (TAP) for $userid" -Sev 'Info' -tenant $TenantFilter return [pscustomobject]@{ resultText = "The TAP for this user is $($GraphRequest.temporaryAccessPass) - This TAP is usable for the next $($GraphRequest.LifetimeInMinutes) minutes" copyField = $($GraphRequest.temporaryAccessPass) state = 'success' @@ -18,7 +18,7 @@ function New-CIPPTAP { } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to created TAP for $($userid): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Failed to created TAP for $($userid): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage Return [pscustomobject]@{ resultText = "Failed to create TAP: $($ErrorMessage.NormalizedError)" state = 'error' } diff --git a/Modules/CIPPCore/Public/New-CIPPTemplateRun.ps1 b/Modules/CIPPCore/Public/New-CIPPTemplateRun.ps1 index 6265eafb927b..ba6144f6b69d 100644 --- a/Modules/CIPPCore/Public/New-CIPPTemplateRun.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPTemplateRun.ps1 @@ -6,9 +6,10 @@ function New-CIPPTemplateRun { ) $Table = Get-CippTable -tablename 'templates' $ExistingTemplates = (Get-CIPPAzDataTableEntity @Table) | ForEach-Object { - $data = $_.JSON | ConvertFrom-Json -Depth 100 + $data = $_.JSON | ConvertFrom-Json -ErrorAction SilentlyContinue -Depth 100 $data | Add-Member -NotePropertyName 'GUID' -NotePropertyValue $_.RowKey -Force $data | Add-Member -NotePropertyName 'PartitionKey' -NotePropertyValue $_.PartitionKey -Force + $data | Add-Member -NotePropertyName 'SHA' -NotePropertyValue $_.SHA -Force $data } | Sort-Object -Property displayName @@ -18,184 +19,211 @@ function New-CIPPTemplateRun { $key } } + if ($TemplateSettings.templateRepo) { + Write-Host 'Grabbing data from required community repo' + $Files = (Get-GitHubFileTree -FullName $TemplateSettings.templateRepo.value -Branch $TemplateSettings.templateRepoBranch.value).tree | Where-Object { $_.path -match '.json$' -and $_.path -notmatch 'NativeImport' } | Select-Object *, @{n = 'html_url'; e = { "https://github.com/$($SplatParams.FullName)/tree/$($SplatParams.Branch)/$($_.path)" } }, @{n = 'name'; e = { ($_.path -split '/')[ -1 ] -replace '\.json$', '' } } + #if there is a migration table file, file the file. Store the file contents in $migrationtable + $MigrationTable = $Files | Where-Object { $_.name -eq 'MigrationTable' } | Select-Object -Last 1 + if ($MigrationTable) { + $MigrationTable = (Get-GitHubFileContents -FullName $TemplateSettings.templateRepo.value -Branch $TemplateSettings.templateRepoBranch.value -Path $MigrationTable.path).content | ConvertFrom-Json + } + foreach ($File in $Files) { + if ($File.name -eq 'MigrationTable' -or $file.name -eq 'ALLOWED COUNTRIES') { continue } + $ExistingTemplate = $ExistingTemplates | Where-Object { $_.displayName -eq $File.name } | Select-Object -First 1 + $Template = (Get-GitHubFileContents -FullName $TemplateSettings.templateRepo.value -Branch $TemplateSettings.templateRepoBranch.value -Path $File.path).content | ConvertFrom-Json + if ($ExistingTemplate) { + $UpdateNeeded = $false + if ($ExistingTemplate.sha -ne $File.sha -or !$ExistingTemplate.sha) { + $UpdateNeeded = $true + } + if ($UpdateNeeded) { + Write-Host "Template $($File.name) needs to be updated as the SHA is different" + Import-CommunityTemplate -Template $Template -SHA $File.sha -MigrationTable $MigrationTable + } + } else { + Write-Host "Template $($File.name) needs to be created" + Import-CommunityTemplate -Template $Template -SHA $File.sha -MigrationTable $MigrationTable + } + } + } else { + foreach ($Task in $Tasks) { + Write-Host "Working on task $Task" + switch ($Task) { + 'ca' { + Write-Host "Template Conditional Access Policies for $TenantFilter" + $Policies = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/conditionalAccess/policies?$top=999' -tenantid $TenantFilter + Write-Host 'Creating templates for found Conditional Access Policies' + foreach ($policy in $policies) { + try { + $Template = New-CIPPCATemplate -TenantFilter $TenantFilter -JSON $policy + #check existing templates, if the displayName is the same, overwrite it. + $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $policy.displayName } | Select-Object -First 1 + if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'CATemplate') { + "Policy $($policy.displayName) found, updating template" + Add-CIPPAzDataTableEntity @Table -Entity @{ + JSON = "$Template" + RowKey = $ExistingPolicy.GUID + PartitionKey = 'CATemplate' + GUID = $ExistingPolicy.GUID + } -Force + } else { + "Policy $($policy.displayName) not found in existing templates, creating new template" + $GUID = (New-Guid).GUID + Add-CIPPAzDataTableEntity @Table -Entity @{ + JSON = "$Template" + RowKey = "$GUID" + PartitionKey = 'CATemplate' + GUID = "$GUID" + } + } + + } catch { + "Failed to create a template of the Conditional Access Policy with ID: $($policy.id). Error: $($_.Exception.Message)" + } + } + } + 'intuneconfig' { + Write-Host "Backup Intune Configuration Policies for $TenantFilter" + $GraphURLS = @("https://graph.microsoft.com/beta/deviceManagement/deviceConfigurations?`$select=id,displayName,lastModifiedDateTime,roleScopeTagIds,microsoft.graph.unsupportedDeviceConfiguration/originalEntityTypeName&`$expand=assignments&top=1000" + 'https://graph.microsoft.com/beta/deviceManagement/windowsDriverUpdateProfiles' + "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations?`$expand=assignments&top=999" + "https://graph.microsoft.com/beta/deviceAppManagement/mobileAppConfigurations?`$expand=assignments&`$filter=microsoft.graph.androidManagedStoreAppConfiguration/appSupportsOemConfig%20eq%20true" + 'https://graph.microsoft.com/beta/deviceManagement/configurationPolicies' + ) + + $Policies = foreach ($url in $GraphURLS) { + try { + $Policies = New-GraphGetRequest -uri "$($url)" -tenantid $TenantFilter + $URLName = (($url).split('?') | Select-Object -First 1) -replace 'https://graph.microsoft.com/beta/deviceManagement/', '' + foreach ($Policy in $Policies) { + try { + $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName $URLName -ID $Policy.ID + $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $Template.DisplayName } | Select-Object -First 1 + if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'IntuneTemplate') { + "Policy $($Template.DisplayName) found, updating template" + $object = [PSCustomObject]@{ + Displayname = $Template.DisplayName + Description = $Template.Description + RAWJson = $Template.TemplateJson + Type = $Template.Type + GUID = $ExistingPolicy.GUID + } | ConvertTo-Json + + Add-CIPPAzDataTableEntity @Table -Entity @{ + JSON = "$object" + RowKey = $ExistingPolicy.GUID + PartitionKey = 'IntuneTemplate' + } -Force + } else { + "Policy $($Template.DisplayName) not found in existing templates, creating new template" + $GUID = (New-Guid).GUID + $object = [PSCustomObject]@{ + Displayname = $Template.DisplayName + Description = $Template.Description + RAWJson = $Template.TemplateJson + Type = $Template.Type + GUID = $GUID + } | ConvertTo-Json + + Add-CIPPAzDataTableEntity @Table -Entity @{ + JSON = "$object" + RowKey = "$GUID" + PartitionKey = 'IntuneTemplate' + } -Force + } + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + "Failed to create a template of the Intune Configuration Policy with ID: $($Policy.id). Error: $ErrorMessage" + } + } + } catch { + Write-Host "Failed to backup $url" + } + } + } + 'intunecompliance' { + Write-Host "Backup Intune Compliance Policies for $TenantFilter" + New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies?$top=999' -tenantid $TenantFilter | ForEach-Object { + $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName 'deviceCompliancePolicies' -ID $_.ID + $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $Template.DisplayName } | Select-Object -First 1 + if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'IntuneTemplate') { + "Policy $($Template.DisplayName) found, updating template" + $object = [PSCustomObject]@{ + Displayname = $Template.DisplayName + Description = $Template.Description + RAWJson = $Template.TemplateJson + Type = $Template.Type + GUID = $ExistingPolicy.GUID + } | ConvertTo-Json - foreach ($Task in $Tasks) { - Write-Host "Working on task $Task" - switch ($Task) { - 'ca' { - Write-Host "Template Conditional Access Policies for $TenantFilter" - $Policies = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/conditionalAccess/policies?$top=999' -tenantid $TenantFilter - Write-Host 'Creating templates for found Conditional Access Policies' - foreach ($policy in $policies) { - try { - $Template = New-CIPPCATemplate -TenantFilter $TenantFilter -JSON $policy - #check existing templates, if the displayName is the same, overwrite it. - $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $policy.displayName } | Select-Object -First 1 - if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'CATemplate') { - "Policy $($policy.displayName) found, updating template" Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$Template" + JSON = "$object" RowKey = $ExistingPolicy.GUID - PartitionKey = 'CATemplate' - GUID = $ExistingPolicy.GUID + PartitionKey = 'IntuneTemplate' } -Force } else { - "Policy $($policy.displayName) not found in existing templates, creating new template" + "Policy $($Template.DisplayName) not found in existing templates, creating new template" $GUID = (New-Guid).GUID + $object = [PSCustomObject]@{ + Displayname = $Template.DisplayName + Description = $Template.Description + RAWJson = $Template.TemplateJson + Type = $Template.Type + GUID = $GUID + } | ConvertTo-Json + Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$Template" + JSON = "$object" RowKey = "$GUID" - PartitionKey = 'CATemplate' - GUID = "$GUID" - } + PartitionKey = 'IntuneTemplate' + } -Force } - } catch { - "Failed to create a template of the Conditional Access Policy with ID: $($policy.id). Error: $($_.Exception.Message)" } } - } - 'intuneconfig' { - Write-Host "Backup Intune Configuration Policies for $TenantFilter" - $GraphURLS = @("https://graph.microsoft.com/beta/deviceManagement/deviceConfigurations?`$select=id,displayName,lastModifiedDateTime,roleScopeTagIds,microsoft.graph.unsupportedDeviceConfiguration/originalEntityTypeName&`$expand=assignments&top=1000" - 'https://graph.microsoft.com/beta/deviceManagement/windowsDriverUpdateProfiles' - "https://graph.microsoft.com/beta/deviceManagement/groupPolicyConfigurations?`$expand=assignments&top=999" - "https://graph.microsoft.com/beta/deviceAppManagement/mobileAppConfigurations?`$expand=assignments&`$filter=microsoft.graph.androidManagedStoreAppConfiguration/appSupportsOemConfig%20eq%20true" - 'https://graph.microsoft.com/beta/deviceManagement/configurationPolicies' - ) - $Policies = foreach ($url in $GraphURLS) { - try { - $Policies = New-GraphGetRequest -uri "$($url)" -tenantid $TenantFilter - $URLName = (($url).split('?') | Select-Object -First 1) -replace 'https://graph.microsoft.com/beta/deviceManagement/', '' - foreach ($Policy in $Policies) { - try { - $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName $URLName -ID $Policy.ID - $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $Template.DisplayName } | Select-Object -First 1 - if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'IntuneTemplate') { - "Policy $($Template.DisplayName) found, updating template" - $object = [PSCustomObject]@{ - Displayname = $Template.DisplayName - Description = $Template.Description - RAWJson = $Template.TemplateJson - Type = $Template.Type - GUID = $ExistingPolicy.GUID - } | ConvertTo-Json + 'intuneprotection' { + Write-Host "Backup Intune Protection Policies for $TenantFilter" + New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceAppManagement/managedAppPolicies?$top=999' -tenantid $TenantFilter | ForEach-Object { + $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName 'managedAppPolicies' -ID $_.ID + $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $Template.DisplayName } | Select-Object -First 1 + if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'IntuneTemplate') { + "Policy $($Template.DisplayName) found, updating template" + $object = [PSCustomObject]@{ + Displayname = $Template.DisplayName + Description = $Template.Description + RAWJson = $Template.TemplateJson + Type = $Template.Type + GUID = $ExistingPolicy.GUID + } | ConvertTo-Json - Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$object" - RowKey = $ExistingPolicy.GUID - PartitionKey = 'IntuneTemplate' - } -Force - } else { - "Policy $($Template.DisplayName) not found in existing templates, creating new template" - $GUID = (New-Guid).GUID - $object = [PSCustomObject]@{ - Displayname = $Template.DisplayName - Description = $Template.Description - RAWJson = $Template.TemplateJson - Type = $Template.Type - GUID = $GUID - } | ConvertTo-Json + Add-CIPPAzDataTableEntity @Table -Entity @{ + JSON = "$object" + RowKey = $ExistingPolicy.GUID + PartitionKey = 'IntuneTemplate' + } -Force + } else { + "Policy $($Template.DisplayName) not found in existing templates, creating new template" + $GUID = (New-Guid).GUID + $object = [PSCustomObject]@{ + Displayname = $Template.DisplayName + Description = $Template.Description + RAWJson = $Template.TemplateJson + Type = $Template.Type + GUID = $GUID + } | ConvertTo-Json - Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$object" - RowKey = "$GUID" - PartitionKey = 'IntuneTemplate' - } -Force - } - } catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - "Failed to create a template of the Intune Configuration Policy with ID: $($Policy.id). Error: $ErrorMessage" - } + Add-CIPPAzDataTableEntity @Table -Entity @{ + JSON = "$object" + RowKey = "$GUID" + PartitionKey = 'IntuneTemplate' + } -Force } - } catch { - Write-Host "Failed to backup $url" } } - } - 'intunecompliance' { - Write-Host "Backup Intune Compliance Policies for $TenantFilter" - New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies?$top=999' -tenantid $TenantFilter | ForEach-Object { - $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName 'deviceCompliancePolicies' -ID $_.ID - $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $Template.DisplayName } | Select-Object -First 1 - if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'IntuneTemplate') { - "Policy $($Template.DisplayName) found, updating template" - $object = [PSCustomObject]@{ - Displayname = $Template.DisplayName - Description = $Template.Description - RAWJson = $Template.TemplateJson - Type = $Template.Type - GUID = $ExistingPolicy.GUID - } | ConvertTo-Json - - Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$object" - RowKey = $ExistingPolicy.GUID - PartitionKey = 'IntuneTemplate' - } -Force - } else { - "Policy $($Template.DisplayName) not found in existing templates, creating new template" - $GUID = (New-Guid).GUID - $object = [PSCustomObject]@{ - Displayname = $Template.DisplayName - Description = $Template.Description - RAWJson = $Template.TemplateJson - Type = $Template.Type - GUID = $GUID - } | ConvertTo-Json - Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$object" - RowKey = "$GUID" - PartitionKey = 'IntuneTemplate' - } -Force - } - - } - } - - 'intuneprotection' { - Write-Host "Backup Intune Protection Policies for $TenantFilter" - New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceAppManagement/managedAppPolicies?$top=999' -tenantid $TenantFilter | ForEach-Object { - $Template = New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName 'managedAppPolicies' -ID $_.ID - $ExistingPolicy = $ExistingTemplates | Where-Object { $_.displayName -eq $Template.DisplayName } | Select-Object -First 1 - if ($ExistingPolicy -and $ExistingPolicy.PartitionKey -eq 'IntuneTemplate') { - "Policy $($Template.DisplayName) found, updating template" - $object = [PSCustomObject]@{ - Displayname = $Template.DisplayName - Description = $Template.Description - RAWJson = $Template.TemplateJson - Type = $Template.Type - GUID = $ExistingPolicy.GUID - } | ConvertTo-Json - - Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$object" - RowKey = $ExistingPolicy.GUID - PartitionKey = 'IntuneTemplate' - } -Force - } else { - "Policy $($Template.DisplayName) not found in existing templates, creating new template" - $GUID = (New-Guid).GUID - $object = [PSCustomObject]@{ - Displayname = $Template.DisplayName - Description = $Template.Description - RAWJson = $Template.TemplateJson - Type = $Template.Type - GUID = $GUID - } | ConvertTo-Json - - Add-CIPPAzDataTableEntity @Table -Entity @{ - JSON = "$object" - RowKey = "$GUID" - PartitionKey = 'IntuneTemplate' - } -Force - } - } } - } } return $BackupData diff --git a/Modules/CIPPCore/Public/New-CIPPUserTask.ps1 b/Modules/CIPPCore/Public/New-CIPPUserTask.ps1 index f5db22fce712..d23a10deb209 100644 --- a/Modules/CIPPCore/Public/New-CIPPUserTask.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPUserTask.ps1 @@ -3,13 +3,13 @@ function New-CIPPUserTask { param ( $userobj, $APIName = 'New User Task', - $ExecutingUser, - $TenantFilter + $TenantFilter, + $Headers ) $Results = [System.Collections.Generic.List[string]]::new() try { - $CreationResults = New-CIPPUser -userobj $UserObj -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $CreationResults = New-CIPPUser -userobj $UserObj -APIName $APINAME -Headers $Headers $results.add('Created New User.') $results.add("Username: $($CreationResults.username)") $results.add("Password: $($CreationResults.password)") @@ -20,32 +20,32 @@ function New-CIPPUserTask { try { if ($userobj.licenses.value) { - $LicenseResults = Set-CIPPUserLicense -UserId $CreationResults.username -TenantFilter $UserObj.tenantFilter -AddLicenses $UserObj.licenses.value + $LicenseResults = Set-CIPPUserLicense -UserId $CreationResults.username -TenantFilter $UserObj.tenantFilter -AddLicenses $UserObj.licenses.value -Headers $Headers $Results.Add($LicenseResults) } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantFilter) -message "Failed to assign the license. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($userobj.tenantFilter) -message "Failed to assign the license. Error:$($_.Exception.Message)" -Sev 'Error' $body = $results.add("Failed to assign the license. $($_.Exception.Message)") } try { if ($Userobj.AddedAliases) { - $AliasResults = Add-CIPPAlias -user $CreationResults.username -Aliases ($UserObj.AddedAliases -split '\s') -UserprincipalName $CreationResults.Username -TenantFilter $UserObj.tenantFilter -APIName $APINAME -ExecutingUser $request.headers.'x-ms-client-principal' + $AliasResults = Add-CIPPAlias -user $CreationResults.username -Aliases ($UserObj.AddedAliases -split '\s') -UserprincipalName $CreationResults.Username -TenantFilter $UserObj.tenantFilter -APIName $APINAME -Headers $Headers $results.add($AliasResults) } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantFilter) -message "Failed to create the Aliases. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($userobj.tenantFilter) -message "Failed to create the Aliases. Error:$($_.Exception.Message)" -Sev 'Error' $body = $results.add("Failed to create the Aliases: $($_.Exception.Message)") } if ($userobj.copyFrom.value) { Write-Host "Copying from $($userObj.copyFrom.value)" - $CopyFrom = Set-CIPPCopyGroupMembers -ExecutingUser $request.headers.'x-ms-client-principal' -CopyFromId $userObj.copyFrom.value -UserID $CreationResults.Username -TenantFilter $UserObj.tenantFilter + $CopyFrom = Set-CIPPCopyGroupMembers -Headers $Headers -CopyFromId $userObj.copyFrom.value -UserID $CreationResults.Username -TenantFilter $UserObj.tenantFilter $CopyFrom.Success | ForEach-Object { $results.Add($_) } $CopyFrom.Error | ForEach-Object { $results.Add($_) } } if ($userobj.setManager) { - $ManagerResult = Set-CIPPManager -user $CreationResults.username -Manager $userObj.setManager.value -TenantFilter $UserObj.tenantFilter -APIName 'Set Manager' -ExecutingUser $request.headers.'x-ms-client-principal' + $ManagerResult = Set-CIPPManager -user $CreationResults.username -Manager $userObj.setManager.value -TenantFilter $UserObj.tenantFilter -APIName 'Set Manager' -Headers $Headers $results.add($ManagerResult) } diff --git a/Modules/CIPPCore/Public/New-CippUser.ps1 b/Modules/CIPPCore/Public/New-CippUser.ps1 index eb2632bf4363..234c9392ba03 100644 --- a/Modules/CIPPCore/Public/New-CippUser.ps1 +++ b/Modules/CIPPCore/Public/New-CippUser.ps1 @@ -5,7 +5,7 @@ function New-CIPPUser { $Aliases = 'Scheduled', $RestoreValues, $APIName = 'New User', - $ExecutingUser + $Headers ) try { @@ -38,16 +38,19 @@ function New-CIPPUser { } } if ($userobj.businessPhone) { $bodytoShip | Add-Member -NotePropertyName businessPhones -NotePropertyValue @($UserObj.businessPhone) } - if ($UserObj.defaultAttributes.value) { - [hashtable]($UserObj.defaultAttributes).GetEnumerator() | ForEach-Object { - $results.add("Added property $($_.Key) with value $($_.value)") - $bodytoShip | Add-Member -NotePropertyName $_.Key -NotePropertyValue $_.Value + if ($UserObj.defaultAttributes) { + $UserObj.defaultAttributes | Get-Member -MemberType NoteProperty | ForEach-Object { + Write-Host "Editing user and adding $($_.Name) with value $($UserObj.defaultAttributes.$($_.Name).value)" + if (-not [string]::IsNullOrWhiteSpace($UserObj.defaultAttributes.$($_.Name).value)) { + Write-Host 'adding body to ship' + $BodyToShip | Add-Member -NotePropertyName $_.Name -NotePropertyValue $UserObj.defaultAttributes.$($_.Name).value -Force + } } } $bodyToShip = ConvertTo-Json -Depth 10 -InputObject $BodyToship -Compress Write-Host "Shipping: $bodyToShip" $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/users' -tenantId $UserObj.tenantFilter -type POST -body $BodyToship -verbose - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($UserObj.tenantFilter) -message "Created user $($UserObj.displayname) with id $($GraphRequest.id) " -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($UserObj.tenantFilter) -message "Created user $($UserObj.displayname) with id $($GraphRequest.id) " -Sev 'Info' try { $PasswordLink = New-PwPushLink -Payload $password @@ -63,7 +66,7 @@ function New-CIPPUser { Password = $password } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($UserObj.tenantFilter) -message "Failed to create user. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($UserObj.tenantFilter) -message "Failed to create user. Error:$($_.Exception.Message)" -Sev 'Error' $results = @{ Results = ("Failed to create user. $($_.Exception.Message)" ) } throw "Failed to create user $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 b/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 index 3c0d9c326024..0fa8eab58997 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 @@ -5,18 +5,18 @@ function Remove-CIPPCalendarInvites { $tenantFilter, $username, $APIName = 'Remove Calendar Invites', - $ExecutingUser + $Headers ) try { New-ExoRequest -tenantid $tenantFilter -cmdlet 'Remove-CalendarEvents' -Anchor $username -cmdParams @{Identity = $username; QueryWindowInDays = 730 ; CancelOrganizedMeetings = $true ; Confirm = $false } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Cancelled all calendar invites for $($username)" -Sev 'Info' -tenant $tenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Cancelled all calendar invites for $($username)" -Sev 'Info' -tenant $tenantFilter "Cancelled all calendar invites for $($username)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not cancel calendar invites for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $tenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not cancel calendar invites for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $tenantFilter -LogData $ErrorMessage return "Could not cancel calendar invites for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 b/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 index 4dcd10d02988..b356dd990b3a 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 @@ -1,7 +1,7 @@ function Remove-CIPPGroup { [CmdletBinding()] param ( - $ExecutingUser, + $Headers, $GroupType, $ID, $DisplayName, @@ -12,18 +12,18 @@ function Remove-CIPPGroup { try { if ($GroupType -eq 'Distribution List' -or $GroupType -eq 'Mail-Enabled Security') { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-DistributionGroup' -cmdParams @{Identity = $id; BypassSecurityGroupManagerCheck = $true } -useSystemMailbox $true - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev 'Info' return "Successfully Deleted $($GroupType) group $($DisplayName)" } elseif ($GroupType -eq 'Microsoft 365' -or $GroupType -eq 'Security') { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/groups/$($ID)" -tenantid $TenantFilter -type Delete -verbose - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev 'Info' return "Successfully Deleted $($GroupType) group $($DisplayName)" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete $DisplayName. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not delete $DisplayName. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not delete $DisplayName. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 b/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 index c434625a3537..862b4b318610 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 @@ -1,5 +1,5 @@ function Remove-CIPPGroupMember( - [string]$ExecutingUser, + $Headers, [string]$GroupType, [string]$GroupId, [string]$Member, @@ -17,13 +17,13 @@ function Remove-CIPPGroupMember( New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($GroupId)/members/$($Member)/`$ref" -tenantid $TenantFilter -type DELETE -body '{}' -Verbose } $Message = "Successfully removed user $($Member) from $($GroupId)." - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $Message -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message $Message -Sev 'Info' return $message } catch { $ErrorMessage = Get-CippException -Exception $_ $message = "Failed to remove user $($Member) from $($GroupId): $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $message -Sev 'error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message $message -Sev 'error' -LogData $ErrorMessage return $message } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 b/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 index e9cb0b078b23..b7fcec73a316 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 @@ -4,7 +4,7 @@ function Remove-CIPPGroups { $Username, $tenantFilter, $APIName = 'Remove From Groups', - $ExecutingUser, + $Headers, $userid ) @@ -32,17 +32,17 @@ function Remove-CIPPGroups { New-ExoRequest -tenantid $using:tenantFilter -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true } - Write-LogMessage -user $using:ExecutingUser -API $($using:APIName) -message "Removed $($using:Username) from $groupname" -Sev 'Info' -tenant $using:TenantFilter + Write-LogMessage -headers $using:Headers -API $($using:APIName) -message "Removed $($using:Username) from $groupname" -Sev 'Info' -tenant $using:TenantFilter "Successfully removed $($using:Username) from group $Groupname" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $using:ExecutingUser -API $($using:APIName) -message "Could not remove $($using:Username) from group $groupname : $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $using:TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $using:Headers -API $($using:APIName) -message "Could not remove $($using:Username) from group $groupname : $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $using:TenantFilter -LogData $ErrorMessage "Could not remove $($using:Username) from group $($Groupname): $($ErrorMessage.NormalizedError). This is likely because its a Dynamic Group or synched with active directory" } } if (!$Returnval) { $Returnval = "$($Username) is not a member of any groups." - Write-LogMessage -user $ExecutingUser -API $APIName -message "$($Username) is not a member of any groups" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "$($Username) is not a member of any groups" -Sev 'Info' -tenant $TenantFilter } return $Returnval } diff --git a/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 b/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 index 6bf266fc7a7a..30c8e6c10abc 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 @@ -1,7 +1,7 @@ function Remove-CIPPLicense { [CmdletBinding(SupportsShouldProcess = $true)] param ( - $ExecutingUser, + $Headers, $userid, $username, $APIName = 'Remove License', @@ -17,10 +17,10 @@ function Remove-CIPPLicense { value = 'Remove-CIPPLicense' } Parameters = [pscustomobject]@{ - userid = $userid - username = $username - APIName = 'Scheduled License Removal' - ExecutingUser = $ExecutingUser + userid = $userid + username = $username + APIName = 'Scheduled License Removal' + Headers = $Headers } ScheduledTime = [int64](([datetime]::UtcNow).AddMinutes(5) - (Get-Date '1/1/1970')).TotalSeconds PostExecution = @{ @@ -45,16 +45,16 @@ function Remove-CIPPLicense { } if ($PSCmdlet.ShouldProcess($userid, "Remove licenses: $ConvertedLicense")) { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/assignlicense" -tenantid $tenantFilter -type POST -body (ConvertTo-Json -InputObject $LicensePayload -Compress -Depth 5) -verbose - Write-LogMessage -user $ExecutingUser -API $APIName -message "Removed licenses for $($username): $ConvertedLicense" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Removed licenses for $($username): $ConvertedLicense" -Sev 'Info' -tenant $TenantFilter } return "Removed licenses for $($Username): $ConvertedLicense" } else { - Write-LogMessage -user $ExecutingUser -API $APIName -message "No licenses to remove for $username" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "No licenses to remove for $username" -Sev 'Info' -tenant $TenantFilter return "No licenses to remove for $username" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not remove license for $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not remove license for $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not remove license for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 b/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 index 16a2dd352cda..dc934b29088d 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 @@ -6,7 +6,7 @@ function Remove-CIPPMailboxPermissions { $TenantFilter, $PermissionsLevel, $APIName = 'Manage Shared Mailbox Access', - $ExecutingUser + $Headers ) try { @@ -16,7 +16,7 @@ function Remove-CIPPMailboxPermissions { Import-Module '.\Modules\AzBobbyTables' Import-Module '.\Modules\CIPPCore' Write-Host "Removing permissions from mailbox $($_.UserPrincipalName)" - Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid $_.UserPrincipalName -AccessUser $using:AccessUser -TenantFilter $using:TenantFilter -APIName $using:APINAME -ExecutingUser $using:ExecutingUser + Remove-CIPPMailboxPermissions -PermissionsLevel @('FullAccess', 'SendAs', 'SendOnBehalf') -userid $_.UserPrincipalName -AccessUser $using:AccessUser -TenantFilter $using:TenantFilter -APIName $using:APINAME -Headers $using:Headers } -ThrottleLimit 10 } else { $Results = $PermissionsLevel | ForEach-Object { @@ -24,14 +24,14 @@ function Remove-CIPPMailboxPermissions { 'SendOnBehalf' { $MailboxPerms = New-ExoRequest -Anchor $UserId -tenantid $Tenantfilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; GrantSendonBehalfTo = @{'@odata.type' = '#Exchange.GenericHashTable'; remove = $AccessUser }; } if ($MailboxPerms -notlike '*completed successfully but no settings of*') { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Removed SendOnBehalf permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Removed SendOnBehalf permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter "Removed SendOnBehalf permissions for $($AccessUser) from $($userid)'s mailbox." } } 'SendAS' { $MailboxPerms = New-ExoRequest -Anchor $userId -tenantid $Tenantfilter -cmdlet 'Remove-RecipientPermission' -cmdParams @{Identity = $userid; Trustee = $AccessUser; accessRights = @('SendAs') } if ($MailboxPerms -notlike "*because the ACE isn't present*") { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Removed SendAs permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Removed SendAs permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter "Removed SendAs permissions for $($AccessUser) from $($userid)'s mailbox." } } @@ -50,7 +50,7 @@ function Remove-CIPPMailboxPermissions { $permissions = New-ExoRequest @ExoRequest if ($permissions -notlike "*because the ACE doesn't exist on the object.*") { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Removed FullAccess permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Removed FullAccess permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter "Removed FullAccess permissions for $($AccessUser) from $($userid)'s mailbox." } } @@ -60,7 +60,7 @@ function Remove-CIPPMailboxPermissions { return $Results } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not remove mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not remove mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not remove mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPMailboxRule.ps1 b/Modules/CIPPCore/Public/Remove-CIPPMailboxRule.ps1 index 82fa745d6f83..47b494ac4b7c 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPMailboxRule.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPMailboxRule.ps1 @@ -5,7 +5,7 @@ function Remove-CIPPMailboxRule { $username, $TenantFilter, $APIName = 'Mailbox Rules Removal', - $ExecutingUser, + $Headers, $RuleId, $RuleName, [switch]$RemoveAllRules @@ -18,29 +18,29 @@ function Remove-CIPPMailboxRule { $rules = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-InboxRule' -cmdParams @{Mailbox = $username; IncludeHidden = $true } | Where-Object { $_.Name -ne 'Junk E-Mail Rule' -and $_.Name -notlike 'Microsoft.Exchange.OOF.*' } Write-Host "$($rules.count) rules found" if ($null -eq $rules) { - Write-LogMessage -user $ExecutingUser -API $APIName -message "No Rules for $($username) to delete" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "No Rules for $($username) to delete" -Sev 'Info' -tenant $TenantFilter return "No rules for $($username) to delete" } else { ForEach ($rule in $rules) { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-InboxRule' -Anchor $username -cmdParams @{Identity = $rule.Identity } } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Deleted Rules for $($username)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Deleted Rules for $($username)" -Sev 'Info' -tenant $TenantFilter return "Deleted Rules for $($username)" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete rules for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not delete rules for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not delete rules for $($username). Error: $($ErrorMessage.NormalizedError)" } } else { # Only delete 1 rule try { $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-InboxRule' -Anchor $username -cmdParams @{Identity = $RuleId } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Deleted mailbox rule $($RuleName) for $($username)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Deleted mailbox rule $($RuleName) for $($username)" -Sev 'Info' -tenant $TenantFilter return "Deleted mailbox rule $($RuleName) for $($username)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete rule for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not delete rule for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not delete rule for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 b/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 index 54706e3e97f3..d1d0a8cb45ba 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 @@ -5,7 +5,7 @@ function Remove-CIPPMobileDevice { $tenantFilter, $username, $APIName = 'Remove Mobile', - $ExecutingUser + $Headers ) try { @@ -18,11 +18,11 @@ function Remove-CIPPMobileDevice { } } if (!$Devices) { $Devices = 'No mobile devices have been removed as we could not find any' } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Deleted mobile devices for $($username)" -Sev 'Info' -tenant $tenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Deleted mobile devices for $($username)" -Sev 'Info' -tenant $tenantFilter return $devices } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete mobile devices for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $tenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not delete mobile devices for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $tenantFilter -LogData $ErrorMessage return "Could not delete mobile devices for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 b/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 index f144b7f1213f..b789f5943fc5 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 @@ -1,7 +1,7 @@ function Remove-CIPPUser { [CmdletBinding()] param ( - $ExecutingUser, + $Headers, $userid, $username, $APIName = 'Remove User', @@ -10,12 +10,12 @@ function Remove-CIPPUser { try { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $ExecutingUser, -API $APIName -message "Deleted account $username" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers, -API $APIName -message "Deleted account $username" -Sev 'Info' -tenant $TenantFilter return "Deleted the user account $username" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser, -API $APIName -message "Could not delete $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers, -API $APIName -message "Could not delete $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not delete $username. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPUserMFA.ps1 b/Modules/CIPPCore/Public/Remove-CIPPUserMFA.ps1 index 6056c62511c5..2d9efd1e30e2 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPUserMFA.ps1 @@ -23,14 +23,14 @@ function Remove-CIPPUserMFA { [Parameter(Mandatory = $true)] [string]$TenantFilter, [Parameter(Mandatory = $false)] - [string]$ExecutingUser = 'CIPP' + $Headers ) Write-Information "Getting auth methods for $UserPrincipalName" try { $AuthMethods = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/authentication/methods" -tenantid $TenantFilter -AsApp $true } catch { - Write-LogMessage -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "Failed to get MFA methods for user $UserPrincipalName" -sev 'Error' -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Headers -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "Failed to get MFA methods for user $UserPrincipalName" -sev 'Error' -LogData (Get-CippException -Exception $_) return "Failed to get MFA methods for user $UserPrincipalName - $($_.Exception.Message)" } $Requests = [System.Collections.Generic.List[object]]::new() @@ -45,17 +45,17 @@ function Remove-CIPPUserMFA { } } if (($Requests | Measure-Object).Count -eq 0) { - Write-LogMessage -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "No MFA methods found for user $UserPrincipalName" -sev 'Info' + Write-LogMessage -headers $Headers -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "No MFA methods found for user $UserPrincipalName" -sev 'Info' $Results = "No MFA methods found for user $($UserPrincipalName)" } else { if ($PSCmdlet.ShouldProcess("Remove MFA methods for $UserPrincipalName")) { $Results = New-GraphBulkRequest -Requests $Requests -tenantid $TenantFilter -asapp $true -erroraction stop if ($Results.status -eq 204) { - Write-LogMessage -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "Successfully removed MFA methods for user $UserPrincipalName" -sev 'Info' + Write-LogMessage -headers $Headers -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "Successfully removed MFA methods for user $UserPrincipalName" -sev 'Info' $Results = [pscustomobject]@{'Results' = "Successfully completed request. User $($Request.Query.ID) must supply MFA at next logon" } } else { $FailedAuthMethods = (($Results | Where-Object { $_.status -ne 204 }).id -split '-')[0] -join ', ' - Write-LogMessage -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "Failed to remove MFA methods for $FailedAuthMethods" -sev 'Error' + Write-LogMessage -headers $Headers -API 'Remove-CIPPUserMFA' -tenant $TenantFilter -message "Failed to remove MFA methods for $FailedAuthMethods" -sev 'Error' $Results = "Failed to reset MFA methods for $FailedAuthMethods" } } diff --git a/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 b/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 index ec686280b938..46514ac6dd14 100644 --- a/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 +++ b/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 @@ -5,7 +5,7 @@ function Request-CIPPSPOPersonalSite { [string]$TenantFilter, [Parameter(Mandatory = $true)] [string[]]$UserEmails, - [string]$ExecutingUser = 'CIPP', + [string]$Headers = 'CIPP', [string]$APIName = 'Request-CIPPSPOPersonalSite' ) $UserList = [System.Collections.Generic.List[string]]::new() @@ -42,11 +42,11 @@ function Request-CIPPSPOPersonalSite { try { $Request = New-GraphPostRequest -scope "$AdminURL/.default" -tenantid $TenantFilter -Uri "$AdminURL/_vti_bin/client.svc/ProcessQuery" -Type POST -Body $XML -ContentType 'text/xml' if (!$Request.IsComplete) { throw } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Requested personal site for $($UserEmails -join ', ')" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Requested personal site for $($UserEmails -join ', ')" -Sev 'Info' -tenant $TenantFilter return "Requested personal site for $($UserEmails -join ', ')" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not request personal site for $($UserEmails -join ', '). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not request personal site for $($UserEmails -join ', '). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not request personal site for $($UserEmails -join ', '). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 b/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 index a20a0df59c8e..82ee5126cd4c 100644 --- a/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 +++ b/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 @@ -1,7 +1,7 @@ function Revoke-CIPPSessions { [CmdletBinding()] param ( - $ExecutingUser, + $Headers, $userid, $username, $APIName = 'Revoke Sessions', @@ -10,12 +10,12 @@ function Revoke-CIPPSessions { try { $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/invalidateAllRefreshTokens" -tenantid $TenantFilter -type POST -body '{}' -verbose - Write-LogMessage -user $ExecutingUser -API $APIName -message "Revoked sessions for $($username)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Revoked sessions for $($username)" -Sev 'Info' -tenant $TenantFilter return "Success. All sessions by $username have been revoked" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to revoke sessions for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Failed to revoke sessions for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Revoke Session Failed: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/SAMManifest.json b/Modules/CIPPCore/Public/SAMManifest.json index c1a3d192fc34..65b801589a7f 100644 --- a/Modules/CIPPCore/Public/SAMManifest.json +++ b/Modules/CIPPCore/Public/SAMManifest.json @@ -87,6 +87,10 @@ "id": "e330c4f0-4170-414e-a55a-2f022ec2b57b", "type": "Role" }, + { + "id": "9255e99d-faf5-445e-bbf7-cb71482737c4", + "type": "Role" + }, { "id": "06a5fe6d-c49d-46a7-b082-56b1b14103c7", "type": "Role" diff --git a/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 b/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 index b81d6ebf6654..3a186dc0b27c 100644 --- a/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 +++ b/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 @@ -8,7 +8,7 @@ function Send-CIPPAlert { $JSONContent, $TenantFilter, $APIName = 'Send Alert', - $ExecutingUser, + $Headers, $TableName, $RowKey = [string][guid]::NewGuid() ) diff --git a/Modules/CIPPCore/Public/Set-CIPPAlwaysShowFrom.ps1 b/Modules/CIPPCore/Public/Set-CIPPAlwaysShowFrom.ps1 index 56a8b2575678..8154ca11443b 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAlwaysShowFrom.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAlwaysShowFrom.ps1 @@ -17,7 +17,7 @@ Function Set-CIPPAlwaysShowFrom { .PARAMETER APIName Specifies the name of the API. The default value is "Always Show From". - .PARAMETER ExecutingUser + .PARAMETER Headers Specifies the user who is executing the function. .PARAMETER AlwaysShowFrom @@ -50,7 +50,7 @@ Function Set-CIPPAlwaysShowFrom { [Parameter(ParameterSetName = 'User')] [Parameter(ParameterSetName = 'AllUsers')] - $ExecutingUser, + $Headers, [Parameter(Mandatory = $true, ParameterSetName = 'User')] [Parameter(Mandatory = $true, ParameterSetName = 'AllUsers')] @@ -63,7 +63,7 @@ Function Set-CIPPAlwaysShowFrom { if ($RunOnAllUsersInTenant.IsPresent -eq $true) { $AllUsers = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-Mailbox' -cmdParams @{ ResultSize = 'Unlimited' } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Setting Always Show From to $AlwaysShowFrom for all $($AllUsers.Count) users in $TenantFilter" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Setting Always Show From to $AlwaysShowFrom for all $($AllUsers.Count) users in $TenantFilter" -Sev 'Info' -tenant $TenantFilter $ErrorCount = 0 foreach ($User in $AllUsers) { try { @@ -73,15 +73,15 @@ Function Set-CIPPAlwaysShowFrom { $ErrorCount++ } } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Set Always Show From to $AlwaysShowFrom for $($AllUsers.Count - $ErrorCount) users in $TenantFilter" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Set Always Show From to $AlwaysShowFrom for $($AllUsers.Count - $ErrorCount) users in $TenantFilter" -Sev 'Info' -tenant $TenantFilter return "Set Always Show From to $AlwaysShowFrom for $($AllUsers.Count - $ErrorCount) users in $TenantFilter" } else { try { $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxMessageConfiguration' -anchor $UserID -cmdParams @{AlwaysShowFrom = $AlwaysShowFrom; Identity = $UserID } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Set Always Show From to $AlwaysShowFrom for $UserID" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Set Always Show From to $AlwaysShowFrom for $UserID" -Sev 'Info' -tenant $TenantFilter } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not set Always Show From to $AlwaysShowFrom for $UserID. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not set Always Show From to $AlwaysShowFrom for $UserID. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not set Always Show From to $AlwaysShowFrom for $UserID. Error: $($ErrorMessage.NormalizedError)" } return "Set Always Show From to $AlwaysShowFrom for $UserID" diff --git a/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 b/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 index d070d7bea3c2..478f1aa6e2b9 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 @@ -7,7 +7,7 @@ function Set-CIPPAssignedApplication { $ApplicationId, $TenantFilter, $APIName = 'Assign Application', - $ExecutingUser + $Headers ) try { @@ -111,12 +111,12 @@ function Set-CIPPAssignedApplication { if ($PSCmdlet.ShouldProcess($GroupName, "Assigning Application $ApplicationId")) { Start-Sleep -Seconds 1 $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($ApplicationId)/assign" -tenantid $TenantFilter -type POST -body ($DefaultAssignmentObject | ConvertTo-Json -Compress -Depth 10) - Write-LogMessage -user $ExecutingUser -API $APIName -message "Assigned Application to $($GroupName)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Assigned Application to $($GroupName)" -Sev 'Info' -tenant $TenantFilter } return "Assigned Application to $($GroupName)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not assign application to $GroupName. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not assign application to $GroupName. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not assign application to $GroupName. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 b/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 index 78a1ee21ea5d..671daa0667fa 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 @@ -7,7 +7,7 @@ function Set-CIPPAssignedPolicy { $TenantFilter, $PlatformType, $APIName = 'Assign Policy', - $ExecutingUser + $Headers ) if (!$PlatformType) { $PlatformType = 'deviceManagement' } try { @@ -76,10 +76,10 @@ function Set-CIPPAssignedPolicy { if ($PSCmdlet.ShouldProcess($GroupName, "Assigning policy $PolicyId")) { Write-Host "https://graph.microsoft.com/beta/$($PlatformType)/$Type('$($PolicyId)')/assign" $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/$($PlatformType)/$Type('$($PolicyId)')/assign" -tenantid $tenantFilter -type POST -body $AssignJSON - Write-LogMessage -user $ExecutingUser -API $APIName -message "Assigned $GroupName to Policy $PolicyId" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Assigned $GroupName to Policy $PolicyId" -Sev 'Info' -tenant $TenantFilter } } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to assign $GroupName to Policy $PolicyId, using Platform $PlatformType and $Type. The error is:$ErrorMessage" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Failed to assign $GroupName to Policy $PolicyId, using Platform $PlatformType and $Type. The error is:$ErrorMessage" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 b/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 index 77cdabfa6374..d3335cc89f35 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 @@ -2,7 +2,7 @@ function Set-CIPPAuthenticationPolicy { [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory = $true)]$Tenant, - [Parameter(Mandatory = $true)][ValidateSet('FIDO2', 'MicrosoftAuthenticator', 'SMS', 'TemporaryAccessPass', 'HardwareOATH', 'softwareOath', 'Voice', 'Email', 'x509Certificate')]$AuthenticationMethodId, + [Parameter(Mandatory = $true)][ValidateSet('FIDO2', 'MicrosoftAuthenticator', 'SMS', 'TemporaryAccessPass', 'HardwareOATH', 'softwareOath', 'Voice', 'Email', 'x509Certificate', 'QRCodePin')]$AuthenticationMethodId, [Parameter(Mandatory = $true)][bool]$Enabled, # true = enabled or false = disabled $MicrosoftAuthenticatorSoftwareOathEnabled, $TAPMinimumLifetime = 60, #Minutes @@ -10,8 +10,10 @@ function Set-CIPPAuthenticationPolicy { $TAPDefaultLifeTime = 60, #minutes $TAPDefaultLength = 8, #TAP password generated length in chars $TAPisUsableOnce = $true, + [Parameter()][ValidateRange(1, 395)]$QRCodeLifetimeInDays = 365, + [Parameter()][ValidateRange(8, 20)]$QRCodePinLength = 8, $APIName = 'Set Authentication Policy', - $ExecutingUser + $Headers ) # Convert bool input to usable string @@ -22,7 +24,7 @@ function Set-CIPPAuthenticationPolicy { $CurrentInfo.state = $State } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Could not get CurrentInfo for $AuthenticationMethodId. Error:$($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Could not get CurrentInfo for $AuthenticationMethodId. Error:$($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage Return "Could not get CurrentInfo for $AuthenticationMethodId. Error:$($ErrorMessage.NormalizedError)" } @@ -55,8 +57,8 @@ function Set-CIPPAuthenticationPolicy { # SMS 'SMS' { if ($State -eq 'enabled') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error - return "Setting $AuthenticationMethodId to enabled is not allowed" + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error + throw "Setting $AuthenticationMethodId to enabled is not allowed" } } @@ -86,16 +88,16 @@ function Set-CIPPAuthenticationPolicy { 'Voice' { # Disallow enabling voice if ($State -eq 'enabled') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error - return "Setting $AuthenticationMethodId to enabled is not allowed" + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error + throw "Setting $AuthenticationMethodId to enabled is not allowed" } } # Email OTP 'Email' { if ($State -eq 'enabled') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error - return "Setting $AuthenticationMethodId to enabled is not allowed" + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error + throw "Setting $AuthenticationMethodId to enabled is not allowed" } } @@ -103,23 +105,31 @@ function Set-CIPPAuthenticationPolicy { 'x509Certificate' { # Nothing special to do here } + + # QR code + 'QRCodePin' { + if ($State -eq 'enabled') { + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Setting $AuthenticationMethodId to enabled is not allowed" -sev Error + throw "Setting $AuthenticationMethodId to enabled is not allowed" + } + } Default { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Somehow you hit the default case with an input of $AuthenticationMethodId . You probably made a typo in the input for AuthenticationMethodId. It`'s case sensitive." -sev Error - return "Somehow you hit the default case with an input of $AuthenticationMethodId . You probably made a typo in the input for AuthenticationMethodId. It`'s case sensitive." + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Somehow you hit the default case with an input of $AuthenticationMethodId . You probably made a typo in the input for AuthenticationMethodId. It`'s case sensitive." -sev Error + throw "Somehow you hit the default case with an input of $AuthenticationMethodId . You probably made a typo in the input for AuthenticationMethodId. It`'s case sensitive." } } # Set state of the authentication method try { if ($PSCmdlet.ShouldProcess($AuthenticationMethodId, "Set state to $State $OptionalLogMessage")) { # Convert body to JSON and send request - $null = New-GraphPostRequest -tenantid $Tenant -Uri "https://graph.microsoft.com/beta/policies/authenticationmethodspolicy/authenticationMethodConfigurations/$AuthenticationMethodId" -Type patch -Body ($CurrentInfo | ConvertTo-Json -Compress -Depth 10) -ContentType 'application/json' - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Set $AuthenticationMethodId state to $State $OptionalLogMessage" -sev Info + $null = New-GraphPostRequest -tenantid $Tenant -Uri "https://graph.microsoft.com/beta/policies/authenticationmethodspolicy/authenticationMethodConfigurations/$AuthenticationMethodId" -Type PATCH -Body (ConvertTo-Json -InputObject $CurrentInfo -Compress -Depth 10) -ContentType 'application/json' + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Set $AuthenticationMethodId state to $State $OptionalLogMessage" -sev Info } return "Set $AuthenticationMethodId state to $State $OptionalLogMessage" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Failed to $State $AuthenticationMethodId Support: $ErrorMessage" -sev Error -LogData $ErrorMessage - return "Failed to $State $AuthenticationMethodId Support. Error: $($ErrorMessage.NormalizedError)" + Write-LogMessage -headers $Headers -API $APIName -tenant $Tenant -message "Failed to $State $AuthenticationMethodId Support: $ErrorMessage" -sev Error -LogData $ErrorMessage + throw "Failed to $State $AuthenticationMethodId Support. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPCAExclusion.ps1 b/Modules/CIPPCore/Public/Set-CIPPCAExclusion.ps1 index 9f66cf3e74c5..ea3ad84de6a5 100644 --- a/Modules/CIPPCore/Public/Set-CIPPCAExclusion.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPCAExclusion.ps1 @@ -6,7 +6,7 @@ function Set-CIPPCAExclusion { $UserID, $PolicyId, $Username, - $executingUser + $Headers ) try { $CheckExististing = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/policies/$($PolicyId)" -tenantid $TenantFilter -AsApp $true @@ -36,9 +36,9 @@ function Set-CIPPCAExclusion { } } "Successfully performed $($ExclusionType) exclusion for $username from policy $($PolicyId)" - Write-LogMessage -user $executingUser -API 'Set-CIPPConditionalAccessExclusion' -message "Successfully performed $($ExclusionType) exclusion for $username from policy $($PolicyId)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API 'Set-CIPPConditionalAccessExclusion' -message "Successfully performed $($ExclusionType) exclusion for $username from policy $($PolicyId)" -Sev 'Info' -tenant $TenantFilter } catch { "Failed to $($ExclusionType) user exclusion for $username from policy $($PolicyId): $($_.Exception.Message)" - Write-LogMessage -user $executingUser -API 'Set-CIPPConditionalAccessExclusion' -message "Failed to $($ExclusionType) user exclusion for $username from policy $($PolicyId): $_" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Headers -API 'Set-CIPPConditionalAccessExclusion' -message "Failed to $($ExclusionType) user exclusion for $username from policy $($PolicyId): $_" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) } } diff --git a/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 b/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 index db069f4f6032..339e4e278a5a 100644 --- a/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 @@ -3,13 +3,13 @@ function Set-CIPPCPVConsent { param( $TenantFilter, $APIName = 'CPV Consent', - $ExecutingUser, + $Headers, [bool]$ResetSP = $false ) $Results = [System.Collections.Generic.List[string]]::new() $Tenant = Get-Tenants -IncludeAll | Where-Object -Property customerId -EQ $TenantFilter | Select-Object -First 1 $TenantName = $Tenant.displayName - $User = $request.headers.'x-ms-client-principal' + $User = $Request.Headers if ($TenantFilter -eq $env:TenantID) { return @('Cannot modify CPV consent on partner tenant') @@ -59,7 +59,7 @@ function Set-CIPPCPVConsent { Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force } $Results.add("Successfully added CPV Application to tenant $($TenantName)") | Out-Null - Write-LogMessage -user $User -API $APINAME -message "Added our Service Principal to $($TenantName)" -Sev 'Info' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter + Write-LogMessage -Headers $User -API $APINAME -message "Added our Service Principal to $($TenantName)" -Sev 'Info' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter } catch { $ErrorMessage = Get-CippException -Exception $_ if ($ErrorMessage.NormalizedError -like '*Permission entry already exists*') { @@ -75,7 +75,7 @@ function Set-CIPPCPVConsent { Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force return @("We've already added our Service Principal to $($TenantName)") } - Write-LogMessage -user $User -API $APINAME -message "Could not add our Service Principal to the client tenant $($TenantName): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Could not add our Service Principal to the client tenant $($TenantName): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter -LogData $ErrorMessage return @("Could not add our Service Principal to the client tenant $($TenantName). Error: $($ErrorMessage.NormalizedError)") } return $Results diff --git a/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 b/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 index bdc0c0cb1409..7225829106e8 100644 --- a/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 @@ -1,7 +1,7 @@ function Set-CIPPCopyGroupMembers { [CmdletBinding(SupportsShouldProcess = $true)] param( - [string]$ExecutingUser, + $Headers, [string]$UserId, [string]$CopyFromId, [string]$TenantFilter, @@ -88,13 +88,13 @@ function Set-CIPPCopyGroupMembers { Add-CIPPScheduledTask -Task $TaskBody -hidden $false $Errors.Add("We've scheduled a task to add $UserId to the Exchange group $($MailGroup.displayName)") | Out-Null } else { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Added $UserId to group $($MailGroup.displayName)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Added $UserId to group $($MailGroup.displayName)" -Sev 'Info' -tenant $TenantFilter $Success.Add("Added user to group: $($MailGroup.displayName)") | Out-Null } } catch { $ErrorMessage = Get-CippException -Exception $_ $Errors.Add("We've failed to add the group $($MailGroup.displayName): $($ErrorMessage.NormalizedError)") | Out-Null - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Group adding failed for group $($_.displayName): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Group adding failed for group $($_.displayName): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 b/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 index ac523c8e1101..f257a9189a6c 100644 --- a/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 @@ -14,12 +14,12 @@ function Set-CIPPDefaultAPDeploymentProfile { $hidePrivacy, $hideTerms, $Autokeyboard, - $ExecutingUser, + $Headers, $Language = 'os-default', $APIName = 'Add Default Enrollment Status Page' ) - $User = $request.headers.'x-ms-client-principal' + $User = $Request.Headers try { $ObjBody = [pscustomobject]@{ @@ -50,7 +50,7 @@ function Set-CIPPDefaultAPDeploymentProfile { if ($_.id -ne $Profiles[0].id) { if ($PSCmdlet.ShouldProcess($_.displayName, 'Delete duplicate Autopilot profile')) { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles/$($_.id)" -tenantid $tenantfilter -type DELETE - Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Deleted duplicate Autopilot profile $($displayname)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APIName -tenant $($tenantfilter) -message "Deleted duplicate Autopilot profile $($displayname)" -Sev 'Info' } } } @@ -60,7 +60,7 @@ function Set-CIPPDefaultAPDeploymentProfile { if ($PSCmdlet.ShouldProcess($displayName, 'Add Autopilot profile')) { $Type = 'Add' $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles' -body $body -tenantid $tenantfilter - Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Added Autopilot profile $($displayname)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APIName -tenant $($tenantfilter) -message "Added Autopilot profile $($displayname)" -Sev 'Info' } } else { $Type = 'Edit' @@ -76,13 +76,13 @@ function Set-CIPPDefaultAPDeploymentProfile { if (!$Assignments) { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles/$($GraphRequest.id)/assignments" -tenantid $tenantfilter -type POST -body $AssignBody } - Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Assigned autopilot profile $($Displayname) to $AssignTo" -Sev 'Info' + Write-LogMessage -Headers $User -API $APIName -tenant $($tenantfilter) -message "Assigned autopilot profile $($Displayname) to $AssignTo" -Sev 'Info' } } "Successfully $($Type)ed profile for $($tenantfilter)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Failed $($Type)ing Autopilot Profile $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APIName -tenant $($tenantfilter) -message "Failed $($Type)ing Autopilot Profile $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage throw "Failed to add profile for $($tenantfilter): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 b/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 index 27ccfec1abde..c0ec587b0433 100644 --- a/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 @@ -10,11 +10,11 @@ function Set-CIPPDefaultAPEnrollment { $TimeOutInMinutes, $AllowFail, $OBEEOnly, - $ExecutingUser, + $Headers, $APIName = 'Add Default Enrollment Status Page' ) - $User = $request.headers.'x-ms-client-principal' + $User = $Request.Headers try { $ObjBody = [pscustomobject]@{ @@ -40,11 +40,11 @@ function Set-CIPPDefaultAPEnrollment { if ($PSCmdlet.ShouldProcess($ExistingStatusPage.ID, 'Set Default Enrollment Status Page')) { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/deviceEnrollmentConfigurations/$($ExistingStatusPage.ID)" -body $body -Type PATCH -tenantid $($TenantFilter) "Successfully changed default enrollment status page for $($($TenantFilter))" - Write-LogMessage -user $User -API $APINAME -tenant $($TenantFilter) -message "Added Autopilot Enrollment Status Page $($Displayname)" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $($TenantFilter) -message "Added Autopilot Enrollment Status Page $($Displayname)" -Sev 'Info' } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $($TenantFilter) -message "Failed adding Autopilot Enrollment Status Page $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $($TenantFilter) -message "Failed adding Autopilot Enrollment Status Page $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage throw "Failed to change default enrollment status page for $($($TenantFilter)): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPDeviceState.ps1 b/Modules/CIPPCore/Public/Set-CIPPDeviceState.ps1 index f9740fb591a7..583dc58983be 100644 --- a/Modules/CIPPCore/Public/Set-CIPPDeviceState.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPDeviceState.ps1 @@ -20,14 +20,14 @@ .PARAMETER TenantFilter Specifies the tenant ID or domain against which to perform the operation. - .PARAMETER ExecutingUser + .PARAMETER Headers Specifies the user who initiated the request for logging purposes. .PARAMETER APIName Specifies the name of the API call for logging purposes. Defaults to 'Set Device State'. .EXAMPLE - Set-CIPPDeviceState -Action Enable -DeviceID "1234abcd-5678-efgh-ijkl-9012mnopqrst" -TenantFilter "contoso.onmicrosoft.com" -ExecutingUser "admin@contoso.onmicrosoft.com" + Set-CIPPDeviceState -Action Enable -DeviceID "1234abcd-5678-efgh-ijkl-9012mnopqrst" -TenantFilter "contoso.onmicrosoft.com" -Headers "admin@contoso.onmicrosoft.com" This command enables the specified device within the given tenant. @@ -49,7 +49,7 @@ [Parameter(Mandatory = $true)]$DeviceID, [Parameter(Mandatory = $true)]$TenantFilter, - $ExecutingUser, + $Headers, $APIName = 'Set Device State' ) $Url = "https://graph.microsoft.com/beta/devices/$($DeviceID)" @@ -67,11 +67,11 @@ } } Write-Host $ActionResult - Write-LogMessage -user $ExecutingUser -API $APIName -message "Executed action $($Action) on $($DeviceID)" -Sev Info + Write-LogMessage -headers $Headers -API $APIName -message "Executed action $($Action) on $($DeviceID)" -Sev Info return "Executed action $($Action) on $($DeviceID)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to queue action $($Action) on $($DeviceID). Error: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Failed to queue action $($Action) on $($DeviceID). Error: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage throw "Failed to queue action $($Action) on $($DeviceID). Error: $($ErrorMessage.NormalizedError)" } diff --git a/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 b/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 index 23bce649ca3e..81e8cf53c9fe 100644 --- a/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 @@ -18,8 +18,8 @@ function Set-CIPPForwarding { .PARAMETER username Username to manage for forwarding. - .PARAMETER ExecutingUser - CIPP user executing the command. + .PARAMETER Headers + CIPP HTTP Request headers. .PARAMETER APIName Name of the API executing the command. @@ -40,7 +40,7 @@ function Set-CIPPForwarding { [string]$forwardingSMTPAddress, [string]$tenantFilter, [string]$username, - [string]$ExecutingUser, + $Headers, [string]$APIName = 'Forwarding', [string]$Forward, $KeepCopy, @@ -63,11 +63,11 @@ function Set-CIPPForwarding { $Message = "Forwarding all email for $username to External Address $ForwardingSMTPAddress and keeping a copy set to $KeepCopy" } } - Write-LogMessage -user $ExecutingUser -API $APIName -message $Message -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message $Message -Sev 'Info' -tenant $TenantFilter return $Message } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add forwarding for $($username). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not add forwarding for $($username). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not add forwarding for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPGDAPAutoExtend.ps1 b/Modules/CIPPCore/Public/Set-CIPPGDAPAutoExtend.ps1 index 4143c122d706..2d8a7dbb7572 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGDAPAutoExtend.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGDAPAutoExtend.ps1 @@ -4,7 +4,7 @@ function Set-CIPPGDAPAutoExtend { $RelationShipid, [switch]$All, $APIName = 'Set GDAP Auto Exension', - $ExecutingUser + $Headers ) $ReturnedData = if ($All -eq $true) { @@ -14,7 +14,7 @@ function Set-CIPPGDAPAutoExtend { $AddedHeader = @{'If-Match' = $Relation.'@odata.etag' } if ($PSCmdlet.ShouldProcess($Relation.id, "Set auto renew for $($Relation.customer.displayName)")) { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships/$($Relation.id)" -tenantid $env:TenantID -type PATCH -body '{"autoExtendDuration":"P180D"}' -Verbose -NoAuthCheck $true -AddedHeaders $AddedHeader - Write-LogMessage -user $ExecutingUser -API $APIName -message "Successfully set auto renew for tenant $($Relation.customer.displayName) with ID $($RelationShipid)" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -message "Successfully set auto renew for tenant $($Relation.customer.displayName) with ID $($RelationShipid)" -Sev 'Info' @("Successfully set auto renew for tenant $($Relation.customer.displayName) with ID $($Relation.id)" ) } } catch { @@ -29,7 +29,7 @@ function Set-CIPPGDAPAutoExtend { $AddedHeader = @{'If-Match' = $Relationship.'@odata.etag' } if ($PSCmdlet.ShouldProcess($RelationShipid, "Set auto renew for $($Relationship.customer.displayName)")) { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships/$($RelationShipid)" -tenantid $env:TenantID -type PATCH -body '{"autoExtendDuration":"P180D"}' -Verbose -NoAuthCheck $true -AddedHeaders $AddedHeader - write-LogMessage -user $ExecutingUser -API $APIName -message "Successfully set auto renew for tenant $($Relationship.customer.displayName) with ID $($RelationShipid)" -Sev 'Info' + write-LogMessage -headers $Headers -API $APIName -message "Successfully set auto renew for tenant $($Relationship.customer.displayName) with ID $($RelationShipid)" -Sev 'Info' @("Successfully set auto renew for tenant $($Relationship.customer.displayName) with ID $($RelationShipid)" ) } } catch { diff --git a/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 b/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 index c5cd14a1a7aa..aebf8b0e83c9 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 @@ -6,7 +6,7 @@ function Set-CIPPGraphSubscription { $Resource, $EventType, $APIName = 'Set Graph Webhook', - $ExecutingUser + $Headers ) if ($RenewSubscriptions) { @@ -26,7 +26,7 @@ function Set-CIPPGraphSubscription { } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to renew Webhook Subscription: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Failed to renew Webhook Subscription: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Failed to renew Webhook Subscription $($WebhookRow.RowKey): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 b/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 index e8d65c89fb5a..6fca31b53dbf 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 @@ -1,5 +1,5 @@ function Set-CIPPGroupAuthentication( - [string]$ExecutingUser, + [string]$Headers, [string]$GroupType, [string]$Id, [string]$OnlyAllowInternalString, @@ -15,15 +15,15 @@ function Set-CIPPGroupAuthentication( } elseif ($GroupType -eq 'Microsoft 365') { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-UnifiedGroup' -cmdParams @{Identity = $Id; RequireSenderAuthenticationEnabled = $OnlyAllowInternal } } elseif ($GroupType -eq 'Security') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message 'This setting cannot be set on a security group.' -Sev 'Error' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message 'This setting cannot be set on a security group.' -Sev 'Error' return "$GroupType's group cannot have this setting changed" } - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id set to allow messages from people $messageSuffix" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "$Id set to allow messages from people $messageSuffix" -Sev 'Info' return "Set $GroupType group $Id to allow messages from people $messageSuffix" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Delivery Management failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Delivery Management failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Failed. $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 b/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 index 0da6ddf798a6..1f2ecb0c07af 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 @@ -1,5 +1,5 @@ function Set-CIPPGroupGAL( - [string]$ExecutingUser, + [string]$Headers, [string]$GroupType, [string]$Id, [string]$HiddenString, @@ -15,15 +15,15 @@ function Set-CIPPGroupGAL( } elseif ($GroupType -eq 'Microsoft 365') { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-UnifiedGroup' -cmdParams @{Identity = $Id; HiddenFromAddressListsEnabled = $Hidden } } elseif ($GroupType -eq 'Security') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message 'This setting cannot be set on a security group.' -Sev 'Error' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message 'This setting cannot be set on a security group.' -Sev 'Error' return "$GroupType's group cannot have this setting changed" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Failed. $($ErrorMessage.NormalizedError)" } - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL" -Sev 'Info' return "Successfully $messageSuffix $GroupType group $Id from GAL." } diff --git a/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 b/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 index be63ce724782..b34daface0e1 100644 --- a/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 @@ -5,16 +5,16 @@ function Set-CIPPHideFromGAL { $TenantFilter, $APIName = 'Hide From Address List', [bool]$HideFromGAL, - $ExecutingUser + $Headers ) $Text = if ($HideFromGAL) { 'hidden' } else { 'unhidden' } try { $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $UserId ; HiddenFromAddressListsEnabled = $HideFromGAL } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($Tenantfilter) -message "$($UserId) $Text from GAL" -Sev Info + Write-LogMessage -headers $Headers -API $APINAME -tenant $($Tenantfilter) -message "$($UserId) $Text from GAL" -Sev Info return "Successfully $Text $($UserId) from GAL." } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not hide $($UserId) from address list. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not hide $($UserId) from address list. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not hide $($UserId) from address list. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 b/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 index 95929155730a..0db2439052a0 100644 --- a/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 @@ -6,7 +6,7 @@ function Set-CIPPIntunePolicy { $DisplayName, $RawJSON, $AssignTo, - $ExecutingUser, + $Headers, $tenantFilter ) $ReturnValue = try { @@ -39,13 +39,13 @@ function Set-CIPPIntunePolicy { $PostType = 'edited' $ExistingID = $CheckExististing | Where-Object -Property displayName -EQ $displayname $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL/$($ExistingID.Id)" -tenantid $tenantFilter -type PATCH -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Updated policy $($DisplayName) to template defaults" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Updated policy $($DisplayName) to template defaults" -Sev 'info' $CreateRequest = $CheckExististing | Where-Object -Property displayName -EQ $DisplayName } else { $RawJSON = ConvertTo-Json -InputObject $JSON -Depth 20 -Compress $PostType = 'added' $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL" -tenantid $tenantFilter -type POST -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' } } 'Admin' { @@ -62,13 +62,13 @@ function Set-CIPPIntunePolicy { $DeleteRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL('$($ExistingID.id)')/updateDefinitionValues" -tenantid $tenantFilter -type POST -body $DeleteJson $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL('$($ExistingID.id)')/updateDefinitionValues" -tenantid $tenantFilter -type POST -body $RawJSON $CreateRequest = $CheckExististing | Where-Object -Property displayName -EQ $DisplayName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Updated policy $($Displayname) to template defaults" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Updated policy $($Displayname) to template defaults" -Sev 'info' $PostType = 'edited' } else { $PostType = 'added' $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL" -tenantid $tenantFilter -type POST -body $CreateBody $UpdateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL('$($CreateRequest.id)')/updateDefinitionValues" -tenantid $tenantFilter -type POST -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Added policy $($Displayname) to template defaults" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Added policy $($Displayname) to template defaults" -Sev 'info' } } @@ -86,11 +86,11 @@ function Set-CIPPIntunePolicy { Write-Host "Raw JSON is $RawJSON" $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL/$($ExistingID.Id)" -tenantid $tenantFilter -type PATCH -body $RawJSON $CreateRequest = $CheckExististing | Where-Object -Property displayName -EQ $DisplayName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Updated policy $($DisplayName) to template defaults" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Updated policy $($DisplayName) to template defaults" -Sev 'info' } else { $PostType = 'added' $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL" -tenantid $tenantFilter -type POST -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' } } @@ -106,7 +106,7 @@ function Set-CIPPIntunePolicy { } else { $PostType = 'added' $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL" -tenantid $tenantFilter -type POST -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' } } 'windowsDriverUpdateProfiles' { @@ -124,22 +124,22 @@ function Set-CIPPIntunePolicy { } else { $PostType = 'added' $CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL" -tenantid $tenantFilter -type POST -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' + Write-LogMessage -headers $Request.Headers -API $APINAME -tenant $($tenantFilter) -message "Added policy $($DisplayName) via template" -Sev 'info' } } } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantFilter) -message "$($PostType) policy $($Displayname)" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($tenantFilter) -message "$($PostType) policy $($Displayname)" -Sev 'Info' if ($AssignTo) { Write-Host "Assigning policy to $($AssignTo) with ID $($CreateRequest.id) and type $TemplateTypeURL for tenant $tenantFilter" Write-Host "ID is $($CreateRequest.id)" - + Set-CIPPAssignedPolicy -GroupName $AssignTo -PolicyId $CreateRequest.id -Type $TemplateTypeURL -TenantFilter $tenantFilter } return "Successfully $($PostType) policy for $($tenantFilter) with display name $($Displayname)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantFilter) -message "Failed $($PostType) policy $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -tenant $($tenantFilter) -message "Failed $($PostType) policy $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage throw "Failed to add or set policy for $($tenantFilter) with display name $($Displayname): $($ErrorMessage.NormalizedError)" } diff --git a/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 b/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 index 1f0f707ee267..9ff552c5a878 100644 --- a/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 @@ -26,7 +26,7 @@ function Set-CIPPIntuneTemplate { GUID = "$GUID" PartitionKey = 'IntuneTemplate' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created intune policy template named $($Request.body.displayname) with GUID $GUID" -Sev 'Debug' + Write-LogMessage -Headers $Request.Headers -API $APINAME -message "Created intune policy template named $($Request.body.displayname) with GUID $GUID" -Sev 'Debug' return 'Successfully added template' } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 index e9efdf9eaa10..7ac44a00b9ee 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 @@ -6,7 +6,7 @@ function Set-CIPPMailboxAccess { [bool]$Automap, $TenantFilter, $APIName = 'Manage Shared Mailbox Access', - $ExecutingUser, + $Headers, [array]$AccessRights ) @@ -14,15 +14,15 @@ function Set-CIPPMailboxAccess { $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Add-MailboxPermission' -cmdParams @{Identity = $userid; user = $AccessUser; automapping = $Automap; accessRights = $AccessRights; InheritanceType = 'all' } -Anchor $userid if ($Automap) { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) with automapping" -Sev 'Info' -tenant $TenantFilter - return "added $($AccessUser) to $($userid) Shared Mailbox with automapping, with the following permissions: $AccessRights" + Write-LogMessage -headers $Headers -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) with automapping" -Sev 'Info' -tenant $TenantFilter + return "Added $($AccessUser) to $($userid) Shared Mailbox with automapping, with the following permissions: $AccessRights" } else { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) without automapping" -Sev 'Info' -tenant $TenantFilter - return "added $($AccessUser) to $($userid) Shared Mailbox without automapping, with the following permissions: $AccessRights" + Write-LogMessage -headers $Headers -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) without automapping" -Sev 'Info' -tenant $TenantFilter + return "Added $($AccessUser) to $($userid) Shared Mailbox without automapping, with the following permissions: $AccessRights" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add mailbox permissions for $($AccessUser) on $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not add mailbox permissions for $($AccessUser) on $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not add shared mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 index 041ce6ec8937..c21505e27310 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 @@ -1,7 +1,7 @@ function Set-CIPPMailboxArchive { [CmdletBinding()] param ( - $ExecutingUser, + $Headers, $userid, $username, $APIName = 'Mailbox Archive', @@ -9,16 +9,16 @@ function Set-CIPPMailboxArchive { [bool]$ArchiveEnabled ) - $User = $request.headers.'x-ms-client-principal' + $User = $Request.Headers Try { if (!$username) { $username = $userid } $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Enable-Mailbox' -cmdParams @{Identity = $userid; Archive = $ArchiveEnabled } "Successfully set archive for $username to $ArchiveEnabled" - Write-LogMessage -user $User -API $APINAME -tenant $($tenantfilter) -message "Successfully set archive for $username to $ArchiveEnabled" -Sev 'Info' + Write-LogMessage -Headers $User -API $APINAME -tenant $($tenantfilter) -message "Successfully set archive for $username to $ArchiveEnabled" -Sev 'Info' } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $($tenantfilter) -message "Failed to set archive for $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $($tenantfilter) -message "Failed to set archive for $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage "Failed. $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxLocale.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxLocale.ps1 index ae7093b7714e..42f922e7891a 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxLocale.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxLocale.ps1 @@ -1,7 +1,7 @@ function Set-CippMailboxLocale { [CmdletBinding()] param ( - $ExecutingUser, + $Headers, $locale, $username, $APIName = 'Mailbox Locale', @@ -14,11 +14,11 @@ function Set-CippMailboxLocale { Language = $locale LocalizeDefaultFolderName = $true } -Anchor $username - Write-LogMessage -user $ExecutingUser -API $APIName -message "set locale for $($username) to a $locale" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "set locale for $($username) to a $locale" -Sev 'Info' -tenant $TenantFilter return "set locale for $($username) to a $locale" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not set locale for $($username). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not set locale for $($username). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not set locale for $username. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 index f139908ade52..cd2ba3313635 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 @@ -1,7 +1,7 @@ function Set-CIPPMailboxType { [CmdletBinding()] param ( - $ExecutingUser, + $Headers, $userid, $username, $APIName = 'Mailbox Conversion', @@ -13,11 +13,11 @@ function Set-CIPPMailboxType { try { if ([string]::IsNullOrWhiteSpace($username)) { $username = $userid } $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; Type = $MailboxType } -Anchor $username - Write-LogMessage -user $ExecutingUser -API $APIName -message "Converted $($username) to a $MailboxType mailbox" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Converted $($username) to a $MailboxType mailbox" -Sev 'Info' -tenant $TenantFilter return "Converted $username to a $MailboxType mailbox" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not convert $username to $MailboxType mailbox. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not convert $username to $MailboxType mailbox. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not convert $username to a $MailboxType mailbox. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPManager.ps1 b/Modules/CIPPCore/Public/Set-CIPPManager.ps1 index 0b7c68c710fc..e9d172853173 100644 --- a/Modules/CIPPCore/Public/Set-CIPPManager.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPManager.ps1 @@ -5,16 +5,16 @@ function Set-CIPPManager { $Manager, $TenantFilter, $APIName = 'Set Manager', - $ExecutingUser + $Headers ) try { $ManagerBody = [PSCustomObject]@{'@odata.id' = "https://graph.microsoft.com/beta/users/$($Manager)" } $ManagerBodyJSON = ConvertTo-Json -Compress -Depth 10 -InputObject $ManagerBody New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($User)/manager/`$ref" -tenantid $TenantFilter -type PUT -body $ManagerBodyJSON -Verbose - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $UserObj.tenantID -message "Set $user's manager to $Manager" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $UserObj.tenantID -message "Set $user's manager to $Manager" -Sev 'Info' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($UserObj.tenantID) -message "Failed to Set Manager. Error:$($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($UserObj.tenantID) -message "Failed to Set Manager. Error:$($_.Exception.Message)" -Sev 'Error' throw "Failed to set manager: $($_.Exception.Message)" } return "Set $user's manager to $Manager" diff --git a/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 b/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 index dae07baf9bf4..8f3e6fe17c33 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 @@ -5,15 +5,15 @@ function Set-CIPPMessageCopy { $MessageCopyForSentAsEnabled, $TenantFilter, $APIName = 'Manage OneDrive Access', - $ExecutingUser + $Headers ) Try { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; MessageCopyForSentAsEnabled = $MessageCopyForSentAsEnabled } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "Successfully set MessageCopyForSentAsEnabled as $MessageCopyForSentAsEnabled on $($userid)." -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $($tenantfilter) -message "Successfully set MessageCopyForSentAsEnabled as $MessageCopyForSentAsEnabled on $($userid)." -Sev 'Info' return "Successfully set MessageCopyForSentAsEnabled as $MessageCopyForSentAsEnabled on $($userid)." } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -tenant $($tenantfilter) -message "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed - $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 b/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 index 830a02cd2564..9726efad1b3f 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 @@ -1,5 +1,5 @@ function Set-CIPPMobileDevice( - [string]$ExecutingUser, + [string]$Headers, [string]$Quarantine, [string]$UserId, [string]$DeviceId, @@ -12,20 +12,20 @@ function Set-CIPPMobileDevice( try { if ($Quarantine -eq 'false') { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-CASMailbox' -cmdParams @{Identity = $UserId; ActiveSyncAllowedDeviceIDs = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $DeviceId } } - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Allow Active Sync Device for $UserId" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Allow Active Sync Device for $UserId" -Sev 'Info' return "Allowed Active Sync Device for $UserId" } elseif ($Quarantine -eq 'true') { New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-CASMailbox' -cmdParams @{Identity = $UserId; ActiveSyncBlockedDeviceIDs = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $DeviceId } } - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Blocked Active Sync Device for $UserId" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Blocked Active Sync Device for $UserId" -Sev 'Info' return "Blocked Active Sync Device for $UserId" } } catch { $ErrorMessage = Get-CippException -Exception $_ if ($Quarantine -eq 'false') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to Allow Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Failed to Allow Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Failed to Allow Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" } elseif ($Quarantine -eq 'true') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to Block Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Failed to Block Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Failed to Block Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" } } @@ -33,12 +33,12 @@ function Set-CIPPMobileDevice( try { if ($Delete -eq 'true') { New-ExoRequest -tenant $TenantFilter -cmdlet 'Remove-MobileDevice' -cmdParams @{Identity = $Guid; Confirm = $false } -UseSystemMailbox $true - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Deleted Active Sync Device for $UserId" -Sev 'Info' + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Deleted Active Sync Device for $UserId" -Sev 'Info' return "Deleted Active Sync Device for $UserId" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to delete Mobile Device $($Guid): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -tenant $TenantFilter -message "Failed to delete Mobile Device $($Guid): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return "Failed to delete Mobile Device $($Guid): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPNamedLocation.ps1 b/Modules/CIPPCore/Public/Set-CIPPNamedLocation.ps1 index 2a5eb8477915..3f23365c31be 100644 --- a/Modules/CIPPCore/Public/Set-CIPPNamedLocation.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPNamedLocation.ps1 @@ -8,7 +8,7 @@ function Set-CIPPNamedLocation { $change, $content, $APIName = 'Set Named Location', - $ExecutingUser + $Headers ) try { @@ -36,12 +36,12 @@ function Set-CIPPNamedLocation { } $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/namedLocations/$NamedLocationId" -tenantid $TenantFilter -type PATCH -body $($NamedLocations | ConvertTo-Json -Compress -Depth 10) - Write-LogMessage -user $ExecutingUser -API $APIName -message "Edited named location. Change: $change with content $($content)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Edited named location. Change: $change with content $($content)" -Sev 'Info' -tenant $TenantFilter } return "Edited named location. Change: $change with content $($content)" } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to edit named location: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Failed to edit named location: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Failed to edit named location. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 b/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 index 116c503486c1..7581fc0c2286 100644 --- a/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 @@ -7,7 +7,7 @@ function Set-CIPPOutOfOffice { $TenantFilter, $State, $APIName = 'Set Out of Office', - $ExecutingUser, + $Headers, $StartTime, $EndTime ) @@ -21,16 +21,16 @@ function Set-CIPPOutOfOffice { } if ($State -ne 'Scheduled') { $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid; AutoReplyState = $State; InternalMessage = $InternalMessage; ExternalMessage = $ExternalMessage } -Anchor $userid - Write-LogMessage -user $ExecutingUser -API $APIName -message "Set Out-of-office for $($userid) to $state" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Set Out-of-office for $($userid) to $state" -Sev 'Info' -tenant $TenantFilter return "Set Out-of-office for $($userid) to $state." } else { $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid; AutoReplyState = $State; InternalMessage = $InternalMessage; ExternalMessage = $ExternalMessage; StartTime = $StartTime; EndTime = $EndTime } -Anchor $userid - Write-LogMessage -user $ExecutingUser -API $APIName -message "Scheduled Out-of-office for $($userid) between $StartTime and $EndTime" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Scheduled Out-of-office for $($userid) between $StartTime and $EndTime" -Sev 'Info' -tenant $TenantFilter return "Scheduled Out-of-office for $($userid) between $($StartTime.toString()) and $($EndTime.toString())" } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not add out of office message for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 b/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 index f1fd6b5c2121..0cb76246c828 100644 --- a/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 @@ -15,11 +15,11 @@ function Set-CIPPPerUserMFA { .PARAMETER State State to set the user to (enabled, disabled, enforced) - .PARAMETER executingUser + .PARAMETER Headers User executing the command .EXAMPLE - Set-CIPPPerUserMFA -TenantFilter 'contoso.onmicrosoft.com' -userId user@contoso.onmicrosoft.com -State 'disabled' -executingUser 'mspuser@partner.com' + Set-CIPPPerUserMFA -TenantFilter 'contoso.onmicrosoft.com' -userId user@contoso.onmicrosoft.com -State 'disabled' -Headers 'mspuser@partner.com' #> [CmdletBinding()] param( @@ -29,7 +29,7 @@ function Set-CIPPPerUserMFA { [string[]]$userId, [ValidateSet('enabled', 'disabled', 'enforced')] $State = 'enabled', - [string]$executingUser = 'CIPP' + [string]$Headers = 'CIPP' ) try { $int = 0 @@ -61,10 +61,10 @@ function Set-CIPPPerUserMFA { } } Set-CIPPUserSchemaProperties -TenantFilter $TenantFilter -Users $Users - Write-LogMessage -user $executingUser -API 'Set-CIPPPerUserMFA' -message "Successfully set Per user MFA State to $State for $id" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API 'Set-CIPPPerUserMFA' -message "Successfully set Per user MFA State to $State for $id" -Sev 'Info' -tenant $TenantFilter } catch { $ErrorMessage = Get-CippException -Exception $_ "Failed to set MFA State for $id. Error: $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $executingUser -API 'Set-CIPPPerUserMFA' -message "Failed to set MFA State to $State for $id. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API 'Set-CIPPPerUserMFA' -message "Failed to set MFA State to $State for $id. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 b/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 index fb829701390c..3069799de39f 100644 --- a/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 @@ -7,16 +7,16 @@ function Set-CIPPProfilePhoto { $type = 'users', $ContentType = 'image/png', $PhotoBase64, - $executingUser + $Headers ) try { $PhotoBytes = [Convert]::FromBase64String($PhotoBase64) New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/$type/$id/photo/`$value" -tenantid $tenantfilter -type PUT -body $PhotoBytes -ContentType $ContentType "Successfully set profile photo for $id" - Write-LogMessage -user $executingUser -API 'Set-CIPPUserProfilePhoto' -message "Successfully set profile photo for $id" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API 'Set-CIPPUserProfilePhoto' -message "Successfully set profile photo for $id" -Sev 'Info' -tenant $TenantFilter } catch { $ErrorMessage = Get-CippException -Exception $_ "Failed to set profile photo for $id. Error: $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $executingUser -API 'Set-CIPPUserProfilePhoto' -message "Failed to set profile photo for $id. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API 'Set-CIPPUserProfilePhoto' -message "Failed to set profile photo for $id. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 b/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 index fbe745f55981..74d248789127 100644 --- a/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 @@ -4,7 +4,7 @@ function Set-CIPPResetPassword { $userid, $tenantFilter, $APIName = 'Reset Password', - $ExecutingUser, + $Headers, [bool]$forceChangePasswordNextSignIn = $true ) @@ -25,7 +25,7 @@ function Set-CIPPResetPassword { if ($PasswordLink) { $password = $PasswordLink } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn" -Sev 'Info' -tenant $TenantFilter if ($UserDetails.onPremisesSyncEnabled -eq $true) { return [pscustomobject]@{ resultText = "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn. The new password is $password. WARNING: This user is AD synced. Please confirm passthrough or writeback is enabled." @@ -40,7 +40,7 @@ function Set-CIPPResetPassword { } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not reset password for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not reset password for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return [pscustomobject]@{ resultText = "Could not reset password for $($userid). Error: $($ErrorMessage.NormalizedError)" state = 'Error' diff --git a/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 b/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 index 54f1a49222da..66a87747b371 100644 --- a/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 @@ -6,7 +6,7 @@ function Set-CIPPSharePointPerms { $TenantFilter, $APIName = 'Manage SharePoint Owner', $RemovePermission, - $ExecutingUser, + $Headers, $URL ) if ($RemovePermission -eq $true) { @@ -43,16 +43,16 @@ function Set-CIPPSharePointPerms { # Write-Host $($request) if (!$request.ErrorInfo.ErrorMessage) { $Message = "$($OnedriveAccessUser) has been $($RemovePermission ? 'removed from' : 'given') access to $URL" - Write-LogMessage -user $ExecutingUser -API $APIName -message $Message -Sev Info -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message $Message -Sev Info -tenant $TenantFilter return $Message } else { $message = "Failed to change access: $($request.ErrorInfo.ErrorMessage)" - Write-LogMessage -user $ExecutingUser -API $APIName -message $message -Sev Error -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message $message -Sev Error -tenant $TenantFilter throw $Message } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add new owner to $($OnedriveAccessUser) on $URL. Error: $($ErrorMessage.NormalizedError)" -Sev Error -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not add new owner to $($OnedriveAccessUser) on $URL. Error: $($ErrorMessage.NormalizedError)" -Sev Error -tenant $TenantFilter -LogData $ErrorMessage return "Could not add owner for $($URL). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 b/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 index 793f8f6f8c6a..f3a51da6934b 100644 --- a/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 @@ -5,7 +5,7 @@ function Set-CIPPSignInState { [bool]$AccountEnabled, $TenantFilter, $APIName = 'Disable User Sign-in', - $ExecutingUser + $Headers ) try { @@ -15,7 +15,7 @@ function Set-CIPPSignInState { $body = ConvertTo-Json -InputObject $body -Compress -Depth 5 $UserDetails = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)?`$select=onPremisesSyncEnabled" -noPagination $true -tenantid $TenantFilter -verbose $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)" -tenantid $TenantFilter -type PATCH -body $body -verbose - Write-LogMessage -user $ExecutingUser -API $APIName -message "Set account enabled state to $AccountEnabled for $UserId" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Set account enabled state to $AccountEnabled for $UserId" -Sev 'Info' -tenant $TenantFilter if ($UserDetails.onPremisesSyncEnabled -eq $true) { return 'WARNING: User is AD Sync enabled. Please enable/disable in AD.' @@ -25,7 +25,7 @@ function Set-CIPPSignInState { } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not disable sign in for $UserId. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not disable sign in for $UserId. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not disable $UserId. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 b/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 index 81a985bf6d36..441854f5e831 100644 --- a/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 @@ -7,7 +7,7 @@ function Set-CIPPSignature { $TenantFilter, $State, $APIName = 'Set Outlook Roaming Signature', - $ExecutingUser, + $Headers, $StartTime, $EndTime ) @@ -17,12 +17,12 @@ function Set-CIPPSignature { [{"name":"Roaming_New_Signature","itemClass":"","id":"","scope":"AdeleV@M365x42953883.OnMicrosoft.com","parentSetting":"","secondaryKey":"","type":"String","timestamp":638296273181532792,"metadata":"","value":"Kelvin","isFirstSync":"true","source":"UserOverride"}] '@ $null = New-GraphPostRequest -uri 'https://substrate.office.com/ows/beta/outlookcloudsettings/settings/global' -tenantid $TenantFilter -type PATCH -contentType 'application/json' -verbose -scope 'https://outlook.office.com/.default' - Write-LogMessage -user $ExecutingUser -API $APIName -message "Set Out-of-office for $($userid) to $state" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Set Out-of-office for $($userid) to $state" -Sev 'Info' -tenant $TenantFilter return "Set Out-of-office for $($userid) to $state." } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage return "Could not add out of office message for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 b/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 index 51da2f11d762..22c1bd20a9a7 100644 --- a/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 @@ -22,7 +22,7 @@ function Set-CIPPUserJITAdmin { DateTime for expiration .EXAMPLE - Set-CIPPUserJITAdmin -TenantFilter 'contoso.onmicrosoft.com' -User @{UserPrincipalName = 'jit@contoso.onmicrosoft.com'} -Roles @('62e90394-69f5-4237-9190-012177145e10') -Action 'AddRoles' -Expiration (Get-Date).AddDays(1) + Set-CIPPUserJITAdmin -TenantFilter 'contoso.onmicrosoft.com' -Headers@{UserPrincipalName = 'jit@contoso.onmicrosoft.com'} -Roles @('62e90394-69f5-4237-9190-012177145e10') -Action 'AddRoles' -Expiration (Get-Date).AddDays(1) #> [CmdletBinding(SupportsShouldProcess = $true)] diff --git a/Modules/CIPPCore/Public/Set-CIPPUserLicense.ps1 b/Modules/CIPPCore/Public/Set-CIPPUserLicense.ps1 index 029310ad772c..382869c4f52a 100644 --- a/Modules/CIPPCore/Public/Set-CIPPUserLicense.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPUserLicense.ps1 @@ -30,10 +30,10 @@ function Set-CIPPUserLicense { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$UserId/assignLicense" -tenantid $TenantFilter -type POST -body $LicenseBodyJson -Verbose } catch { $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 + Write-LogMessage -Headers $Request.Headers -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' + Write-LogMessage -Headers $Request.Headers -API $APIName -tenant $TenantFilter -message "Assigned licenses to user $UserId. Added: $AddLicenses; Removed: $RemoveLicenses" -Sev 'Info' return 'Set licenses successfully' } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuthMethodsSettings.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuthMethodsSettings.ps1 new file mode 100644 index 000000000000..b379d603c4b4 --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuthMethodsSettings.ps1 @@ -0,0 +1,98 @@ +function Invoke-CIPPStandardAuthMethodsSettings { + <# + .FUNCTIONALITY + Internal + .COMPONENT + (APIName) AuthMethodsSettings + .SYNOPSIS + (Label) Configure Authentication Methods Policy Settings + .DESCRIPTION + (Helptext) Configures the report suspicious activity settings and system credential preferences in the authentication methods policy + (DocsDescription) This standard allows you to configure the reportSuspiciousActivitySettings and systemCredentialPreferences properties within the authentication methods policy. + .NOTES + CAT + Entra Standards + TAG + "lowimpact" + ADDEDCOMPONENT + {"type":"autoComplete","multiple":false,"name":"standards.AuthMethodsSettings.ReportSuspiciousActivity","label":"Report Suspicious Activity Settings","options":[{"label":"Default","value":"default"},{"label":"Enabled","value":"enabled"},{"label":"Disabled","value":"disabled"}]} + {"type":"autoComplete","multiple":false,"name":"standards.AuthMethodsSettings.SystemCredential","label":"System Credential Preferences","options":[{"label":"Default","value":"default"},{"label":"Enabled","value":"enabled"},{"label":"Disabled","value":"disabled"}]} + IMPACT + Low Impact + POWERSHELLEQUIVALENT + Update-MgBetaPolicyAuthenticationMethodPolicy + .LINK + https://docs.cipp.app/user-documentation/tenant/standards/list-standards/global-standards#low-impact + #> + + param($Tenant, $Settings) + + Write-Host 'Time to run' + # Get current authentication methods policy + try { + $CurrentPolicy = New-GraphGetRequest -Uri 'https://graph.microsoft.com/beta/policies/authenticationMethodsPolicy' -tenantid $Tenant -AsApp $true + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -API 'Standards' -tenant $tenant -message 'Failed to get authentication methods policy' -sev Error -LogData $ErrorMessage + return + } + + if ($Settings.report -eq $true) { + Add-CIPPBPAField -FieldName 'ReportSuspiciousActivity' -FieldValue $CurrentPolicy.reportSuspiciousActivitySettings.state -StoreAs string -Tenant $tenant + Add-CIPPBPAField -FieldName 'SystemCredential' -FieldValue $CurrentPolicy.systemCredentialPreferences.state -StoreAs string -Tenant $tenant + } + # Set wanted states + $ReportSuspiciousActivityState = $Settings.ReportSuspiciousActivity.value ?? $Settings.ReportSuspiciousActivity + $SystemCredentialState = $Settings.SystemCredential.value ?? $Settings.SystemCredential + + # Input validation + $ValidStates = @('default', 'enabled', 'disabled') + if (($Settings.remediate -eq $true -or $Settings.alert -eq $true) -and + ($ReportSuspiciousActivityState -notin $ValidStates -or $SystemCredentialState -notin $ValidStates)) { + Write-Host "ReportSuspiciousActivity: $($ReportSuspiciousActivityState)" + Write-Host "SystemCredential: $($SystemCredentialState)" + Write-LogMessage -API 'Standards' -tenant $tenant -message 'AuthMethodsPolicy: Invalid state parameter set' -sev Error + return + } + + + + # Check if states are set correctly + $ReportSuspiciousActivityCorrect = if ($CurrentPolicy.reportSuspiciousActivitySettings.state -eq $ReportSuspiciousActivityState) { $true } else { $false } + $SystemCredentialCorrect = if ($CurrentPolicy.systemCredentialPreferences.state -eq $SystemCredentialState) { $true } else { $false } + $StateSetCorrectly = $ReportSuspiciousActivityCorrect -and $SystemCredentialCorrect + + if ($Settings.remediate -eq $true) { + Write-Host 'Time to remediate' + if ($StateSetCorrectly -eq $false) { + try { + $body = [PSCustomObject]@{ + reportSuspiciousActivitySettings = $CurrentPolicy.reportSuspiciousActivitySettings + systemCredentialPreferences = $CurrentPolicy.systemCredentialPreferences + } + $body.reportSuspiciousActivitySettings.state = $ReportSuspiciousActivityState + $body.systemCredentialPreferences.state = $SystemCredentialState + + Write-Host "Body: $($body | ConvertTo-Json -Depth 10 -Compress)" + # Update settings + $null = New-GraphPostRequest -tenantid $tenant -Uri 'https://graph.microsoft.com/beta/policies/authenticationMethodsPolicy' -AsApp $true -Type PATCH -Body ($body | ConvertTo-Json -Depth 10 -Compress) -ContentType 'application/json' + Write-LogMessage -API 'Standards' -tenant $tenant -message "Successfully configured authentication methods policy settings: Report Suspicious Activity ($ReportSuspiciousActivityState), System Credential Preferences ($SystemCredentialState)" -sev Info + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -API 'Standards' -tenant $tenant -message 'Failed to configure authentication methods policy settings' -sev Error -LogData $ErrorMessage + } + } else { + Write-LogMessage -API 'Standards' -tenant $tenant -message 'Authentication methods policy settings are already configured correctly' -sev Info + } + } + + if ($Settings.alert -eq $true) { + if ($StateSetCorrectly -eq $true) { + Write-LogMessage -API 'Standards' -tenant $tenant -message "Authentication methods policy settings are correctly configured: Report Suspicious Activity ($ReportSuspiciousActivityState), System Credential Preferences ($SystemCredentialState)" -sev Info + } else { + $CurrentReportState = $CurrentPolicy.reportSuspiciousActivitySettings.state + $CurrentSystemState = $CurrentPolicy.systemCredentialPreferences.state + Write-LogMessage -API 'Standards' -tenant $tenant -message "Authentication methods policy settings are not configured correctly. Current values: Report Suspicious Activity ($CurrentReportState), System Credential Preferences ($CurrentSystemState)" -sev Alert + } + } +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAutoAddProxy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAutoAddProxy.ps1 new file mode 100644 index 000000000000..e74ff3a89996 --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAutoAddProxy.ps1 @@ -0,0 +1,43 @@ +function Invoke-CIPPStandardAutoAddProxy { + param( + $Tenant, + $Settings, + $QueueItem + ) + + if ($Settings.remediate -eq $true) { + $Domains = New-ExoRequest -TenantId $Tenant -Cmdlet 'Get-AcceptedDomain' | Select-Object -ExpandProperty DomainName + + $AllMailboxes = New-ExoRequest -TenantId $Tenant -Cmdlet 'Get-Mailbox' + foreach ($Domain in $Domains) { + $ProcessMailboxes = $AllMailboxes | Where-Object { + $addresses = @($_.EmailAddresses) -replace '^[^:]+:' # remove SPO:, SMTP:, etc. + $hasDomain = $addresses | Where-Object { $_ -like "*@$Domain" } + if ($hasDomain) { return $false } else { return $true } + } + + $bulkRequest = foreach ($Mailbox in $ProcessMailboxes) { + $LocalPart = $Mailbox.UserPrincipalName -split '@' | Select-Object -First 1 + $NewAlias = "$LocalPart@$Domain" + @{ + CmdletInput = @{ + CmdletName = 'Set-Mailbox' + Parameters = @{Identity = $Mailbox.Identity ; EmailAddresses = @{ + '@odata.type' = '#Exchange.GenericHashTable' + Add = "smtp:$NewAlias" + } + } + } + } + } + $BatchResults = New-ExoBulkRequest -tenantid $Tenant -cmdletArray @($bulkRequest) + $BatchResults | ForEach-Object { + if ($_.error) { + $ErrorMessage = Get-CippException -Exception $_.error + Write-Host "Failed to apply new email policy to $($_.target) Error: $($ErrorMessage.NormalizedError)" + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Failed to apply Delegate Sent Items Style to $($_.error.target) Error: $($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage + } + } + } + } +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardConditionalAccessTemplate.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardConditionalAccessTemplate.ps1 index 51182481cfa2..be53a501e8a9 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardConditionalAccessTemplate.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardConditionalAccessTemplate.ps1 @@ -15,7 +15,7 @@ function Invoke-CIPPStandardConditionalAccessTemplate { MULTIPLE True DISABLEDFEATURES - + IMPACT High ADDEDCOMPONENT @@ -39,7 +39,7 @@ function Invoke-CIPPStandardConditionalAccessTemplate { $Table = Get-CippTable -tablename 'templates' $Filter = "PartitionKey eq 'CATemplate' and RowKey eq '$($Setting.TemplateList.value)'" $JSONObj = (Get-CippAzDataTableEntity @Table -Filter $Filter).JSON - $null = New-CIPPCAPolicy -TenantFilter $tenant -state $Setting.state -RawJSON $JSONObj -Overwrite $true -APIName $APIName -ExecutingUser $request.headers.'x-ms-client-principal' -ReplacePattern 'displayName' + $null = New-CIPPCAPolicy -TenantFilter $tenant -state $Setting.state -RawJSON $JSONObj -Overwrite $true -APIName $APIName -Headers $Request.Headers -ReplacePattern 'displayName' } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to create or update conditional access rule $($JSONObj.displayName). Error: $ErrorMessage" -sev 'Error' diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableEmail.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableEmail.ps1 index 1f9d537a015e..42ae78c7a734 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableEmail.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableEmail.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardDisableEmail { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'Email authentication method is already disabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'Email' -Enabled $false + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'Email' -Enabled $false + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableQRCodePin.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableQRCodePin.ps1 new file mode 100644 index 000000000000..98c05fc3c90e --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableQRCodePin.ps1 @@ -0,0 +1,56 @@ +function Invoke-CIPPStandardDisableQRCodePin { + <# + .FUNCTIONALITY + Internal + .COMPONENT + (APIName) DisableQRCodePin + .SYNOPSIS + (Label) Disables QR Code Pin as an MFA method + .DESCRIPTION + (Helptext) This blocks users from using QR Code Pin as an MFA method. If a user only has QR Code Pin as a MFA method, they will be unable to log in. + (DocsDescription) Disables QR Code Pin as an MFA method for the tenant. If a user only has QR Code Pin as a MFA method, they will be unable to sign in. + .NOTES + CAT + Entra (AAD) Standards + TAG + "highimpact" + ADDEDCOMPONENT + IMPACT + High Impact + POWERSHELLEQUIVALENT + Update-MgBetaPolicyAuthenticationMethodPolicyAuthenticationMethodConfiguration + RECOMMENDEDBY + UPDATECOMMENTBLOCK + Run the Tools\Update-StandardsComments.ps1 script to update this comment block + .LINK + https://docs.cipp.app/user-documentation/tenant/standards/list-standards/entra-aad-standards#high-impact + #> + + param($Tenant, $Settings) + + $CurrentState = New-GraphGetRequest -Uri 'https://graph.microsoft.com/beta/policies/authenticationmethodspolicy/authenticationMethodConfigurations/QRCodePin' -tenantid $Tenant + $StateIsCorrect = ($CurrentState.state -eq 'disabled') + + If ($Settings.remediate -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -tenant $tenant -message 'QR Code Pin authentication method is already disabled.' -sev Info + } else { + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'QRCodePin' -Enabled $false + } catch { + } + } + } + + if ($Settings.alert -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -tenant $tenant -message 'QR Code Pin authentication method is not enabled' -sev Info + } else { + Write-LogMessage -API 'Standards' -tenant $tenant -message 'QR Code Pin authentication method is enabled' -sev Alert + } + } + + if ($Settings.report -eq $true) { + Add-CIPPBPAField -FieldName 'DisableQRCodePin' -FieldValue $StateIsCorrect -StoreAs bool -Tenant $tenant + } +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableSMS.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableSMS.ps1 index a948d1d13213..a9a6e9deeff3 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableSMS.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableSMS.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardDisableSMS { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'SMS authentication method is already disabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'SMS' -Enabled $false + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'SMS' -Enabled $false + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableVoice.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableVoice.ps1 index 619b3e11c50b..d52dd3afedd0 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableVoice.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisableVoice.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardDisableVoice { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'Voice authentication method is already disabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'Voice' -Enabled $false + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'Voice' -Enabled $false + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisablex509Certificate.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisablex509Certificate.ps1 index 8d1d0ae0b990..9c3ab1093e0f 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisablex509Certificate.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardDisablex509Certificate.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardDisablex509Certificate { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'x509Certificate authentication method is already disabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'x509Certificate' -Enabled $false + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'x509Certificate' -Enabled $false + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableFIDO2.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableFIDO2.ps1 index 8b71a8f1963a..d76014e535dc 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableFIDO2.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableFIDO2.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardEnableFIDO2 { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'FIDO2 Support is already enabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'Fido2' -Enabled $true + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'Fido2' -Enabled $true + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableHardwareOAuth.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableHardwareOAuth.ps1 index a55d5410612d..4394cf0740cd 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableHardwareOAuth.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableHardwareOAuth.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardEnableHardwareOAuth { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'HardwareOAuth Support is already enabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'HardwareOath' -Enabled $true + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'HardwareOath' -Enabled $true + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGroupTemplate.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGroupTemplate.ps1 index 69d4f18fdb99..cee0f39dc6e3 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGroupTemplate.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGroupTemplate.ps1 @@ -76,7 +76,7 @@ function Invoke-CIPPStandardGroupTemplate { $GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'New-DistributionGroup' -cmdParams $params } } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'Standards' -tenant $tenant -message "Created group $($groupobj.displayname) with id $($GraphRequest.id) " -Sev 'Info' + Write-LogMessage -API 'Standards' -tenant $tenant -message "Created group $($groupobj.displayname) with id $($GraphRequest.id) " -Sev 'Info' } else { if ($groupobj.groupType -in 'Generic', 'azurerole', 'dynamic') { $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($CheckExististing.id)" -tenantid $tenant -type PATCH -body (ConvertTo-Json -InputObject $BodyToship -Depth 10) -verbose @@ -100,7 +100,7 @@ function Invoke-CIPPStandardGroupTemplate { $GraphRequest = New-ExoRequest -tenantid $tenant -cmdlet 'Set-DistributionGroup' -cmdParams $params } } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API 'Standards' -tenant $tenant -message "Group exists $($groupobj.displayname). Updated to latest settings." -Sev 'Info' + Write-LogMessage -API 'Standards' -tenant $tenant -message "Group exists $($groupobj.displayname). Updated to latest settings." -Sev 'Info' } } catch { diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGuestInvite.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGuestInvite.ps1 index e9df84d6f574..5193b69708fb 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGuestInvite.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardGuestInvite.ps1 @@ -19,7 +19,7 @@ function Invoke-CIPPStandardGuestInvite { IMPACT Medium Impact POWERSHELLEQUIVALENT - + RECOMMENDEDBY UPDATECOMMENTBLOCK Run the Tools\Update-StandardsComments.ps1 script to update this comment block @@ -31,8 +31,7 @@ function Invoke-CIPPStandardGuestInvite { $CurrentState = New-GraphGetRequest -Uri 'https://graph.microsoft.com/beta/policies/authorizationPolicy/authorizationPolicy' -tenantid $Tenant - if ($null -eq $Settings.allowInvitesFrom) { $Settings.allowInvitesFrom = 'Everyone' } # none, adminsAndGuestInviters, adminsGuestInvitersAndAllMembers, everyone - $StateIsCorrect = ($CurrentState.allowInvitesFrom -eq $Settings.allowInvitesFrom) + $StateIsCorrect = ($CurrentState.allowInvitesFrom -eq $Settings.allowInvitesFrom.value) if ($Settings.remediate -eq $true) { if ($StateIsCorrect -eq $true) { @@ -46,13 +45,13 @@ function Invoke-CIPPStandardGuestInvite { Type = 'PATCH' ContentType = 'application/json; charset=utf-8' Body = [pscustomobject]@{ - allowInvitesFrom = $Settings.allowInvitesFrom + allowInvitesFrom = $Settings.allowInvitesFrom.value } | ConvertTo-Json -Compress } New-GraphPostRequest @GraphRequest - Write-LogMessage -API 'Standards' -Tenant $Tenant -Message "Successfully updated Guest Invite setting to $($Settings.allowInvitesFrom)" -Sev Info + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message "Successfully updated Guest Invite setting to $($Settings.allowInvitesFrom.value)" -Sev Info } catch { - Write-LogMessage -API 'Standards' -Tenant $Tenant -Message "Failed to update Guest Invite setting to $($Settings.allowInvitesFrom)" -Sev Error -LogData $_ + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message "Failed to update Guest Invite setting to $($Settings.allowInvitesFrom.value)" -Sev Error -LogData $_ } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardIntuneComplianceSettings.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardIntuneComplianceSettings.ps1 index e946ef49cc4f..d8ca6d499c9f 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardIntuneComplianceSettings.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardIntuneComplianceSettings.ps1 @@ -20,7 +20,7 @@ function Invoke-CIPPStandardIntuneComplianceSettings { IMPACT Low Impact POWERSHELLEQUIVALENT - + RECOMMENDEDBY UPDATECOMMENTBLOCK Run the Tools\Update-StandardsComments.ps1 script to update this comment block @@ -32,9 +32,8 @@ function Invoke-CIPPStandardIntuneComplianceSettings { $CurrentState = New-GraphGetRequest -Uri 'https://graph.microsoft.com/beta/deviceManagement/settings' -tenantid $Tenant - if ($null -eq $Settings.secureByDefault) { $Settings.secureByDefault = $true } if ($null -eq $Settings.deviceComplianceCheckinThresholdDays) { $Settings.deviceComplianceCheckinThresholdDays = $CurrentState.deviceComplianceCheckinThresholdDays } - $StateIsCorrect = ($CurrentState.secureByDefault -eq $Settings.secureByDefault) -and + $StateIsCorrect = ($CurrentState.secureByDefault -eq $Settings.secureByDefault.value) -and ($CurrentState.deviceComplianceCheckinThresholdDays -eq $Settings.deviceComplianceCheckinThresholdDays) if ($Settings.remediate -eq $true) { @@ -50,7 +49,7 @@ function Invoke-CIPPStandardIntuneComplianceSettings { ContentType = 'application/json; charset=utf-8' Body = [pscustomobject]@{ settings = [pscustomobject]@{ - secureByDefault = $Settings.secureByDefault + secureByDefault = $Settings.secureByDefault.value deviceComplianceCheckinThresholdDays = $Settings.deviceComplianceCheckinThresholdDays } } | ConvertTo-Json -Compress diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPWdisplayAppInformationRequiredState.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPWdisplayAppInformationRequiredState.ps1 index 1c7005cb470f..8ddea0115551 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPWdisplayAppInformationRequiredState.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPWdisplayAppInformationRequiredState.ps1 @@ -38,7 +38,10 @@ function Invoke-CIPPStandardPWdisplayAppInformationRequiredState { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'Passwordless with Information and Number Matching is already enabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'MicrosoftAuthenticator' -Enabled $true + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'MicrosoftAuthenticator' -Enabled $true + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardRetentionPolicy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardRetentionPolicy.ps1 new file mode 100644 index 000000000000..291e21412a92 --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardRetentionPolicy.ps1 @@ -0,0 +1,86 @@ +function Invoke-CIPPStandardRetentionPolicyTag { + <# + .FUNCTIONALITY + Internal + .COMPONENT + (APIName) RetentionPolicyTag + #> + + param($Tenant, $Settings) + ##$Rerun -Type Standard -Tenant $Tenant -Settings $Settings 'RetentionPolicyTag' + + $PolicyName = 'CIPP Deleted Items' + $CurrentState = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-RetentionPolicyTag' | + Where-Object -Property Identity -EQ $PolicyName + + $PolicyState = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-RetentionPolicy' | + Where-Object -Property Identity -EQ 'Default MRM Policy' + + $StateIsCorrect = ($CurrentState.Name -eq $PolicyName) -and + ($CurrentState.RetentionEnabled -eq $true) -and + ($CurrentState.RetentionAction -eq 'PermanentlyDelete') -and + ($CurrentState.AgeLimitForRetention -eq ([timespan]::FromDays($Settings.AgeLimitForRetention))) -and + ($CurrentState.Type -eq 'DeletedItems') -and + ($PolicyState.RetentionPolicyTagLinks -contains $PolicyName) + + if ($Settings.remediate -eq $true) { + + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -tenant $Tenant -message 'Retention policy tag already correctly configured' -sev Info + } else { + $cmdparams = @{ + RetentionEnabled = $true + AgeLimitForRetention = $Settings.AgeLimitForRetention + RetentionAction = 'PermanentlyDelete' + } + + if ($CurrentState.Name -eq $PolicyName) { + try { + $cmdparams.Add('Identity', $PolicyName) + New-ExoRequest -tenantid $Tenant -cmdlet 'Set-RetentionPolicyTag' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Updated Retention policy tag $PolicyName." -sev Info + } catch { + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Failed to update Retention policy tag $PolicyName." -sev Error -LogData $_ + } + } else { + try { + $cmdparams.Add('Name', $PolicyName) + $cmdparams.Add('Type', 'DeletedItems') + New-ExoRequest -tenantid $Tenant -cmdlet 'New-RetentionPolicyTag' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Created Retention policy tag $PolicyName." -sev Info + } catch { + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Failed to create Retention policy tag $PolicyName." -sev Error -LogData $_ + } + } + + if ($PolicyState.RetentionPolicyTagLinks -notcontains $PolicyName) { + try { + $cmdparams = @{ + Identity = 'Default MRM Policy' + RetentionPolicyTagLinks = @($PolicyState.RetentionPolicyTagLinks + $PolicyName) + } + New-ExoRequest -tenantid $Tenant -cmdlet 'Set-RetentionPolicy' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Added $PolicyName Retention tag to $($PolicyState.Identity)." -sev Info + } catch { + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Failed to add $PolicyName Retention tag to $($PolicyState.Identity)." -sev Error -LogData $_.Exception.Message + } + } + + } + + } + + if ($Settings.alert -eq $true) { + + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -tenant $Tenant -message 'Retention Policy is enabled' -sev Info + } else { + Write-LogMessage -API 'Standards' -tenant $Tenant -message 'Retention Policy is not enabled' -sev Alert + } + } + + if ($Settings.report -eq $true) { + Add-CIPPBPAField -FieldName 'RetentionPolicy' -FieldValue $StateIsCorrect -StoreAs bool -Tenant $tenant + } + +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSafeAttachmentPolicy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSafeAttachmentPolicy.ps1 index a35f420cf73f..d45abf7e5973 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSafeAttachmentPolicy.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSafeAttachmentPolicy.ps1 @@ -64,7 +64,7 @@ function Invoke-CIPPStandardSafeAttachmentPolicy { $StateIsCorrect = ($CurrentState.Name -eq $PolicyName) -and ($CurrentState.Enable -eq $true) -and - ($CurrentState.Action -eq $Settings.Action) -and + ($CurrentState.Action -eq $Settings.SafeAttachmentAction) -and ($CurrentState.QuarantineTag -eq $Settings.QuarantineTag) -and ($CurrentState.Redirect -eq $Settings.Redirect) -and (($null -eq $Settings.RedirectAddress) -or ($CurrentState.RedirectAddress -eq $Settings.RedirectAddress)) @@ -87,7 +87,7 @@ function Invoke-CIPPStandardSafeAttachmentPolicy { } else { $cmdparams = @{ Enable = $true - Action = $Settings.Action + Action = $Settings.SafeAttachmentAction QuarantineTag = $Settings.QuarantineTag Redirect = $Settings.Redirect RedirectAddress = $Settings.RedirectAddress diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 index 4e4bd537aa5e..0a1a86939f08 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 @@ -46,16 +46,16 @@ function Invoke-CIPPStandardSpamFilterPolicy { Select-Object -Property * $StateIsCorrect = ($CurrentState.Name -eq $PolicyName) -and - ($CurrentState.SpamAction -eq $Settings.SpamAction) -and - ($CurrentState.SpamQuarantineTag -eq $Settings.SpamQuarantineTag) -and - ($CurrentState.HighConfidenceSpamAction -eq $Settings.HighConfidenceSpamAction) -and - ($CurrentState.HighConfidenceSpamQuarantineTag -eq $Settings.HighConfidenceSpamQuarantineTag) -and - ($CurrentState.BulkSpamAction -eq $Settings.BulkSpamAction) -and - ($CurrentState.BulkQuarantineTag -eq $Settings.BulkQuarantineTag) -and - ($CurrentState.PhishSpamAction -eq $Settings.PhishSpamAction) -and - ($CurrentState.PhishQuarantineTag -eq $Settings.PhishQuarantineTag) -and + ($CurrentState.SpamAction -eq $Settings.SpamAction.value) -and + ($CurrentState.SpamQuarantineTag -eq $Settings.SpamQuarantineTag.value) -and + ($CurrentState.HighConfidenceSpamAction -eq $Settings.HighConfidenceSpamAction.value) -and + ($CurrentState.HighConfidenceSpamQuarantineTag -eq $Settings.HighConfidenceSpamQuarantineTag.value) -and + ($CurrentState.BulkSpamAction -eq $Settings.BulkSpamAction.value) -and + ($CurrentState.BulkQuarantineTag -eq $Settings.BulkQuarantineTag.value) -and + ($CurrentState.PhishSpamAction -eq $Settings.PhishSpamAction.value) -and + ($CurrentState.PhishQuarantineTag -eq $Settings.PhishQuarantineTag.value) -and ($CurrentState.HighConfidencePhishAction -eq 'Quarantine') -and - ($CurrentState.HighConfidencePhishQuarantineTag -eq $Settings.HighConfidencePhishQuarantineTag) -and + ($CurrentState.HighConfidencePhishQuarantineTag -eq $Settings.HighConfidencePhishQuarantineTag.value) -and ($CurrentState.BulkThreshold -eq $Settings.BulkThreshold) -and ($CurrentState.QuarantineRetentionPeriod -eq 30) -and ($CurrentState.IncreaseScoreWithNumericIps -eq 'On') -and @@ -86,16 +86,16 @@ function Invoke-CIPPStandardSpamFilterPolicy { Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Spam Filter Policy already correctly configured' -sev Info } else { $cmdparams = @{ - SpamAction = $Settings.SpamAction - SpamQuarantineTag = $Settings.SpamQuarantineTag - HighConfidenceSpamAction = $Settings.HighConfidenceSpamAction - HighConfidenceSpamQuarantineTag = $Settings.HighConfidenceSpamQuarantineTag - BulkSpamAction = $Settings.BulkSpamAction - BulkQuarantineTag = $Settings.BulkQuarantineTag - PhishSpamAction = $Settings.PhishSpamAction - PhishQuarantineTag = $Settings.PhishQuarantineTag + SpamAction = $Settings.SpamAction.value + SpamQuarantineTag = $Settings.SpamQuarantineTag.value + HighConfidenceSpamAction = $Settings.HighConfidenceSpamAction.value + HighConfidenceSpamQuarantineTag = $Settings.HighConfidenceSpamQuarantineTag.value + BulkSpamAction = $Settings.BulkSpamAction.value + BulkQuarantineTag = $Settings.BulkQuarantineTag.value + PhishSpamAction = $Settings.PhishSpamAction.value + PhishQuarantineTag = $Settings.PhishQuarantineTag.value HighConfidencePhishAction = 'Quarantine' - HighConfidencePhishQuarantineTag = $Settings.HighConfidencePhishQuarantineTag + HighConfidencePhishQuarantineTag = $Settings.HighConfidencePhishQuarantineTag.value BulkThreshold = $Settings.BulkThreshold QuarantineRetentionPeriod = 30 IncreaseScoreWithNumericIps = 'On' @@ -110,6 +110,8 @@ function Invoke-CIPPStandardSpamFilterPolicy { PhishZapEnabled = $true SpamZapEnabled = $true } + Write-Host "================== DEBUG ==================" + Write-Host $cmdparams if ($CurrentState.Name -eq $PolicyName) { try { diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTAP.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTAP.ps1 index 925916f948e8..23f6ae97a643 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTAP.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTAP.ps1 @@ -32,7 +32,7 @@ function Invoke-CIPPStandardTAP { $CurrentState = New-GraphGetRequest -Uri 'https://graph.microsoft.com/beta/policies/authenticationmethodspolicy/authenticationMethodConfigurations/TemporaryAccessPass' -tenantid $Tenant if ($null -eq $Settings.config) { $Settings.config = $True } - $StateIsCorrect = ($CurrentState.state -eq 'enabled') -and + $StateIsCorrect = ($CurrentState.state -eq 'enabled') -and ([System.Convert]::ToBoolean($CurrentState.isUsableOnce) -eq [System.Convert]::ToBoolean($Settings.config)) if ($Settings.report -eq $true) { @@ -43,7 +43,10 @@ function Invoke-CIPPStandardTAP { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'Temporary Access Passwords is already enabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'TemporaryAccessPass' -Enabled $true -TAPisUsableOnce $Settings.config + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'TemporaryAccessPass' -Enabled $true -TAPisUsableOnce $Settings.config + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsEnrollUser.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsEnrollUser.ps1 index 64e4ad948181..464324ff4b61 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsEnrollUser.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsEnrollUser.ps1 @@ -32,25 +32,23 @@ Function Invoke-CIPPStandardTeamsEnrollUser { $CurrentState = New-TeamsRequest -TenantFilter $Tenant -Cmdlet 'Get-CsTeamsMeetingPolicy' -CmdParams @{Identity = 'Global' } | Select-Object EnrollUserOverride - if ($null -eq $Settings.EnrollUserOverride) { $Settings.EnrollUserOverride = $CurrentState.EnrollUserOverride } - - $StateIsCorrect = ($CurrentState.EnrollUserOverride -eq $Settings.EnrollUserOverride) + $StateIsCorrect = ($CurrentState.EnrollUserOverride -eq $Settings.EnrollUserOverride.value) if ($Settings.remediate -eq $true) { if ($StateIsCorrect -eq $true) { - Write-LogMessage -API 'Standards' -tenant $Tenant -message "Teams Enroll User Override settings already set to $($Settings.EnrollUserOverride)." -sev Info + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Teams Enroll User Override settings already set to $($Settings.EnrollUserOverride.value)." -sev Info } else { $cmdparams = @{ Identity = 'Global' - EnrollUserOverride = $Settings.EnrollUserOverride + EnrollUserOverride = $Settings.EnrollUserOverride.value } try { New-TeamsRequest -TenantFilter $Tenant -Cmdlet 'Set-CsTeamsMeetingPolicy' -CmdParams $cmdparams - Write-LogMessage -API 'Standards' -tenant $Tenant -message "Updated Teams Enroll User Override setting to $($Settings.EnrollUserOverride)." -sev Info + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Updated Teams Enroll User Override setting to $($Settings.EnrollUserOverride.value)." -sev Info } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - Write-LogMessage -API 'Standards' -tenant $Tenant -message "Failed to set Teams Enroll User Override setting to $($Settings.EnrollUserOverride)." -sev Error -LogData $ErrorMessage + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Failed to set Teams Enroll User Override setting to $($Settings.EnrollUserOverride.value)." -sev Error -LogData $ErrorMessage } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsFederationConfiguration.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsFederationConfiguration.ps1 index 930bff06c4db..aea9e7a3e6b0 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsFederationConfiguration.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsFederationConfiguration.ps1 @@ -36,7 +36,7 @@ Function Invoke-CIPPStandardTeamsFederationConfiguration { $CurrentState = New-TeamsRequest -TenantFilter $Tenant -Cmdlet 'Get-CsTenantFederationConfiguration' -CmdParams @{Identity = 'Global' } | Select-Object * - Switch ($Settings.DomainControl) { + Switch ($Settings.DomainControl.value) { 'AllowAllExternal' { $AllowFederatedUsers = $true $AllowedDomainsAsAList = 'AllowAllKnownDomains' @@ -65,6 +65,10 @@ Function Invoke-CIPPStandardTeamsFederationConfiguration { $BlockedDomains = @() } } + Default { + Write-LogMessage -API 'Standards' -tenant $Tenant -message "Federation Configuration: Invalid $($Settings.DomainControl.value) parameter" -sev Error + Return + } } # TODO : Add proper validation for the domain list diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsGlobalMeetingPolicy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsGlobalMeetingPolicy.ps1 index 5827f007b0f1..4d0cfd8ff359 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsGlobalMeetingPolicy.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsGlobalMeetingPolicy.ps1 @@ -35,16 +35,12 @@ Function Invoke-CIPPStandardTeamsGlobalMeetingPolicy { $CurrentState = New-TeamsRequest -TenantFilter $Tenant -Cmdlet 'Get-CsTeamsMeetingPolicy' -CmdParams @{Identity = 'Global' } | Select-Object AllowAnonymousUsersToJoinMeeting, AllowAnonymousUsersToStartMeeting, AutoAdmittedUsers, AllowPSTNUsersToBypassLobby, MeetingChatEnabledType, DesignatedPresenterRoleMode, AllowExternalParticipantGiveRequestControl - if ($null -eq $Settings.DesignatedPresenterRoleMode) { $Settings.DesignatedPresenterRoleMode = $CurrentState.DesignatedPresenterRoleMode } - if ($null -eq $Settings.AllowAnonymousUsersToJoinMeeting) { $Settings.AllowAnonymousUsersToJoinMeeting = $CurrentState.AllowAnonymousUsersToJoinMeeting } - if ($null -eq $Settings.MeetingChatEnabledType) { $Settings.MeetingChatEnabledType = $CurrentState.MeetingChatEnabledType } # Enabled, EnabledExceptAnonymous, Disabled - $StateIsCorrect = ($CurrentState.AllowAnonymousUsersToJoinMeeting -eq $Settings.AllowAnonymousUsersToJoinMeeting) -and ($CurrentState.AllowAnonymousUsersToStartMeeting -eq $false) -and ($CurrentState.AutoAdmittedUsers -eq 'EveryoneInCompanyExcludingGuests') -and ($CurrentState.AllowPSTNUsersToBypassLobby -eq $false) -and - ($CurrentState.MeetingChatEnabledType -eq $Settings.MeetingChatEnabledType) -and - ($CurrentState.DesignatedPresenterRoleMode -eq $Settings.DesignatedPresenterRoleMode) -and + ($CurrentState.MeetingChatEnabledType -eq $Settings.MeetingChatEnabledType.value) -and + ($CurrentState.DesignatedPresenterRoleMode -eq $Settings.DesignatedPresenterRoleMode.value) -and ($CurrentState.AllowExternalParticipantGiveRequestControl -eq $false) if ($Settings.remediate -eq $true) { @@ -57,8 +53,8 @@ Function Invoke-CIPPStandardTeamsGlobalMeetingPolicy { AllowAnonymousUsersToStartMeeting = $false AutoAdmittedUsers = 'EveryoneInCompanyExcludingGuests' AllowPSTNUsersToBypassLobby = $false - MeetingChatEnabledType = $Settings.MeetingChatEnabledType - DesignatedPresenterRoleMode = $Settings.DesignatedPresenterRoleMode + MeetingChatEnabledType = $Settings.MeetingChatEnabledType.value + DesignatedPresenterRoleMode = $Settings.DesignatedPresenterRoleMode.value AllowExternalParticipantGiveRequestControl = $false } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsMessagingPolicy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsMessagingPolicy.ps1 index cb0a7c4d796b..14f3c3660d12 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsMessagingPolicy.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardTeamsMessagingPolicy.ps1 @@ -43,7 +43,6 @@ Function Invoke-CIPPStandardTeamsMessagingPolicy { if ($null -eq $Settings.AllowUserDeleteMessage) { $Settings.AllowUserDeleteMessage = $CurrentState.AllowUserDeleteMessage } if ($null -eq $Settings.AllowUserEditMessage) { $Settings.AllowUserEditMessage = $CurrentState.AllowUserEditMessage } if ($null -eq $Settings.AllowUserDeleteChat) { $Settings.AllowUserDeleteChat = $CurrentState.AllowUserDeleteChat } - if ($null -eq $Settings.ReadReceiptsEnabledType) { $Settings.ReadReceiptsEnabledType = $CurrentState.ReadReceiptsEnabledType } if ($null -eq $Settings.CreateCustomEmojis) { $Settings.CreateCustomEmojis = $CurrentState.CreateCustomEmojis } if ($null -eq $Settings.DeleteCustomEmojis) { $Settings.DeleteCustomEmojis = $CurrentState.DeleteCustomEmojis } if ($null -eq $Settings.AllowSecurityEndUserReporting) { $Settings.AllowSecurityEndUserReporting = $CurrentState.AllowSecurityEndUserReporting } @@ -53,7 +52,7 @@ Function Invoke-CIPPStandardTeamsMessagingPolicy { ($CurrentState.AllowUserDeleteMessage -eq $Settings.AllowUserDeleteMessage) -and ($CurrentState.AllowUserEditMessage -eq $Settings.AllowUserEditMessage) -and ($CurrentState.AllowUserDeleteChat -eq $Settings.AllowUserDeleteChat) -and - ($CurrentState.ReadReceiptsEnabledType -eq $Settings.ReadReceiptsEnabledType) -and + ($CurrentState.ReadReceiptsEnabledType -eq $Settings.ReadReceiptsEnabledType.value) -and ($CurrentState.CreateCustomEmojis -eq $Settings.CreateCustomEmojis) -and ($CurrentState.DeleteCustomEmojis -eq $Settings.DeleteCustomEmojis) -and ($CurrentState.AllowSecurityEndUserReporting -eq $Settings.AllowSecurityEndUserReporting) -and @@ -69,7 +68,7 @@ Function Invoke-CIPPStandardTeamsMessagingPolicy { AllowUserDeleteMessage = $Settings.AllowUserDeleteMessage AllowUserEditMessage = $Settings.AllowUserEditMessage AllowUserDeleteChat = $Settings.AllowUserDeleteChat - ReadReceiptsEnabledType = $Settings.ReadReceiptsEnabledType + ReadReceiptsEnabledType = $Settings.ReadReceiptsEnabledType.value CreateCustomEmojis = $Settings.CreateCustomEmojis DeleteCustomEmojis = $Settings.DeleteCustomEmojis AllowSecurityEndUserReporting = $Settings.AllowSecurityEndUserReporting diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOAuthTokens.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOAuthTokens.ps1 index 6035ca8d04dc..b621e3e85ea6 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOAuthTokens.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOAuthTokens.ps1 @@ -36,7 +36,10 @@ function Invoke-CIPPStandardallowOAuthTokens { if ($StateIsCorrect -eq $true) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'Software OTP/oAuth tokens is already enabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'softwareOath' -Enabled $true + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'softwareOath' -Enabled $true + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOTPTokens.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOTPTokens.ps1 index 9b9441b9e951..fb07572ffb32 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOTPTokens.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardallowOTPTokens.ps1 @@ -35,7 +35,10 @@ function Invoke-CIPPStandardallowOTPTokens { if ($CurrentInfo.isSoftwareOathEnabled) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'MS authenticator OTP/oAuth tokens is already enabled.' -sev Info } else { - Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'MicrosoftAuthenticator' -Enabled $true -MicrosoftAuthenticatorSoftwareOathEnabled $true + try { + Set-CIPPAuthenticationPolicy -Tenant $tenant -APIName 'Standards' -AuthenticationMethodId 'MicrosoftAuthenticator' -Enabled $true -MicrosoftAuthenticatorSoftwareOathEnabled $true + } catch { + } } } diff --git a/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 b/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 index 411497f4cb30..e111bbf55d2e 100644 --- a/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 @@ -3,11 +3,11 @@ function Test-CIPPAccessPermissions { param ( $TenantFilter, $APIName = 'Access Check', - $ExecutingUser + $Headers ) $User = $request.headers.'x-ms-client-principal' - Write-LogMessage -user $User -API $APINAME -message 'Started permissions check' -Sev 'Debug' + Write-LogMessage -Headers $User -API $APINAME -message 'Started permissions check' -Sev 'Debug' $Messages = [System.Collections.Generic.List[string]]::new() $ErrorMessages = [System.Collections.Generic.List[string]]::new() $MissingPermissions = [System.Collections.Generic.List[string]]::new() @@ -46,7 +46,7 @@ function Test-CIPPAccessPermissions { } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -tenant $tenant -message "Key vault exception: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $tenant -message "Key vault exception: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } else { $Messages.Add('Your refresh token matches key vault.') | Out-Null @@ -60,7 +60,7 @@ function Test-CIPPAccessPermissions { Name = '' AuthMethods = @() } - Write-LogMessage -user $User -API $APINAME -tenant $tenant -message "Token exception: $($ErrorMessage.NormalizedError_) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -tenant $tenant -message "Token exception: $($ErrorMessage.NormalizedError_) " -Sev 'Error' -LogData $ErrorMessage $Success = $false } @@ -152,7 +152,7 @@ function Test-CIPPAccessPermissions { } } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $User -API $APINAME -message "Permissions check failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -Headers $User -API $APINAME -message "Permissions check failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage $ErrorMessages.Add("We could not connect to the API to retrieve the permissions. There might be a problem with the secure application model configuration. The returned error is: $($ErrorMessage.NormalizedError)") | Out-Null $Success = $false } diff --git a/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 b/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 index 575993740ca6..b895a40c9574 100644 --- a/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 @@ -3,7 +3,7 @@ function Test-CIPPAccessTenant { param ( $Tenant = 'AllTenants', $APIName = 'Access Check', - $ExecutingUser + $Headers ) $ExpectedRoles = @( @{ Name = 'Application Administrator'; Id = '9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3' }, @@ -98,7 +98,7 @@ function Test-CIPPAccessTenant { } catch { $ErrorMessage = Get-CippException -Exception $_ $GraphTest = "Failed to connect to Graph: $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $tenant.defaultDomainName -message "Tenant access check failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -tenant $tenant.defaultDomainName -message "Tenant access check failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } try { @@ -112,11 +112,11 @@ function Test-CIPPAccessTenant { if ($null -eq $Message) { $Message = $($_.Exception.Message) } $ExchangeTest = "Failed to connect to Exchange: $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $tenant.defaultDomainName -message "Tenant access check for Exchange failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -tenant $tenant.defaultDomainName -message "Tenant access check for Exchange failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } if ($GraphStatus -and $ExchangeStatus) { - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $Tenant.defaultDomainName -tenantId $Tenant.customerId -message 'Tenant access check executed successfully' -Sev 'Info' + Write-LogMessage -headers $Headers -API $APINAME -tenant $Tenant.defaultDomainName -tenantId $Tenant.customerId -message 'Tenant access check executed successfully' -Sev 'Info' } $Results.GraphStatus = $GraphStatus @@ -126,7 +126,7 @@ function Test-CIPPAccessTenant { $Results.GDAPRoles = @($GDAPRoles) $Results.MissingRoles = @($MissingRoles) - $ExecutingUser = $ExecutingUser.UserDetails + $Headers = $Headers.UserDetails $Entity = @{ PartitionKey = 'TenantAccessChecks' RowKey = $Tenant.customerId @@ -136,7 +136,7 @@ function Test-CIPPAccessTenant { try { $null = Add-CIPPAzDataTableEntity @Table -Entity $Entity -Force } catch { - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $Tenant.defaultDomainName -message "Failed to add access check for $($Tenant.customerId): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) + Write-LogMessage -headers $Headers -API $APINAME -tenant $Tenant.defaultDomainName -message "Failed to add access check for $($Tenant.customerId): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) } } diff --git a/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 b/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 index 09cf46fe35c4..596fc6a8e19c 100644 --- a/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 @@ -3,7 +3,7 @@ function Test-CIPPGDAPRelationships { param ( $TenantFilter, $APIName = 'Access Check', - $ExecutingUser + $Headers ) $GDAPissues = [System.Collections.Generic.List[object]]@() @@ -95,7 +95,7 @@ function Test-CIPPGDAPRelationships { } catch { $ErrorMessage = Get-CippException -Exception $_ - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Failed to run GDAP check for $($TenantFilter): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $APINAME -message "Failed to run GDAP check for $($TenantFilter): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage } $GDAPRelationships = [PSCustomObject]@{ diff --git a/Modules/CIPPCore/Public/Test-CIPPRerun.ps1 b/Modules/CIPPCore/Public/Test-CIPPRerun.ps1 index 39384ad879bc..a7f5ed0d676a 100644 --- a/Modules/CIPPCore/Public/Test-CIPPRerun.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPRerun.ps1 @@ -5,7 +5,7 @@ function Test-CIPPRerun { $Type, $API, $Settings, - $ExecutingUser, + $Headers, [switch]$Clear, [switch]$ClearAll ) @@ -45,7 +45,7 @@ function Test-CIPPRerun { } } if ($RerunData.EstimatedNextRun -gt $CurrentUnixTime) { - Write-LogMessage -API $API -message "Standard rerun detected for $($API). Prevented from running again." -tenant $TenantFilter -user $ExecutingUser -Sev 'Info' + Write-LogMessage -API $API -message "Standard rerun detected for $($API). Prevented from running again." -tenant $TenantFilter -headers $Headers -Sev 'Info' return $true } else { $RerunData.EstimatedNextRun = $EstimatedNextRun @@ -67,7 +67,7 @@ function Test-CIPPRerun { } catch { $ErrorMessage = Get-CippException -Exception $_ Write-Host "Could not detect if this is a rerun: $($ErrorMessage.NormalizedError)" - Write-LogMessage -user $ExecutingUser -API $API -message "Could not detect if this is a rerun: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + Write-LogMessage -headers $Headers -API $API -message "Could not detect if this is a rerun: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage return $false } } diff --git a/Modules/CIPPCore/Public/Tools/Import-CommunityTemplate.ps1 b/Modules/CIPPCore/Public/Tools/Import-CommunityTemplate.ps1 new file mode 100644 index 000000000000..396757529a9f --- /dev/null +++ b/Modules/CIPPCore/Public/Tools/Import-CommunityTemplate.ps1 @@ -0,0 +1,107 @@ +function Import-CommunityTemplate { + <# + + #> + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + $Template, + $SHA, + $MigrationTable, + [switch]$Force + ) + + $Table = Get-CippTable -TableName 'templates' + + + if ($Template.RowKey) { + Write-Host "This is going to be a direct write to table, it's a CIPP template. We're writing $($Template.RowKey)" + $Template = $Template | Select-Object * -ExcludeProperty timestamp + Add-CIPPAzDataTableEntity @Table -Entity $Template -Force + } else { + if ($Template.mailNickname) { $Type = 'Group' } + if ($Template.'@odata.type' -like '*conditionalAccessPolicy*') { $Type = 'ConditionalAccessPolicy' } + Write-Host "The type is $Type" + switch -Wildcard ($Type) { + + '*Group*' { + $RawJsonObj = [PSCustomObject]@{ + Displayname = $Template.displayName + Description = $Template.Description + MembershipRules = $Template.membershipRule + username = $Template.mailNickname + GUID = $Template.id + groupType = 'generic' + } | ConvertTo-Json -Depth 100 + $entity = @{ + JSON = "$RawJsonObj" + PartitionKey = 'GroupTemplate' + SHA = $SHA + GUID = $Template.id + RowKey = $Template.id + } + Add-CIPPAzDataTableEntity @Table -Entity $entity -Force + break + } + '*conditionalAccessPolicy*' { + Write-Host $MigrationTable + $Template = ([pscustomobject]$Template) | ForEach-Object { + $NonEmptyProperties = $_.psobject.Properties | Where-Object { $null -ne $_.Value } | Select-Object -ExpandProperty Name + $_ | Select-Object -Property $NonEmptyProperties + } + $id = $Template.id + $Template = $Template | Select-Object * -ExcludeProperty lastModifiedDateTime, 'assignments', '#microsoft*', '*@odata.navigationLink', '*@odata.associationLink', '*@odata.context', 'ScopeTagIds', 'supportsScopeTags', 'createdDateTime', '@odata.id', '@odata.editLink', '*odata.type', 'roleScopeTagIds@odata.type', createdDateTime, 'createdDateTime@odata.type' + Remove-ODataProperties -Object $Template + $RawJson = ConvertTo-Json -InputObject $Template -Depth 100 -Compress + #Replace the ids with the displayname by using the migration table, this is a simple find and replace each instance in the JSON. + $MigrationTable.objects | ForEach-Object { + if ($RawJson -match $_.ID) { + $RawJson = $RawJson.Replace($_.ID, $($_.DisplayName)) + } + } + $entity = @{ + JSON = "$RawJson" + PartitionKey = 'CATemplate' + SHA = $SHA + GUID = $ID + RowKey = $ID + } + Add-CIPPAzDataTableEntity @Table -Entity $entity -Force + break + } + default { + $URLName = switch -Wildcard ($Template.'@odata.id') { + '*CompliancePolicies*' { 'DeviceCompliancePolicies' } + '*deviceConfigurations*' { 'Device' } + '*DriverUpdateProfiles*' { 'windowsDriverUpdateProfiles' } + '*SettingsCatalog*' { 'Catalog' } + '*configurationPolicies*' { 'Catalog' } + } + $id = $Template.id + $RawJson = $Template | Select-Object * -ExcludeProperty id, lastModifiedDateTime, 'assignments', '#microsoft*', '*@odata.navigationLink', '*@odata.associationLink', '*@odata.context', 'ScopeTagIds', 'supportsScopeTags', 'createdDateTime', '@odata.id', '@odata.editLink', 'lastModifiedDateTime@odata.type', 'roleScopeTagIds@odata.type', createdDateTime, 'createdDateTime@odata.type' + Remove-ODataProperties -Object $RawJson + $RawJson = $RawJson | ConvertTo-Json -Depth 100 -Compress + + #create a new template + $RawJsonObj = [PSCustomObject]@{ + Displayname = $Template.displayName ?? $template.Name + Description = $Template.Description + RAWJson = $RawJson + Type = $URLName + GUID = $ID + } | ConvertTo-Json -Depth 100 -Compress + + $entity = @{ + JSON = "$RawJsonObj" + PartitionKey = 'IntuneTemplate' + SHA = $SHA + GUID = $ID + RowKey = $ID + } + Add-CIPPAzDataTableEntity @Table -Entity $entity -Force + + } + } + } + +} diff --git a/Modules/CIPPCore/Public/Tools/Remove-ODataProperties.ps1 b/Modules/CIPPCore/Public/Tools/Remove-ODataProperties.ps1 new file mode 100644 index 000000000000..7a098d2732ea --- /dev/null +++ b/Modules/CIPPCore/Public/Tools/Remove-ODataProperties.ps1 @@ -0,0 +1,94 @@ +function Remove-ODataProperties { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + $Object, + [switch]$SkipRemovingProperties, + [string[]]$PropertiesToRemove = @(), + [string[]]$SkipRemoveProperties = @(), + [switch]$SkipRemoveDefaultProperties, + [switch]$SkipRemovingChildProperties + ) + if ($SkipRemovingProperties) { + return + } + $defaultProperties = @( + 'id', + 'createdDateTime', + 'lastModifiedDateTime', + 'supportsScopeTags', + 'modifiedDateTime' + ) + if (-not $Object) { + return + } + $removeProps = New-Object System.Collections.Generic.List[string] + if ($PropertiesToRemove) { + $removeProps.AddRange($PropertiesToRemove) + } + if (-not $SkipRemoveDefaultProperties) { + foreach ($defProp in $defaultProperties) { + if (-not $removeProps.Contains($defProp)) { + $removeProps.Add($defProp) + } + } + } + function Remove-PropertyIfPresent { + param( + [Parameter(Mandatory)] + $psObject, + [Parameter(Mandatory)] + [string]$propName + ) + $propExists = $psObject.PSObject.Properties | Where-Object { $_.Name -eq $propName } + if ($propExists) { + $psObject.PSObject.Properties.Remove($propName) | Out-Null + } + } + + if ($Object -is [System.Collections.IEnumerable] -and -not ($Object -is [string])) { + foreach ($element in $Object) { + Remove-ODataProperties -Object $element -SkipRemovingProperties:$SkipRemovingProperties -PropertiesToRemove $PropertiesToRemove -SkipRemoveProperties $SkipRemoveProperties -SkipRemoveDefaultProperties:$SkipRemoveDefaultProperties -SkipRemovingChildProperties:$SkipRemovingChildProperties + } + return + } + if ($Object -is [PSCustomObject]) { + $odataProps = $Object.PSObject.Properties | Where-Object { + $_.Name -like '*@odata*Link' -or + $_.Name -like '*@odata.context' -or + $_.Name -like '*@odata.id' -or + ($_.Name -like '*@odata.type' -and $_.Name -ne '@odata.type') + } + + foreach ($oProp in $odataProps) { + if (-not $removeProps.Contains($oProp.Name)) { + $removeProps.Add($oProp.Name) + } + } + + foreach ($propName in $removeProps) { + if ($SkipRemoveProperties -notcontains $propName) { + Remove-PropertyIfPresent -psObject $Object -propName $propName + } + } + + if (-not $SkipRemovingChildProperties) { + foreach ($prop in $Object.PSObject.Properties) { + $val = $prop.Value + + if ($val -is [System.Collections.IEnumerable] -and -not ($val -is [string])) { + foreach ($child in $val) { + + if ($child -is [PSCustomObject]) { + Remove-ODataProperties -Object $child -SkipRemovingProperties:$SkipRemovingProperties -PropertiesToRemove $PropertiesToRemove -SkipRemoveProperties $SkipRemoveProperties -SkipRemoveDefaultProperties:$SkipRemoveDefaultProperties -SkipRemovingChildProperties:$SkipRemovingChildProperties + } + } + } + # If $val is a single PSCustomObject, recurse into it as well. + elseif ($val -is [PSCustomObject]) { + Remove-ODataProperties -Object $val -SkipRemovingProperties:$SkipRemovingProperties -PropertiesToRemove $PropertiesToRemove -SkipRemoveProperties $SkipRemoveProperties -SkipRemoveDefaultProperties:$SkipRemoveDefaultProperties -SkipRemovingChildProperties:$SkipRemovingChildProperties + } + } + } + } +} diff --git a/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPGraphWebhookRenewal.ps1 b/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPGraphWebhookRenewal.ps1 index 0ac6acf10bbb..16f7890c4e94 100644 --- a/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPGraphWebhookRenewal.ps1 +++ b/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPGraphWebhookRenewal.ps1 @@ -15,7 +15,7 @@ function Invoke-CippGraphWebhookRenewal { $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/subscriptions/$($UpdateSub.SubscriptionID)" -tenantid $TenantFilter -type PATCH -body $body -Verbose $UpdateSub.Expiration = $RenewalDate $null = Add-AzDataTableEntity @WebhookTable -Entity $UpdateSub -Force - Write-LogMessage -user 'CIPP' -API 'Renew_Graph_Subscriptions' -message "Renewed Subscription:$($UpdateSub.SubscriptionID)" -Sev "Info" -tenant $TenantFilter + Write-LogMessage -Headers'CIPP' -API 'Renew_Graph_Subscriptions' -message "Renewed Subscription:$($UpdateSub.SubscriptionID)" -Sev "Info" -tenant $TenantFilter } catch { # Rebuild creation parameters @@ -28,8 +28,8 @@ function Invoke-CippGraphWebhookRenewal { $Resource = "$($UpdateSub.Resource)" $EventType = "$($UpdateSub.EventType)" - Write-LogMessage -user 'CIPP' -API 'Renew_Graph_Subscriptions' -message "Recreating: $($UpdateSub.SubscriptionID) as renewal failed." -Sev "Info" -tenant $TenantFilter - $CreateResult = New-CIPPGraphSubscription -TenantFilter $TenantFilter -TypeofSubscription $TypeofSubscription -BaseURL $BaseURL -Resource $Resource -EventType $EventType -ExecutingUser 'GraphSubscriptionRenewal' -Recreate + Write-LogMessage -Headers'CIPP' -API 'Renew_Graph_Subscriptions' -message "Recreating: $($UpdateSub.SubscriptionID) as renewal failed." -Sev "Info" -tenant $TenantFilter + $CreateResult = New-CIPPGraphSubscription -TenantFilter $TenantFilter -TypeofSubscription $TypeofSubscription -BaseURL $BaseURL -Resource $Resource -EventType $EventType -Headers 'GraphSubscriptionRenewal' -Recreate if ($CreateResult -match 'Created Webhook subscription for') { Remove-AzDataTableEntity -Force @WebhookTable -Entity $UpdateSub @@ -39,7 +39,7 @@ function Invoke-CippGraphWebhookRenewal { } catch { - Write-LogMessage -user 'CIPP' -API 'Renew_Graph_Subscriptions' -message "Failed to renew Webhook Subscription: $($UpdateSub.SubscriptionID). Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $($_.Exception.message)" -Sev "Error" -tenant $TenantFilter + Write-LogMessage -Headers'CIPP' -API 'Renew_Graph_Subscriptions' -message "Failed to renew Webhook Subscription: $($UpdateSub.SubscriptionID). Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $($_.Exception.message)" -Sev "Error" -tenant $TenantFilter } } } diff --git a/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPWebhookProcessing.ps1 b/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPWebhookProcessing.ps1 index ae8ad7a8ff74..e1850d93f551 100644 --- a/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPWebhookProcessing.ps1 +++ b/Modules/CIPPCore/Public/Webhooks/Invoke-CIPPWebhookProcessing.ps1 @@ -7,7 +7,7 @@ function Invoke-CippWebhookProcessing { $Operations, $CIPPURL, $APIName = 'Process webhook', - $ExecutingUser + $Headers ) $AuditLogTable = Get-CIPPTable -TableName 'AuditLogs' @@ -26,13 +26,13 @@ function Invoke-CippWebhookProcessing { Write-Host "this is our action: $($action | ConvertTo-Json -Depth 15 -Compress)" switch ($action) { 'disableUser' { - Set-CIPPSignInState -TenantFilter $TenantFilter -User $data.UserId -AccountEnabled $false -APIName 'Alert Engine' -ExecutingUser 'Alert Engine' + Set-CIPPSignInState -TenantFilter $TenantFilter -User $data.UserId -AccountEnabled $false -APIName 'Alert Engine' -Headers 'Alert Engine' } 'becremediate' { $username = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($data.UserId)" -tenantid $TenantFilter).UserPrincipalName - Set-CIPPResetPassword -UserID $username -tenantFilter $TenantFilter -APIName 'Alert Engine' -ExecutingUser 'Alert Engine' - Set-CIPPSignInState -userid $username -AccountEnabled $false -tenantFilter $TenantFilter -APIName 'Alert Engine' -ExecutingUser 'Alert Engine' - Revoke-CIPPSessions -userid $username -username $username -ExecutingUser 'Alert Engine' -APIName 'Alert Engine' -tenantFilter $TenantFilter + Set-CIPPResetPassword -UserID $username -tenantFilter $TenantFilter -APIName 'Alert Engine' -Headers 'Alert Engine' + Set-CIPPSignInState -userid $username -AccountEnabled $false -tenantFilter $TenantFilter -APIName 'Alert Engine' -Headers 'Alert Engine' + Revoke-CIPPSessions -userid $username -username $username -Headers 'Alert Engine' -APIName 'Alert Engine' -tenantFilter $TenantFilter $RuleDisabled = 0 New-ExoRequest -anchor $username -tenantid $TenantFilter -cmdlet 'Get-InboxRule' -cmdParams @{Mailbox = $username; IncludeHidden = $true } | Where-Object { $_.Name -ne 'Junk E-Mail Rule' -and $_.Name -notlike 'Microsoft.Exchange.OOF.*' } | ForEach-Object { $null = New-ExoRequest -anchor $username -tenantid $TenantFilter -cmdlet 'Disable-InboxRule' -cmdParams @{Confirm = $false; Identity = $_.Identity } diff --git a/Modules/CIPPCore/Public/Webhooks/Invoke-RemoveWebhookAlert.ps1 b/Modules/CIPPCore/Public/Webhooks/Invoke-RemoveWebhookAlert.ps1 index 5e26756fb04d..9c56fd9dcbaf 100644 --- a/Modules/CIPPCore/Public/Webhooks/Invoke-RemoveWebhookAlert.ps1 +++ b/Modules/CIPPCore/Public/Webhooks/Invoke-RemoveWebhookAlert.ps1 @@ -10,8 +10,8 @@ Function Invoke-RemoveWebhookAlert { [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 = $Request.Params.CIPPEndpoint + Write-LogMessage -headers $Request.Headers -API $APINAME -message 'Accessed this API' -Sev 'Debug' try { $WebhookTable = Get-CIPPTable -TableName 'SchedulerConfig' @@ -33,7 +33,7 @@ Function Invoke-RemoveWebhookAlert { } Remove-AzDataTableEntity -Force @Table -Entity $CompleteObject -ErrorAction SilentlyContinue | Out-Null } catch { - Write-LogMessage -user $Request.headers.'x-ms-client-principal' -API $APIName -message "Failed to remove webhook for AllTenants. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APIName -message "Failed to remove webhook for AllTenants. $($_.Exception.Message)" -Sev 'Error' } } else { $Tenants = $Request.query.TenantFilter @@ -48,7 +48,7 @@ Function Invoke-RemoveWebhookAlert { } $body = [pscustomobject]@{'Results' = $Results } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove webhook alert. $($_.Exception.Message)" -Sev 'Error' + Write-LogMessage -headers $Request.Headers -API $APINAME -message "Failed to remove webhook alert. $($_.Exception.Message)" -Sev 'Error' $body = [pscustomobject]@{'Results' = "Failed to remove webhook alert: $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Webhooks/New-CIPPGraphSubscription.ps1 b/Modules/CIPPCore/Public/Webhooks/New-CIPPGraphSubscription.ps1 index c03f02629b58..a68ab8923a8b 100644 --- a/Modules/CIPPCore/Public/Webhooks/New-CIPPGraphSubscription.ps1 +++ b/Modules/CIPPCore/Public/Webhooks/New-CIPPGraphSubscription.ps1 @@ -8,7 +8,7 @@ function New-CIPPGraphSubscription { $Resource, $EventType, $APIName = 'Create Webhook', - $ExecutingUser, + $Headers, [Switch]$Recreate, [switch]$PartnerCenter ) @@ -68,14 +68,14 @@ function New-CIPPGraphSubscription { WebhookNotificationUrl = [string]$Body.WebhookUrl } $null = Add-CIPPAzDataTableEntity @WebhookTable -Entity $WebhookRow -Force - Write-LogMessage -user $ExecutingUser -API $APIName -message "$Action Partner Center Webhook subscription" -Sev 'Info' -tenant 'PartnerTenant' + Write-LogMessage -headers $Headers -API $APIName -message "$Action Partner Center Webhook subscription" -Sev 'Info' -tenant 'PartnerTenant' return "$Action Partner Center Webhook subscription" } else { - Write-LogMessage -user $ExecutingUser -API $APIName -message 'Existing Partner Center Webhook subscription found' -Sev 'Info' -tenant 'PartnerTenant' + Write-LogMessage -headers $Headers -API $APIName -message 'Existing Partner Center Webhook subscription found' -Sev 'Info' -tenant 'PartnerTenant' return 'Existing Partner Center Webhook subscription found' } } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to create Partner Center Webhook Subscription: $($_.Exception.Message)" -Sev 'Error' -tenant 'PartnerTenant' + Write-LogMessage -headers $Headers -API $APIName -message "Failed to create Partner Center Webhook Subscription: $($_.Exception.Message)" -Sev 'Error' -tenant 'PartnerTenant' return "Failed to create Partner Webhook Subscription: $($_.Exception.Message)" } @@ -111,14 +111,14 @@ function New-CIPPGraphSubscription { $null = Add-CIPPAzDataTableEntity @WebhookTable -Entity $WebhookRow #todo: add remove webhook function, add check webhook function, add list webhooks function #add refresh webhook function based on table. - Write-LogMessage -user $ExecutingUser -API $APIName -message "Created Graph Webhook subscription for $($TenantFilter)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Created Graph Webhook subscription for $($TenantFilter)" -Sev 'Info' -tenant $TenantFilter } else { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Existing Graph Webhook subscription for $($TenantFilter) found" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Existing Graph Webhook subscription for $($TenantFilter) found" -Sev 'Info' -tenant $TenantFilter } } return "Created Webhook subscription for $($TenantFilter)" } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to create Webhook Subscription: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Failed to create Webhook Subscription: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter Return "Failed to create Webhook Subscription for $($TenantFilter): $($_.Exception.Message)" } } diff --git a/Modules/CIPPCore/Public/Webhooks/Remove-CIPPGraphSubscription.ps1 b/Modules/CIPPCore/Public/Webhooks/Remove-CIPPGraphSubscription.ps1 index a9b35a01c3e6..24769a81b3c6 100644 --- a/Modules/CIPPCore/Public/Webhooks/Remove-CIPPGraphSubscription.ps1 +++ b/Modules/CIPPCore/Public/Webhooks/Remove-CIPPGraphSubscription.ps1 @@ -6,7 +6,7 @@ function Remove-CIPPGraphSubscription { $APIName = 'Remove Graph Webhook', $Type, $EventType, - $ExecutingUser, + $Headers, $Cleanup = $false ) try { @@ -20,11 +20,11 @@ function Remove-CIPPGraphSubscription { $WebhookRow = Get-CIPPAzDataTableEntity @WebhookTable | Where-Object { $_.PartitionKey -eq $TenantFilter -and $_.Resource -eq $EventType -and $_.version -ne '2' } $null = Remove-AzDataTableEntity -Force @WebhookTable -Entity $Entity } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message 'Deleted an audit log webhook that was already removed from CIPP' -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message 'Deleted an audit log webhook that was already removed from CIPP' -Sev 'Info' -tenant $TenantFilter } } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to cleanup old audit logs: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Failed to cleanup old audit logs: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter } } } else { @@ -39,7 +39,7 @@ function Remove-CIPPGraphSubscription { try { $AuditLog = New-GraphPOSTRequest -uri "https://manage.office.com/api/v1.0/$($TenantFilter)/activity/feed/subscriptions/stop?contentType=$($EventType)" -scope 'https://manage.office.com/.default' -tenantid $TenantFilter -type POST -body '{}' -verbose } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to remove webhook subscription at Microsoft's side: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Failed to remove webhook subscription at Microsoft's side: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter } $null = Remove-AzDataTableEntity -Force @WebhookTable -Entity $Entity } else { @@ -50,7 +50,7 @@ function Remove-CIPPGraphSubscription { return "Removed webhook subscription to $($WebhookRow.resource) for $($TenantFilter)" } } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to renew Webhook Subscription: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter + Write-LogMessage -headers $Headers -API $APIName -message "Failed to renew Webhook Subscription: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter return "Failed to remove Webhook Subscription $($GraphRequest.value.notificationUrl): $($_.Exception.Message)" } } diff --git a/Modules/CippEntrypoints/CippEntrypoints.psm1 b/Modules/CippEntrypoints/CippEntrypoints.psm1 index e7de51d858a7..4378bc872d98 100644 --- a/Modules/CippEntrypoints/CippEntrypoints.psm1 +++ b/Modules/CippEntrypoints/CippEntrypoints.psm1 @@ -10,6 +10,10 @@ function Receive-CippHttpTrigger { $TriggerMetadata ) + if ($Request.Headers.'x-ms-coldstart' -eq 1) { + Write-Information '** Function app cold start detected **' + } + $ConfigTable = Get-CIPPTable -tablename Config $Config = Get-CIPPAzDataTableEntity @ConfigTable -Filter "PartitionKey eq 'OffloadFunctions' and RowKey eq 'OffloadFunctions'" diff --git a/Modules/CippExtensions/Private/GitHub/Invoke-GitHubApiRequest.ps1 b/Modules/CippExtensions/Private/GitHub/Invoke-GitHubApiRequest.ps1 deleted file mode 100644 index 312a38f8534d..000000000000 --- a/Modules/CippExtensions/Private/GitHub/Invoke-GitHubApiRequest.ps1 +++ /dev/null @@ -1,27 +0,0 @@ -function Invoke-GitHubApiRequest { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - $Configuration, - [string]$Method = 'GET', - [Parameter(Mandatory = $true)] - [string] - $Path, - [Parameter()] - $Body - ) - - if ($Configuration.Enabled) { - $APIKey = Get-ExtensionAPIKey -Extension 'GitHub' - $Headers = @{ - Authorization = "Bearer $($APIKey)" - 'User-Agent' = 'CIPP' - Accept = 'application/vnd.github.v3+json' - } - - $FullUri = "https://api.github.com/$Path" - return Invoke-RestMethod -Method $Method -Uri $FullUri -Headers $Headers -Body $Body - } else { - throw 'GitHub API is not enabled' - } -} diff --git a/Modules/CippExtensions/Public/Extension Functions/Push-CippExtensionData.ps1 b/Modules/CippExtensions/Public/Extension Functions/Push-CippExtensionData.ps1 index 95e74b54838b..7ef43a9bc4bb 100644 --- a/Modules/CippExtensions/Public/Extension Functions/Push-CippExtensionData.ps1 +++ b/Modules/CippExtensions/Public/Extension Functions/Push-CippExtensionData.ps1 @@ -11,7 +11,7 @@ function Push-CippExtensionData { 'Hudu' { if ($Config.Hudu.Enabled) { Write-Host 'Perfoming Hudu Extension Sync...' - Invoke-HuduExtensionSync -Configuration $Config.Hudu -TenantFilter $TenantFilter + Invoke-HuduExtensionSync -Configuration $Config -TenantFilter $TenantFilter } } } diff --git a/Modules/CippExtensions/Public/Extension Functions/Set-ExtensionFieldMapping.ps1 b/Modules/CippExtensions/Public/Extension Functions/Set-ExtensionFieldMapping.ps1 index 4228bfd77e1f..9716e968fb81 100644 --- a/Modules/CippExtensions/Public/Extension Functions/Set-ExtensionFieldMapping.ps1 +++ b/Modules/CippExtensions/Public/Extension Functions/Set-ExtensionFieldMapping.ps1 @@ -16,7 +16,7 @@ function Set-ExtensionFieldMapping { IntegrationName = "$($mapping.value.label)" } Add-AzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added mapping for $($mapping.name)." -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added mapping for $($mapping.name)." -Sev 'Info' } $Result = [pscustomobject]@{'Results' = 'Successfully edited mapping table.' } diff --git a/Modules/CippExtensions/Public/GitHub/Get-GitHubBranch.ps1 b/Modules/CippExtensions/Public/GitHub/Get-GitHubBranch.ps1 new file mode 100644 index 000000000000..53581eaea498 --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/Get-GitHubBranch.ps1 @@ -0,0 +1,16 @@ +function Get-GitHubBranch { + <# + .SYNOPSIS + Get GitHub Branch + .DESCRIPTION + Get GitHub Branch + . + #> + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$FullName + ) + + Invoke-GitHubApiRequest -Path "repos/$FullName/branches" -Method GET +} diff --git a/Modules/CippExtensions/Public/GitHub/Get-GitHubFileContents.ps1 b/Modules/CippExtensions/Public/GitHub/Get-GitHubFileContents.ps1 new file mode 100644 index 000000000000..489bc89a8833 --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/Get-GitHubFileContents.ps1 @@ -0,0 +1,29 @@ +function Get-GitHubFileContents { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipelineByPropertyName = $true, Mandatory = $true)] + $FullName, + + [Parameter(ValueFromPipelineByPropertyName = $true, Mandatory = $true)] + $Path, + + [Parameter(ValueFromPipelineByPropertyName = $true, Mandatory = $true)] + $Branch + ) + + process { + $Path = "repos/$($FullName)/contents/$($Path)?ref=$($Branch)" + #Write-Information $Path + $File = Invoke-GitHubApiRequest -Path $Path -Method GET + $content = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($File.content)) + #If the first character is a BOM, remove it + if ($content[0] -eq [char]65279) { $content = $content.Substring(1) } + return [PSCustomObject]@{ + name = $File.name + path = $File.path + content = $content + sha = $File.sha + size = $File.size + } + } +} diff --git a/Modules/CippExtensions/Public/GitHub/Get-GitHubFileTree.ps1 b/Modules/CippExtensions/Public/GitHub/Get-GitHubFileTree.ps1 new file mode 100644 index 000000000000..951a364c7408 --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/Get-GitHubFileTree.ps1 @@ -0,0 +1,18 @@ +function Get-GitHubFileTree { + <# + .SYNOPSIS + Get GitHub File Tree + .DESCRIPTION + Get GitHub File Tree + . + #> + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$FullName, + [Parameter(Mandatory = $true)] + [string]$Branch + ) + + Invoke-GitHubApiRequest -Path "repos/$FullName/git/trees/$($Branch)?recursive=1" -Method GET +} diff --git a/Modules/CippExtensions/Public/GitHub/Invoke-GitHubApiRequest.ps1 b/Modules/CippExtensions/Public/GitHub/Invoke-GitHubApiRequest.ps1 new file mode 100644 index 000000000000..28c114d3d968 --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/Invoke-GitHubApiRequest.ps1 @@ -0,0 +1,64 @@ +function Invoke-GitHubApiRequest { + [CmdletBinding()] + param( + [string]$Method = 'GET', + [Parameter(Mandatory = $true)] + [string] + $Path, + [Parameter()] + $Body, + [string]$Accept = 'application/vnd.github+json', + [switch]$ReturnHeaders + ) + + $Table = Get-CIPPTable -TableName Extensionsconfig + $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json).GitHub + + if ($Configuration.Enabled) { + $APIKey = Get-ExtensionAPIKey -Extension 'GitHub' + $Headers = @{ + Authorization = "Bearer $($APIKey)" + 'User-Agent' = 'CIPP' + Accept = $Accept + 'X-GitHub-API-Version' = '2022-11-28' + } + + $FullUri = "https://api.github.com/$Path" + Write-Verbose "[$Method] $FullUri" + + $RestMethod = @{ + Method = $Method + Uri = $FullUri + Headers = $Headers + } + if ($ReturnHeaders.IsPresent) { + $RestMethod.ResponseHeadersVariable = 'ResponseHeaders' + } + + if ($Body) { + $RestMethod.Body = $Body | ConvertTo-Json -Depth 10 + $RestMethod.ContentType = 'application/json' + } + + try { + $Response = Invoke-RestMethod @RestMethod + if ($ReturnHeaders.IsPresent) { + $Response | Add-Member -MemberType NoteProperty -Name Headers -Value $ResponseHeaders + return $Response + } else { + return $Response + } + } catch { + throw $_.Exception.Message + } + } else { + $Action = @{ + Action = 'ApiCall' + Path = $Path + Method = $Method + Body = $Body + Accept = $Accept + } + (Invoke-RestMethod -Uri 'https://cippy.azurewebsites.net/api/ExecGitHubAction' -Method POST -Body ($Action | ConvertTo-Json -Depth 10) -ContentType 'application/json').Results + } +} diff --git a/Modules/CippExtensions/Public/GitHub/New-GitHubRepo.ps1 b/Modules/CippExtensions/Public/GitHub/New-GitHubRepo.ps1 new file mode 100644 index 000000000000..27d975d9bcf3 --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/New-GitHubRepo.ps1 @@ -0,0 +1,58 @@ +function New-GitHubRepo { + <# + .SYNOPSIS + Create a new GitHub repository + + .DESCRIPTION + This function creates a new GitHub repository + + .PARAMETER Name + The name of the repository + + .PARAMETER Description + The description of the repository + + .PARAMETER Private + Whether the repository is private + + .PARAMETER Type + + #> + [CmdletBinding(SupportsShouldProcess = $true)] + param ( + [Parameter(Mandatory = $true)] + [string]$Name, + [string]$Description, + [switch]$Private, + [ValidateSet('User', 'Org')] + [string]$Type = 'User', + [string]$Org, + [string]$License = 'agpl-3.0' + ) + + $Body = @{ + name = $Name + description = $Description + private = $Private.IsPresent + license_template = $License + } + + if ($Type -eq 'Org') { + $Path = "orgs/$Org/repos" + $Owner = $Org + } else { + $Path = 'user/repos' + $Owner = (Invoke-GitHubApiRequest -Path 'user').login + } + + # Check if repo exists + try { + $Existing = Invoke-GitHubApiRequest -Path "repos/$Owner/$Name" + if ($Existing.id) { + return $Existing + } + } catch { } + if ($PSCmdlet.ShouldProcess("Create repository '$Name'")) { + Invoke-GitHubApiRequest -Path $Path -Method POST -Body $Body + } +} diff --git a/Modules/CippExtensions/Public/GitHub/Push-GitHubContent.ps1 b/Modules/CippExtensions/Public/GitHub/Push-GitHubContent.ps1 new file mode 100644 index 000000000000..ca7282fffa5e --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/Push-GitHubContent.ps1 @@ -0,0 +1,47 @@ +function Push-GitHubContent { + <# + .SYNOPSIS + Update file content in GitHub repository + .DESCRIPTION + Update file content in GitHub repository + .PARAMETER FullName + The full name of the repository (e.g. 'octocat/Hello-World') + .PARAMETER Path + The path to the file in the repository + .PARAMETER Branch + The branch to update the file in (default: 'main') + .PARAMETER Content + The new content of the file + .PARAMETER Message + The commit message + .EXAMPLE + Push-GitHubContent -FullName 'octocat/Hello-World' -Path 'README.md' -Content 'Hello, World!' -Message 'Update README.md' + #> + [CmdletBinding()] + param ( + [string]$FullName, + [string]$Path, + [string]$Branch = 'main', + [string]$Content, + [string]$Message + ) + + $ContentBase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Content)) + try { + $ContentSha = (Invoke-GitHubApiRequest -Path "repos/$($FullName)/contents/$($Path)?ref=$($Branch)").sha + } catch { + $ContentSha = $null + } + $Filename = Split-Path $Path -Leaf + + $Body = @{ + message = $Message ?? "Update $($Filename)" + content = $ContentBase64 + branch = $Branch + } + if ($ContentSha) { + $Body.sha = $ContentSha + } + + Invoke-GitHubApiRequest -Path "repos/$($FullName)/contents/$($Path)" -Method PUT -Body $Body +} diff --git a/Modules/CippExtensions/Public/GitHub/Search-GitHub.ps1 b/Modules/CippExtensions/Public/GitHub/Search-GitHub.ps1 new file mode 100644 index 000000000000..c630d524c149 --- /dev/null +++ b/Modules/CippExtensions/Public/GitHub/Search-GitHub.ps1 @@ -0,0 +1,53 @@ +function Search-GitHub { + [CmdletBinding()] + Param ( + [string[]]$Repository, + [string]$User, + [string]$Org, + [string]$Path, + [string[]]$SearchTerm, + [string]$Language, + [ValidateSet('code', 'commits', 'issues', 'users', 'repositories', 'topics', 'labels')] + [string]$Type = 'code' + ) + + $QueryParts = [System.Collections.Generic.List[string]]::new() + if ($SearchTerm) { + $SearchTermParts = [System.Collections.Generic.List[string]]::new() + foreach ($Term in $SearchTerm) { + $SearchTermParts.Add("`"$Term`"") + } + if (($SearchTermParts | Measure-Object).Count -gt 1) { + $QueryParts.Add(($SearchTermParts -join ' OR ')) + } else { + $QueryParts.Add($SearchTermParts[0]) + } + } + if ($Repository) { + $RepoParts = [System.Collections.Generic.List[string]]::new() + foreach ($Repo in $Repository) { + $RepoParts.Add("repo:$Repo") + } + if (($RepoParts | Measure-Object).Count -gt 1) { + $QueryParts.Add('(' + ($RepoParts -join ' OR ') + ')') + } else { + $QueryParts.Add($RepoParts[0]) + } + } + if ($User) { + $QueryParts.Add("user:$User") + } + if ($Org) { + $QueryParts.Add("org:$Org") + } + if ($Path) { + $QueryParts.Add("path:$Path") + } + if ($Language) { + $QueryParts.Add("language:$Language") + } + + $Query = $QueryParts -join ' ' + Write-Information "Query: $Query" + Invoke-GitHubApiRequest -Path "search/$($Type)?q=$($Query)" -Method GET +} diff --git a/Modules/CippExtensions/Public/Gradient/Get-GradientToken.ps1 b/Modules/CippExtensions/Public/Gradient/Get-GradientToken.ps1 index a944d16b805d..eac3ca57f789 100644 --- a/Modules/CippExtensions/Public/Gradient/Get-GradientToken.ps1 +++ b/Modules/CippExtensions/Public/Gradient/Get-GradientToken.ps1 @@ -16,9 +16,9 @@ function Get-GradientToken { try { return [hashtable]$headers } catch { - Write-Error $_.Exception.Message + return $false } - } catch { - throw 'No Gradient configuration' + } else { + return $false } } diff --git a/Modules/CippExtensions/Public/Gradient/New-GradientAlert.ps1 b/Modules/CippExtensions/Public/Gradient/New-GradientAlert.ps1 index 497052367edf..13bb0a3fdc04 100644 --- a/Modules/CippExtensions/Public/Gradient/New-GradientAlert.ps1 +++ b/Modules/CippExtensions/Public/Gradient/New-GradientAlert.ps1 @@ -6,6 +6,7 @@ function New-GradientAlert { $client ) + $APINAME = 'GradientAlert' $Table = Get-CIPPTable -TableName Extensionsconfig $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json).Gradient #creating accounts in Gradient @@ -27,15 +28,13 @@ function New-GradientAlert { $AlertId = Invoke-RestMethod -Uri "https://app.usegradient.com/api/vendor-api/alerting/$($client)" -Method POST -Headers $GradientToken -Body $body -ContentType 'application/json' #check if the message is actually sent, if not, abort and log. check url: https://app.usegradient.com/api/vendor-api/alerting/debug/{messageId} $AlertStatus = Invoke-RestMethod -Uri "https://app.usegradient.com/api/vendor-api/alerting/debug/$($AlertId.messageId)" -Method GET -Headers $GradientToken - if ($AlertStatus.status -eq "failed") { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create ticket in Gradient API. Error: $($AlertStatus.errors)" -Sev "Error" -tenant $client - + if ($AlertStatus.status -eq 'failed') { + Write-LogMessage -API $APINAME -message "Failed to create ticket in Gradient API. Error: $($AlertStatus.errors)" -Sev 'Error' -tenant $client } - - } - catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create ticket in Gradient API. Error: $($_.Exception.Message)" -Sev "Error" -tenant "GradientAPI" + + } catch { + Write-LogMessage -API $APINAME -message "Failed to create ticket in Gradient API. Error: $($_.Exception.Message)" -Sev 'Error' -tenant 'GradientAPI' } -} \ No newline at end of file +} diff --git a/Modules/CippExtensions/Public/Gradient/New-GradientServiceSyncRun.ps1 b/Modules/CippExtensions/Public/Gradient/New-GradientServiceSyncRun.ps1 index 11d039d1ecf5..e60feeaac807 100644 --- a/Modules/CippExtensions/Public/Gradient/New-GradientServiceSyncRun.ps1 +++ b/Modules/CippExtensions/Public/Gradient/New-GradientServiceSyncRun.ps1 @@ -23,7 +23,7 @@ function New-GradientServiceSyncRun { $ActivateRequest = Invoke-RestMethod -Uri 'https://app.usegradient.com/api/vendor-api/organization/status/active' -Method PATCH -Headers $GradientToken } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create tenants in Gradient API. Error: $($_.Exception.Message)" -Sev 'Error' -tenant 'GradientAPI' + Write-LogMessage -Headers $Request.Headers -API $APINAME -message "Failed to create tenants in Gradient API. Error: $($_.Exception.Message)" -Sev 'Error' -tenant 'GradientAPI' } @@ -83,7 +83,7 @@ function New-GradientServiceSyncRun { } | ConvertTo-Json -Depth 10 $Results = Invoke-RestMethod -Uri "https://app.usegradient.com/api/vendor-api/service/$($ExistingService.id)/count" -Method POST -Headers $GradientToken -Body $ServiceBody -ContentType 'application/json' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create license in Gradient API. Error: $($_). $results" -Sev 'Error' -tenant $singlereq.tenant + Write-LogMessage -Headers $Request.Headers -API $APINAME -message "Failed to create license in Gradient API. Error: $($_). $results" -Sev 'Error' -tenant $singlereq.tenant } } diff --git a/Modules/CippExtensions/Public/Halo/Get-HaloTicketType.ps1 b/Modules/CippExtensions/Public/Halo/Get-HaloTicketType.ps1 new file mode 100644 index 000000000000..6ed6d21e4054 --- /dev/null +++ b/Modules/CippExtensions/Public/Halo/Get-HaloTicketType.ps1 @@ -0,0 +1,28 @@ +function Get-HaloTicketType { + <# + .SYNOPSIS + Get Halo Ticket Type + .DESCRIPTION + Get Halo Ticket Type + .EXAMPLE + Get-HaloTicketType + + #> + [CmdletBinding()] + param () + $Table = Get-CIPPTable -TableName Extensionsconfig + try { + $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json -ea stop).HaloPSA + $Token = Get-HaloToken -configuration $Configuration + + Invoke-RestMethod -Uri "$($Configuration.ResourceURL)/TicketType?showall=true" -ContentType 'application/json' -Method GET -Headers @{Authorization = "Bearer $($Token.access_token)" } + } catch { + $Message = if ($_.ErrorDetails.Message) { + Get-NormalizedError -Message $_.ErrorDetails.Message + } else { + $_.Exception.message + } + @(@{name = "Could not get HaloPSA Ticket Types, error: $Message"; id = '' }) + } +} + diff --git a/Modules/CippExtensions/Public/Halo/Get-HaloToken.ps1 b/Modules/CippExtensions/Public/Halo/Get-HaloToken.ps1 index 545da1377a99..6ca2edaeefb7 100644 --- a/Modules/CippExtensions/Public/Halo/Get-HaloToken.ps1 +++ b/Modules/CippExtensions/Public/Halo/Get-HaloToken.ps1 @@ -12,7 +12,6 @@ function Get-HaloToken { client_secret = $Secret scope = 'all' } - Write-Host ($body | ConvertTo-Json) if ($Configuration.Tenant -ne 'None') { $Tenant = "?tenant=$($Configuration.Tenant)" } $token = Invoke-RestMethod -Uri "$($Configuration.AuthURL)/token$Tenant" -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded' return $token diff --git a/Modules/CippExtensions/Public/Halo/New-HaloPSATicket.ps1 b/Modules/CippExtensions/Public/Halo/New-HaloPSATicket.ps1 index e29ef33bd84c..440e24842e1c 100644 --- a/Modules/CippExtensions/Public/Halo/New-HaloPSATicket.ps1 +++ b/Modules/CippExtensions/Public/Halo/New-HaloPSATicket.ps1 @@ -1,5 +1,5 @@ function New-HaloPSATicket { - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] param ( $title, $description, @@ -29,25 +29,27 @@ function New-HaloPSATicket { } if ($Configuration.TicketType) { - $object | Add-Member -MemberType NoteProperty -Name 'tickettype_id' -Value $Configuration.TicketType -Force + $TicketType = $Configuration.TicketType.value ?? $Configuration.TicketType + $object | Add-Member -MemberType NoteProperty -Name 'tickettype_id' -Value $TicketType -Force } #use the token to create a new ticket in HaloPSA $body = ConvertTo-Json -Compress -Depth 10 -InputObject @($Object) - - Write-Host 'Sending ticket to HaloPSA' - Write-Host $body + Write-Information 'Sending ticket to HaloPSA' + Write-Information $body try { - $Ticket = Invoke-RestMethod -Uri "$($Configuration.ResourceURL)/Tickets" -ContentType 'application/json; charset=utf-8' -Method Post -Body $body -Headers @{Authorization = "Bearer $($token.access_token)" } + if ($PSCmdlet.ShouldProcess('Send ticket to HaloPSA', 'Create ticket')) { + $Ticket = Invoke-RestMethod -Uri "$($Configuration.ResourceURL)/Tickets" -ContentType 'application/json; charset=utf-8' -Method Post -Body $body -Headers @{Authorization = "Bearer $($token.access_token)" } + Write-Information "Ticket created in HaloPSA: $($Ticket.id)" + } } catch { $Message = if ($_.ErrorDetails.Message) { Get-NormalizedError -Message $_.ErrorDetails.Message } else { $_.Exception.message } - Write-LogMessage -message "Failed to send ticket to HaloPSA: $Message" -API 'HaloPSATicket' -sev Error - Write-Host "Failed to send ticket to HaloPSA: $Message" - Write-Host "Body we tried to ship: $body" + Write-LogMessage -message "Failed to send ticket to HaloPSA: $Message" -API 'HaloPSATicket' -sev Error -LogData (Get-CippException -Exception $_) + Write-Information "Failed to send ticket to HaloPSA: $Message" + Write-Information "Body we tried to ship: $body" } - } diff --git a/Modules/CippExtensions/Public/Halo/Set-HaloMapping.ps1 b/Modules/CippExtensions/Public/Halo/Set-HaloMapping.ps1 index fb8c0c51585e..30ae54a5e310 100644 --- a/Modules/CippExtensions/Public/Halo/Set-HaloMapping.ps1 +++ b/Modules/CippExtensions/Public/Halo/Set-HaloMapping.ps1 @@ -18,7 +18,7 @@ function Set-HaloMapping { Add-CIPPAzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added mapping for $($mapping.name)." -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added mapping for $($mapping.name)." -Sev 'Info' } $Result = [pscustomobject]@{'Results' = 'Successfully edited mapping table.' } diff --git a/Modules/CippExtensions/Public/Hudu/Connect-HuduAPI.ps1 b/Modules/CippExtensions/Public/Hudu/Connect-HuduAPI.ps1 index cf4e4056c2b1..c704c3e7c559 100644 --- a/Modules/CippExtensions/Public/Hudu/Connect-HuduAPI.ps1 +++ b/Modules/CippExtensions/Public/Hudu/Connect-HuduAPI.ps1 @@ -6,12 +6,11 @@ function Connect-HuduAPI { $APIKey = Get-ExtensionAPIKey -Extension 'Hudu' - # Add logic to check if we're using CloudFlare Tunnel (if Hudu.CFEnabled checkbox is checked from Extensions.json). If the checkbox is checked, pull CloudFlare ClientID and API Key and add as a header - if ($Configuration.CFEnabled) { - $CFClientID = (Get-AzKeyVaultSecret -VaultName $keyvaultname -Name 'CloudFlareClientID' -AsPlainText) - $CFAPIKey = (Get-AzKeyVaultSecret -VaultName $keyvaultname -Name 'CloudFlareAPIKey' -AsPlainText) - New-HuduCustomHeaders -Headers @{'CF-Access-Client-Id' = "$CFClientID"; 'CF-Access-Client-Secret' = "$CFAPIKey" } + if ($Configuration.Hudu.CFEnabled -eq $true -and $Configuration.CFZTNA.Enabled -eq $true) { + $CFAPIKey = Get-ExtensionAPIKey -Extension 'CFZTNA' + New-HuduCustomHeaders -Headers @{'CF-Access-Client-Id' = $Configuration.CFZTNA.ClientId; 'CF-Access-Client-Secret' = "$CFAPIKey" } + Write-Information 'CF-Access-Client-Id and CF-Access-Client-Secret headers added to Hudu API request' } - New-HuduBaseURL -BaseURL $Configuration.BaseURL + New-HuduBaseURL -BaseURL $Configuration.Hudu.BaseURL New-HuduAPIKey -ApiKey $APIKey } diff --git a/Modules/CippExtensions/Public/Hudu/Get-HuduFieldMapping.ps1 b/Modules/CippExtensions/Public/Hudu/Get-HuduFieldMapping.ps1 index 7004401fd33d..ea86c61980bb 100644 --- a/Modules/CippExtensions/Public/Hudu/Get-HuduFieldMapping.ps1 +++ b/Modules/CippExtensions/Public/Hudu/Get-HuduFieldMapping.ps1 @@ -28,7 +28,7 @@ function Get-HuduFieldMapping { $Table = Get-CIPPTable -TableName Extensionsconfig try { - $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json -ea stop).Hudu + $Configuration = (Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json -ea stop Connect-HuduAPI -configuration $Configuration $AssetLayouts = Get-HuduAssetLayouts | Select-Object @{Name = 'FieldType' ; Expression = { 'Layouts' } }, @{Name = 'value'; Expression = { $_.id } }, name, fields diff --git a/Modules/CippExtensions/Public/Hudu/Get-HuduMapping.ps1 b/Modules/CippExtensions/Public/Hudu/Get-HuduMapping.ps1 index 622dfa10765f..a56b84d2a06d 100644 --- a/Modules/CippExtensions/Public/Hudu/Get-HuduMapping.ps1 +++ b/Modules/CippExtensions/Public/Hudu/Get-HuduMapping.ps1 @@ -23,7 +23,7 @@ function Get-HuduMapping { $Tenants = Get-Tenants -IncludeErrors $Table = Get-CIPPTable -TableName Extensionsconfig try { - $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json -ea stop).Hudu + $Configuration = (Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json -ea stop Connect-HuduAPI -configuration $Configuration $HuduCompanies = Get-HuduCompanies diff --git a/Modules/CippExtensions/Public/Hudu/Set-HuduMapping.ps1 b/Modules/CippExtensions/Public/Hudu/Set-HuduMapping.ps1 index 1f8ba6c37d88..667ce95ad869 100644 --- a/Modules/CippExtensions/Public/Hudu/Set-HuduMapping.ps1 +++ b/Modules/CippExtensions/Public/Hudu/Set-HuduMapping.ps1 @@ -17,7 +17,7 @@ function Set-HuduMapping { } Add-CIPPAzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added mapping for $($mapping.name)." -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added mapping for $($mapping.name)." -Sev 'Info' } $Result = [pscustomobject]@{'Results' = 'Successfully edited mapping table.' } diff --git a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneDeviceWebhook.ps1 b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneDeviceWebhook.ps1 index 67e54991324e..bcd5735dcfca 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneDeviceWebhook.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneDeviceWebhook.ps1 @@ -13,7 +13,7 @@ function Invoke-NinjaOneDeviceWebhook { } if ($MappedFields.DeviceCompliance) { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Webhook Recieved - Updating NinjaOne Device compliance for $($Data.resourceData.id) in $($Data.tenantId)" -Sev 'Info' -tenant $TenantFilter + Write-LogMessage -Headers $Headers -API $APIName -message "Webhook Recieved - Updating NinjaOne Device compliance for $($Data.resourceData.id) in $($Data.tenantId)" -Sev 'Info' -tenant $TenantFilter $tenantfilter = $Data.tenantId $M365DeviceID = $Data.resourceData.id @@ -28,7 +28,7 @@ function Invoke-NinjaOneDeviceWebhook { $Token = Get-NinjaOneToken -configuration $Configuration if (!$Token.access_token) { - Write-LogMessage -API 'NinjaOneSync' -tenant $tenantfilter -user 'CIPP' -message 'Failed to get NinjaOne Token for Device Compliance Update' -Sev 'Error' + Write-LogMessage -API 'NinjaOneSync' -tenant $tenantfilter -Headers'CIPP' -message 'Failed to get NinjaOne Token for Device Compliance Update' -Sev 'Error' return } @@ -52,10 +52,10 @@ function Invoke-NinjaOneDeviceWebhook { $_.Exception.message } Write-Error "Failed NinjaOne Device Webhook for: $($Data | ConvertTo-Json -Depth 100) Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" - Write-LogMessage -API 'NinjaOneSync' -user 'CIPP' -message "Failed NinjaOne Device Webhook Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" -Sev 'Error' + Write-LogMessage -API 'NinjaOneSync' -Headers'CIPP' -message "Failed NinjaOne Device Webhook Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" -Sev 'Error' } } else { - Write-LogMessage -API 'NinjaOneSync' -user 'CIPP' -message "$($DeviceM365.displayName) ($($M365DeviceID)) was not matched in Ninja for $($tenantfilter)" -Sev 'Info' + Write-LogMessage -API 'NinjaOneSync' -Headers'CIPP' -message "$($DeviceM365.displayName) ($($M365DeviceID)) was not matched in Ninja for $($tenantfilter)" -Sev 'Info' } } @@ -67,7 +67,7 @@ function Invoke-NinjaOneDeviceWebhook { $_.Exception.message } Write-Error "Failed NinjaOne Device Webhook for: $($Data | ConvertTo-Json -Depth 100) Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" - Write-LogMessage -API 'NinjaOneSync' -user 'CIPP' -message "Failed NinjaOne Device Webhook Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" -Sev 'Error' + Write-LogMessage -API 'NinjaOneSync' -Headers'CIPP' -message "Failed NinjaOne Device Webhook Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" -Sev 'Error' } diff --git a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneExtensionScheduler.ps1 b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneExtensionScheduler.ps1 index ca69e5b10935..921a6d1e1ac3 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneExtensionScheduler.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneExtensionScheduler.ps1 @@ -55,7 +55,7 @@ function Invoke-NinjaOneExtensionScheduler { } Add-AzDataTableEntity @Table -Entity $AddObject -Force - Write-LogMessage -API 'NinjaOneSync' -user 'CIPP' -message "NinjaOne Daily Synchronization Queued for $(($TenantsToProcess | Measure-Object).count) Tenants" -Sev 'Info' + Write-LogMessage -API 'NinjaOneSync' -Headers'CIPP' -message "NinjaOne Daily Synchronization Queued for $(($TenantsToProcess | Measure-Object).count) Tenants" -Sev 'Info' } else { if ($LastRunTime -lt (Get-Date).AddMinutes(-90)) { @@ -91,10 +91,10 @@ function Invoke-NinjaOneExtensionScheduler { } if (($CatchupTenants | Measure-Object).count -gt 0) { - Write-LogMessage -API 'NinjaOneSync' -user 'CIPP' -message "NinjaOne Synchronization Catchup Queued for $(($CatchupTenants | Measure-Object).count) Tenants" -Sev 'Info' + Write-LogMessage -API 'NinjaOneSync' -Headers'CIPP' -message "NinjaOne Synchronization Catchup Queued for $(($CatchupTenants | Measure-Object).count) Tenants" -Sev 'Info' } } } -} \ No newline at end of file +} diff --git a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMapping.ps1 b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMapping.ps1 index 443e3d49042b..d8e963a536c1 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMapping.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMapping.ps1 @@ -87,7 +87,7 @@ function Invoke-NinjaOneOrgMapping { IntegrationName = "$($MatchedOrg.name)" } Add-AzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API 'NinjaOneAutoMap_Queue' -user 'CIPP' -message "Added mapping from Organization name match for $($Tenant.customerId). to $($($MatchedOrg.name))" -Sev 'Info' + Write-LogMessage -API 'NinjaOneAutoMap_Queue' -Headers'CIPP' -message "Added mapping from Organization name match for $($Tenant.customerId). to $($($MatchedOrg.name))" -Sev 'Info' } } diff --git a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMappingTenant.ps1 b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMappingTenant.ps1 index c3f05acf1cc3..7db9841d7295 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMappingTenant.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneOrgMappingTenant.ps1 @@ -66,8 +66,8 @@ function Invoke-NinjaOneOrgMappingTenant { IntegrationName = "$($MatchedOrg.name)" } Add-AzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API 'NinjaOneAutoMap_Queue' -user 'CIPP' -message "Added mapping from Device match for $($Tenant.displayName) to $($($MatchedOrg.name))" -Sev 'Info' + Write-LogMessage -API 'NinjaOneAutoMap_Queue' -Headers'CIPP' -message "Added mapping from Device match for $($Tenant.displayName) to $($($MatchedOrg.name))" -Sev 'Info' } -} \ No newline at end of file +} diff --git a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneSync.ps1 b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneSync.ps1 index c6fb732eb30a..54a0c2c28a67 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneSync.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneSync.ps1 @@ -32,7 +32,7 @@ function Invoke-NinjaOneSync { Add-AzDataTableEntity @Table -Entity $AddObject -Force - Write-LogMessage -API 'NinjaOneAutoMap_Queue' -user 'CIPP' -message "NinjaOne Synchronization Queued for $(($TenantsToProcess | Measure-Object).count) Tenants" -Sev 'Info' + Write-LogMessage -API 'NinjaOneAutoMap_Queue' -Headers'CIPP' -message "NinjaOne Synchronization Queued for $(($TenantsToProcess | Measure-Object).count) Tenants" -Sev 'Info' } catch { Write-LogMessage -API 'Scheduler_Billing' -tenant 'none' -message "Could not start NinjaOne Sync $($_.Exception.Message)" -sev Error } diff --git a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneTenantSync.ps1 b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneTenantSync.ps1 index 7008402506bf..813ce65b3af5 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneTenantSync.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Invoke-NinjaOneTenantSync.ps1 @@ -45,7 +45,7 @@ function Invoke-NinjaOneTenantSync { $Customer = Get-Tenants -IncludeErrors | Where-Object { $_.customerId -eq $MappedTenant.RowKey } Write-Information "Processing: $($Customer.displayName) - Queued for $((New-TimeSpan -Start $StartQueueTime -End $StartTime).TotalSeconds)" - Write-LogMessage -API 'NinjaOneSync' -user 'NinjaOneSync' -message "Processing NinjaOne Synchronization for $($Customer.displayName) - Queued for $((New-TimeSpan -Start $StartQueueTime -End $StartTime).TotalSeconds)" -Sev 'Info' + Write-LogMessage -API 'NinjaOneSync' -Headers'NinjaOneSync' -message "Processing NinjaOne Synchronization for $($Customer.displayName) - Queued for $((New-TimeSpan -Start $StartQueueTime -End $StartTime).TotalSeconds)" -Sev 'Info' if (($Customer | Measure-Object).count -ne 1) { Throw "Unable to match the recieved ID to a tenant QueueItem: $($QueueItem | ConvertTo-Json -Depth 100 | Out-String) Matched Customer: $($Customer| ConvertTo-Json -Depth 100 | Out-String)" @@ -886,7 +886,7 @@ function Invoke-NinjaOneTenantSync { # Enable Device Updates Subscription if needed. if ($MappedFields.DeviceCompliance) { - New-CIPPGraphSubscription -TenantFilter $TenantFilter -TypeofSubscription 'updated' -BaseURL $CIPPUrl -Resource 'devices' -EventType 'DeviceUpdate' -ExecutingUser 'NinjaOneSync' + New-CIPPGraphSubscription -TenantFilter $TenantFilter -TypeofSubscription 'updated' -BaseURL $CIPPUrl -Resource 'devices' -EventType 'DeviceUpdate' -Headers 'NinjaOneSync' } Write-Information 'Processed Devices' @@ -2326,7 +2326,7 @@ function Invoke-NinjaOneTenantSync { $CurrentItem | Add-Member -NotePropertyName lastStatus -NotePropertyValue 'Completed' -Force Add-CIPPAzDataTableEntity @MappingTable -Entity $CurrentItem -Force - Write-LogMessage -API 'NinjaOneSync' -user 'NinjaOneSync' -message "Completed NinjaOne Sync for $($Customer.displayName). Queued for $((New-TimeSpan -Start $StartQueueTime -End $StartTime).TotalSeconds) seconds. Data fetched in $((New-TimeSpan -Start $StartTime -End $FetchEnd).TotalSeconds) seconds. Total processing time $((New-TimeSpan -Start $StartTime -End (Get-Date)).TotalSeconds) seconds" -Sev 'info' + Write-LogMessage -API 'NinjaOneSync' -Headers'NinjaOneSync' -message "Completed NinjaOne Sync for $($Customer.displayName). Queued for $((New-TimeSpan -Start $StartQueueTime -End $StartTime).TotalSeconds) seconds. Data fetched in $((New-TimeSpan -Start $StartTime -End $FetchEnd).TotalSeconds) seconds. Total processing time $((New-TimeSpan -Start $StartTime -End (Get-Date)).TotalSeconds) seconds" -Sev 'info' } catch { $Message = if ($_.ErrorDetails.Message) { @@ -2335,7 +2335,7 @@ function Invoke-NinjaOneTenantSync { $_.Exception.message } Write-Error "Failed NinjaOne Processing for $($Customer.displayName) Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" - Write-LogMessage -API 'NinjaOneSync' -user 'NinjaOneSync' -message "Failed NinjaOne Processing for $($Customer.displayName) Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" -Sev 'Error' + Write-LogMessage -API 'NinjaOneSync' -Headers'NinjaOneSync' -message "Failed NinjaOne Processing for $($Customer.displayName) Linenumber: $($_.InvocationInfo.ScriptLineNumber) Error: $Message" -Sev 'Error' $CurrentItem | Add-Member -NotePropertyName lastEndTime -NotePropertyValue ([string]$((Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ'))) -Force $CurrentItem | Add-Member -NotePropertyName lastStatus -NotePropertyValue 'Failed' -Force Add-CIPPAzDataTableEntity @MappingTable -Entity $CurrentItem -Force diff --git a/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneFieldMapping.ps1 b/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneFieldMapping.ps1 index abba4fc1a022..eedca3f891fe 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneFieldMapping.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneFieldMapping.ps1 @@ -17,7 +17,7 @@ function Set-NinjaOneFieldMapping { } Add-AzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added mapping for $($mapping.name)." -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added mapping for $($mapping.name)." -Sev 'Info' } $Result = [pscustomobject]@{'Results' = 'Successfully edited mapping table.' } diff --git a/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneOrgMapping.ps1 b/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneOrgMapping.ps1 index d501714d1a6d..b0798eca8230 100644 --- a/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneOrgMapping.ps1 +++ b/Modules/CippExtensions/Public/NinjaOne/Set-NinjaOneOrgMapping.ps1 @@ -19,7 +19,7 @@ function Set-NinjaOneOrgMapping { Add-CIPPAzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added mapping for $($mapping.name)." -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added mapping for $($mapping.name)." -Sev 'Info' } $Result = [pscustomobject]@{'Results' = 'Successfully edited mapping table.' } diff --git a/Modules/CippExtensions/Public/PwPush/Get-PwPushAccount.ps1 b/Modules/CippExtensions/Public/PwPush/Get-PwPushAccount.ps1 new file mode 100644 index 000000000000..f5e5198a1633 --- /dev/null +++ b/Modules/CippExtensions/Public/PwPush/Get-PwPushAccount.ps1 @@ -0,0 +1,13 @@ +function Get-PwPushAccount { + $Table = Get-CIPPTable -TableName Extensionsconfig + $Configuration = ((Get-CIPPAzDataTableEntity @Table).config | ConvertFrom-Json).PWPush + if ($Configuration.Enabled -eq $true -and $Configuration.PWPushPro -eq $true) { + Set-PwPushConfig -Configuration $Configuration + Get-PushAccount + } else { + return @(@{ + name = 'PWPush Pro is not enabled or configured. Make sure to save the configuration first.'; + id = '' + }) + } +} diff --git a/Modules/CippExtensions/Public/PwPush/New-PwPushLink.ps1 b/Modules/CippExtensions/Public/PwPush/New-PwPushLink.ps1 index 566bf8c3cb45..a4afea1d7c17 100644 --- a/Modules/CippExtensions/Public/PwPush/New-PwPushLink.ps1 +++ b/Modules/CippExtensions/Public/PwPush/New-PwPushLink.ps1 @@ -13,6 +13,7 @@ function New-PwPushLink { if ($Configuration.ExpireAfterDays) { $PushParams.ExpireAfterDays = $Configuration.ExpireAfterDays } if ($Configuration.ExpireAfterViews) { $PushParams.ExpireAfterViews = $Configuration.ExpireAfterViews } if ($Configuration.DeletableByViewer) { $PushParams.DeletableByViewer = $Configuration.DeletableByViewer } + if ($Configuration.AccountId) { $PushParams.AccountId = $Configuration.AccountId.value } try { if ($PSCmdlet.ShouldProcess('Create a new PwPush link')) { $Link = New-Push @PushParams diff --git a/Modules/CippExtensions/Public/PwPush/Set-PwPushConfig.ps1 b/Modules/CippExtensions/Public/PwPush/Set-PwPushConfig.ps1 index 321534395f9f..6c816f6f5fc6 100644 --- a/Modules/CippExtensions/Public/PwPush/Set-PwPushConfig.ps1 +++ b/Modules/CippExtensions/Public/PwPush/Set-PwPushConfig.ps1 @@ -17,15 +17,24 @@ function Set-PwPushConfig { if ($Configuration.BaseUrl) { $InitParams.BaseUrl = $Configuration.BaseUrl } - if (![string]::IsNullOrEmpty($Configuration.EmailAddress)) { + if (![string]::IsNullOrEmpty($Configuration.EmailAddress) -or $Configuration.UseBearerAuth -eq $true) { $ApiKey = Get-ExtensionAPIKey -Extension 'PWPush' if (![string]::IsNullOrEmpty($ApiKey)) { $InitParams.APIKey = $ApiKey + } + if (![string]::IsNullOrEmpty($Configuration.EmailAddress)) { $InitParams.EmailAddress = $Configuration.EmailAddress } + if ($Configuration.UseBearerAuth -eq $true) { + $InitParams.AccountType = 'Pro' + } } + + $Module = Get-Module PassPushPosh -ListAvailable + Write-Host $Module.Version if ($PSCmdlet.ShouldProcess('Initialize-PassPushPosh')) { Initialize-PassPushPosh @InitParams } } + diff --git a/Modules/CippExtensions/Public/Sherweb/Get-SherwebCurrentSubscription.ps1 b/Modules/CippExtensions/Public/Sherweb/Get-SherwebCurrentSubscription.ps1 index 1c260ccd2cfd..aada3ea21a9c 100644 --- a/Modules/CippExtensions/Public/Sherweb/Get-SherwebCurrentSubscription.ps1 +++ b/Modules/CippExtensions/Public/Sherweb/Get-SherwebCurrentSubscription.ps1 @@ -6,12 +6,11 @@ function Get-SherwebCurrentSubscription { [string]$SKU, [string]$ProductName ) -if($TenantFilter){ - Get-ExtensionMapping -Extension 'Sherweb' | Where-Object { $_.RowKey -eq $TenantFilter } | ForEach-Object { - write-host "Extracted customer id from tenant filter - It's $($_.IntegrationId)" - $CustomerId = $_.IntegrationId + if ($TenantFilter) { + $TenantFilter = (Get-Tenants -TenantFilter $TenantFilter).customerId + $CustomerId = Get-ExtensionMapping -Extension 'Sherweb' | Where-Object { $_.RowKey -eq $TenantFilter } | Select-Object -ExpandProperty IntegrationId } -} + $AuthHeader = Get-SherwebAuthentication $Uri = "https://api.sherweb.com/service-provider/v1/billing/subscriptions/details?customerId=$CustomerId" $SubscriptionDetails = Invoke-RestMethod -Uri $Uri -Method GET -Headers $AuthHeader diff --git a/Modules/CippExtensions/Public/Sherweb/Set-SherwebMapping.ps1 b/Modules/CippExtensions/Public/Sherweb/Set-SherwebMapping.ps1 index f9f7b25e07b7..0fe51015c4b4 100644 --- a/Modules/CippExtensions/Public/Sherweb/Set-SherwebMapping.ps1 +++ b/Modules/CippExtensions/Public/Sherweb/Set-SherwebMapping.ps1 @@ -18,7 +18,7 @@ function Set-SherwebMapping { } Add-CIPPAzDataTableEntity @CIPPMapping -Entity $AddObject -Force - Write-LogMessage -API $APINAME -user $request.headers.'x-ms-client-principal' -message "Added mapping for $($mapping.name)." -Sev 'Info' + Write-LogMessage -API $APINAME -headers $Request.Headers -message "Added mapping for $($mapping.name)." -Sev 'Info' } $Result = [pscustomobject]@{'Results' = 'Successfully edited mapping table.' } diff --git a/Modules/PassPushPosh/0.3.0/PassPushPosh.psm1 b/Modules/PassPushPosh/0.3.0/PassPushPosh.psm1 deleted file mode 100644 index 7f6363d3f47d..000000000000 --- a/Modules/PassPushPosh/0.3.0/PassPushPosh.psm1 +++ /dev/null @@ -1,959 +0,0 @@ -class PasswordPush { - [string]$Payload - [string] hidden $__UrlToken - [string] hidden $__LinkBase - [bool]$RetrievalStep - [bool]$IsExpired - [bool]$IsDeleted - [bool]$IsDeletableByViewer - [int]$ExpireAfterDays - [int]$DaysRemaining - [int]$ExpireAfterViews - [int]$ViewsRemaining - [DateTime]$DateCreated - [DateTime]$DateUpdated - [DateTime]$DateExpired - # Added by constructors: - #[string]$URLToken - #[string]$Link - #[string]$LinkDirect - #[string]$LinkRetrievalStep - - PasswordPush() { - # Blank constructor - } - - # Constructor to allow casting or explicit import from a PSObject Representing the result of an API call - PasswordPush([PSCustomObject]$APIresponseObject) { - throw NotImplementedException - } - - # Allow casting or explicit import from the raw Content of an API call - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Scope = 'Function', Justification = 'Global variables are used for module session helpers.')] - PasswordPush([string]$JsonResponse) { - Write-Debug 'New PasswordPush object instantiated from JsonResponse string' - Initialize-PassPushPosh # Initialize the module if not yet done. - - $_j = $JsonResponse | ConvertFrom-Json - $this.Payload = $_j.payload - $this.IsExpired = $_j.expired - $this.IsDeleted = $_j.deleted - $this.IsDeletableByViewer = $_j.deletable_by_viewer - $this.ExpireAfterDays = $_j.expire_after_days - $this.DaysRemaining = $_j.days_remaining - $this.ExpireAfterViews = $_j.expire_after_views - $this.ViewsRemaining = $_j.views_remaining - $this.DateCreated = $_j.created_at - $this.DateUpdated = $_j.updated_at - $this.DateExpired = if ($_j.expired_on) { $_j.expired_on } else { [DateTime]0 } - - - $this | Add-Member -Name 'UrlToken' -MemberType ScriptProperty -Value { - return $this.__UrlToken - } -SecondValue { - $this.__UrlToken = $_ - $this.__LinkBase = "$Global:PPPBaseUrl/p/$($this.__UrlToken)" - } - $this.__UrlToken = $_j.url_token - $this.__LinkBase = "$Global:PPPBaseUrl/p/$($this.__UrlToken)" - $this | Add-Member -Name 'LinkDirect' -MemberType ScriptProperty -Value { return $this.__LinkBase } -SecondValue { - Write-Warning 'LinkDirect is a read-only calculated member.' - Write-Debug 'Link* members are calculated based on the Global BaseUrl and Push Retrieval Step values' - } - $this | Add-Member -Name 'LinkRetrievalStep' -MemberType ScriptProperty -Value { return "$($this.__LinkBase)/r" } -SecondValue { - Write-Warning 'LinkRetrievalStep is a read-only calculated member.' - Write-Debug 'Link* members are calculated based on the Global BaseUrl and Push Retrieval Step values' - } - $this | Add-Member -Name 'Link' -MemberType ScriptProperty -Value { - $_Link = if ($this.RetrievalStep) { $this.LinkRetrievalStep } else { $this.LinkDirect } - Write-Debug "Presented Link: $_link" - return $_Link - } -SecondValue { - Write-Warning 'Link is a read-only calculated member.' - Write-Debug 'Link* members are calculated based on the Global BaseUrl and Push Retrieval Step values' - } - } -} - -function ConvertTo-PasswordPush { - <# - .SYNOPSIS - Convert API call response to a PasswordPush object - - .DESCRIPTION - Accepts a JSON string returned from the Password Pusher API and converts it to a [PasswordPush] object. - This allows calculated push retrieval URLs and a more "PowerShell" experience. - Generally you won't need to use this directly, it's automatically invoked within Register-Push and Request-Push. - - .INPUTS - [string] - - .OUTPUTS - [PasswordPush] for single object - [PasswordPush[]] for Json array data - - .EXAMPLE - # Common usage - from within the Register-Push cmdlet - PS> $myPush = Register-Push -Payload "This is my secret!" - PS> $myPush.Link # The link parameter always presents the URL as it would appear with the same settings selected on pwpush.com - - https://pwpush.com/p/rz6nryvl-d4 - - .EXAMPLE - # Manually invoking the API - PS> $rawJson = Invoke-WebRequest ` - -Uri https://pwpush.com/p.json ` - -Method Post ` - -Body '{"password": { "payload": "This is my secret!"}}' ` - -ContentType 'application/json' | - Select-Object -ExpandProperty Content - PS> $rawJson - {"expire_after_days":7,"expire_after_views":5,"expired":false,"url_token":"rz6nryvl-d4","created_at":"2022-11-18T14:16:29.821Z","updated_at":"2022-11-18T14:16:29.821Z","deleted":false,"deletable_by_viewer":true,"retrieval_step":false,"expired_on":null,"days_remaining":7,"views_remaining":5} - PS> $rawJson | ConvertTo-PasswordPush - UrlToken : rz6nryvl-d4 - LinkDirect : https://pwpush.com/p/rz6nryvl-d4 - LinkRetrievalStep : https://pwpush.com/p/rz6nryvl-d4/r - Link : https://pwpush.com/p/rz6nryvl-d4 - Payload : - RetrievalStep : False - IsExpired : False - IsDeleted : False - IsDeletableByViewer : True - ExpireAfterDays : 7 - DaysRemaining : 7 - ExpireAfterViews : 5 - ViewsRemaining : 5 - DateCreated : 11/18/2022 2:16:29 PM - DateUpdated : 11/18/2022 2:16:29 PM - DateExpired : 1/1/0001 12:00:00 AM - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/ConvertTo-PasswordPush.md - - .NOTES - Needs a rewrite / cleanup - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope = 'Function', Justification = 'Creates a new object, no risk of overwriting data.')] - [CmdletBinding()] - [OutputType([PasswordPush])] - param( - # The string result of an API call from the Password Pusher application - [parameter(Mandatory, ValueFromPipeline)] - [ValidateNotNullOrEmpty()] - [string]$JsonResponse - ) - process { - try { - $jsonObject = $JsonResponse | ConvertFrom-Json - foreach ($o in $jsonObject) { - [PasswordPush]($o | ConvertTo-Json) # TODO fix this mess - } - } - catch { - Write-Debug 'Error in ConvertTo-PasswordPush coercing JSON object to PasswordPush object' - Write-Debug "JsonResponse parameter value: [[$JsonResponse]]" - Write-Error $_ - } - } -} -function Get-Dashboard { - <# - .SYNOPSIS - Get a list of active or expired Pushes for an authenticated user - - .DESCRIPTION - Retrieves a list of Pushes - active or expired - for an authenticated user. - Active and Expired are different endpoints, so to get both you'll need to make - two calls. - - .INPUTS - [string] 'Active' or 'Expired' - - .OUTPUTS - [PasswordPush[]] Array of pushes with data - [string] raw response body from API call - - .EXAMPLE - Get-Dashboard - - .EXAMPLE - Get-Dashboard Active - - .EXAMPLE - Get-Dashboard -Dashboard Expired - - .EXAMPLE - Get-Dashboard -Raw - [{"expire_after_days":1,"expire_after_views":5,"expired":false,"url_token":"xm3q7czvtdpmyg","created_at":"2022-11-19T18:10:42.055Z","updated_at":"2022-11-19T18:10:42.055Z","deleted":false,"deletable_by_viewer":true,"retrieval_step":false,"expired_on":null,"note":null,"days_remaining":1,"views_remaining":3}] - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-Dashboard.md - - .LINK - https://pwpush.com/api/1.0/dashboard.en.html - - .LINK - Get-PushAuditLog - - .NOTES - TODO update Invoke-Webrequest flow and error-handling to match other functions - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Scope = 'Function', Justification = 'Global variables are used for module session helpers.')] - [CmdletBinding()] - [OutputType([PasswordPush[]],[string])] - param( - # URL Token from a secret - [parameter(Position=0)] - [ValidateSet('Active','Expired')] - [ValidateNotNullOrEmpty()] - [string] - $Dashboard = 'Active', - - # Return content of API call directly - [Parameter()] - [switch] - $Raw - ) - if (-not $Global:PPPHeaders) { Write-Error 'Dashboard access requires authentication. Run Initialize-PassPushPosh and pass your email address and API key before retrying.' -ErrorAction Stop -Category AuthenticationError } - try { - $uri = "$Global:PPPBaseUrl/d/" - if ($Dashboard -eq 'Active') { $uri += 'active.json' } - elseif ($Dashboard -eq 'Expired') { $uri += 'expired.json' } - Write-Debug "Requesting $uri" - $response = Invoke-WebRequest -Uri $uri -Method Get -Headers $Global:PPPHeaders -ErrorAction Stop - if ($Raw) { return $response.Content } - else { - return $response.Content | ConvertTo-PasswordPush - } - } catch { - Write-Verbose "An exception was caught: $($_.Exception.Message)" - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name 'PPPLastError' -Value $_ - Write-Debug -Message 'Response object set to global variable $PPPLastError' - } - throw # Re-throw the error - } -} -function Get-Push { - <# - .SYNOPSIS - Retrieve the secret contents of a Push - - .DESCRIPTION - Accepts a URL Token string, returns the contents of a Push along with - metadata regarding that Push. Note, Get-Push will return data on an expired - Push (datestamps, etc) even if it does not return the Push contents. - - .INPUTS - [string] - - .OUTPUTS - [PasswordPush] or [string] - - .EXAMPLE - Get-Push -URLToken gzv65wiiuciy - - .EXAMPLE - Get-Push -URLToken gzv65wiiuciy -Raw - {"payload":"I am your payload!","expired":false,"deleted":false,"expired_on":"","expire_after_days":1,"expire_after_views":4,"url_token":"bwzehzem_xu-","created_at":"2022-11-21T13:20:08.635Z","updated_at":"2022-11-21T13:23:45.342Z","deletable_by_viewer":true,"retrieval_step":false,"days_remaining":1,"views_remaining":4} - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-Push.md - - .LINK - https://pwpush.com/api/1.0/passwords/show.en.html - - .LINK - New-Push - - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Scope='Function',Justification='Global variables are used for module session helpers.')] - [CmdletBinding()] - [OutputType([PasswordPush])] - param( - # URL Token for the secret - [parameter(Mandatory,ValueFromPipeline,Position=0)] - [ValidateNotNullOrEmpty()] - [Alias('Token')] - $URLToken, - - # Return the raw response body from the API call - [Parameter()] - [switch] - $Raw - ) - begin { Initialize-PassPushPosh -Verbose:$VerbosePreference -Debug:$DebugPreference } - - process { - try { - $iwrSplat = @{ - 'Method' = 'Get' - 'ContentType' = 'application/json' - 'Uri' = "$Global:PPPBaseUrl/p/$URLToken.json" - 'UserAgent' = $Global:PPPUserAgent - } - if ($Global:PPPHeaders) { $iwrSplat['Headers'] = $Global:PPPHeaders } - Write-Verbose "Sending HTTP request: $($iwrSplat | Out-String)" - $response = Invoke-WebRequest @iwrSplat -ErrorAction Stop - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name PPPLastCall -Value $response - Write-Debug 'Response to Invoke-WebRequest set to PPPLastCall Global variable' - } - if ($Raw) { - Write-Debug "Returning raw object:`n$($response.Content)" - return $response.Content - } - return $response.Content | ConvertTo-PasswordPush - } catch { - Write-Verbose "An exception was caught: $($_.Exception.Message)" - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name PPPLastError -Value $_ - Write-Debug -Message 'Response object set to global variable $PPPLastError' - } - } - } -} -function Get-PushAuditLog { - <# - .SYNOPSIS - Get the view log of an authenticated Push - - .DESCRIPTION - Retrieves the view log of a Push created under an authenticated session. - Returns an array of custom objects with view data. If the query is - successful but there are no results, it returns an empty array. - If there's an error, a single object is returned with information. - See "handling errors" under NOTES - - .INPUTS - [string] - - .OUTPUTS - [PsCustomObject[]] Array of entries. - [PsCustomObject] If there's an error in the call, it will be returned an object with a property - named 'error'. The value of that member will contain more information - - .EXAMPLE - Get-PushAuditLog -URLToken 'mytokenfromapush' - ip : 75.202.43.56,102.70.135.200 - user_agent : Mozilla/5.0 (Macintosh; Darwin 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:20:05 PDT 2022; root:xnu-8020.140.49~2/RELEASE_ARM64_T8101; - en-US) PowerShell/7.2.7 - referrer : - successful : True - created_at : 11/19/2022 6:32:42 PM - updated_at : 11/19/2022 6:32:42 PM - kind : 0 - - .EXAMPLE - # If there are no views, an empty array is returned - Get-PushAuditLog -URLToken 'mytokenthatsneverbeenseen' - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-PushAuditLog.md - - .LINK - https://pwpush.com/api/1.0/passwords/audit.en.html - - .LINK - Get-Dashboard - - .NOTES - Handling Errors: - The API returns different HTTP status codes and results depending where the - call fails. - - | HTTP RESPONSE | Error Reason | Response Body | Sample Object Returned | Note | - |------------------|---------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------| - | 401 UNAUTHORIZED | Invalid API key or email | None | @{ 'Error'= 'Authentication error. Verify email address and API key.'; 'ErrorCode'= 401 } | | - | 200 OK | Push created by another account | {"error":"That push doesn't belong to you."} | @{ 'Error'= "That Push doesn't belong to you"; 'ErrorCode'= 403 } | Function transforms error code to 403 to allow easier response management | - | 404 NOT FOUND | Invalid URL token | None | @{ 'Error'= 'Invalid token. Verify your Push URL token is correct.'; 'ErrorCode'= 404 } | This is different than the response to a delete Push query - in this case it will only return 404 if the token is invalid. | - - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Scope = 'Function', Justification = 'Global variables are used for module session helpers.')] - [CmdletBinding()] - [OutputType([PSCustomObject[]],[string])] - param( - # URL Token from a secret - [parameter(ValueFromPipeline)] - [ValidateNotNullOrEmpty()] - [string] - $URLToken, - - # Return content of API call directly - [Parameter()] - [switch] - $Raw - ) - begin { - if (-not $Global:PPPHeaders) { Write-Error 'Retrieving audit logs requires authentication. Run Initialize-PassPushPosh and pass your email address and API key before retrying.' -ErrorAction Stop -Category AuthenticationError } - } - process { - try { - $uri = "$Global:PPPBaseUrl/p/$URLToken/audit.json" - Write-Debug 'Requesting $uri' - $response = Invoke-WebRequest -Uri $uri -Method Get -Headers $Global:PPPHeaders -ErrorAction Stop - if ([int]$response.StatusCode -eq 200 -and $response.Content -ieq "{`"error`":`"That push doesn't belong to you.`"}") { - $result = [PSCustomObject]@{ 'Error' = "That Push doesn't belong to you"; 'ErrorCode' = 403 } - Write-Warning $result.Error - return $result - } - if ($Raw) { return $response.Content } else { return $response.Content | ConvertFrom-Json } - } - catch { - Write-Verbose "An exception was caught: $($_.Exception.Message)" - if ([int]$_.Exception.Response.StatusCode -eq 401) { # Could be optimized - $result = [PSCustomObject]@{ 'Error' = 'Authentication error. Verify email address and API key.'; 'ErrorCode' = 401 } - Write-Warning $result.Error - return $result - } elseif ([int]$_.Exception.Response.StatusCode -eq 404) { - $result = [PSCustomObject]@{ 'Error' = 'Invalid token. Verify your Push URL token is correct.'; 'ErrorCode' = 404 } - Write-Warning $result.Error - return $result - } - elseif ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name 'PPPLastError' -Value $_ - Write-Debug -Message 'Response object set to global variable $PPPLastError' - return [PSCustomObject]@{ - 'Error' = $_.Exception.Message - 'ErrorCode' = [int]$_.Exception.Response.StatusCode - 'ErrorMessage' = $_.Exception.Response.ReasonPhrase - } - } - } - } -} - -# Invalid API key / email - 401 -# Invalid URL Token - 404 -# Valid token but not mine - 200, content = {"error":"That push doesn't belong to you."} -# Success but no views - 200, content = : {"views":[]} -# Success with view history {"views":[{"ip":"75.118.137.58,172.70.135.200","user_agent":"Mozilla/5.0 (Macintosh; Darwin 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:20:05 PDT 2022; root:xnu-8020.140.49~2/RELEASE_ARM64_T8101; en-US) PowerShell/7.2.7","referrer":"","successful":true,"created_at":"2022-11-19T18:32:42.277Z","updated_at":"2022-11-19T18:32:42.277Z","kind":0}]} -# Content.Views -<# -ip : 75.118.137.58,172.70.135.200 -user_agent : Mozilla/5.0 (Macintosh; Darwin 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:20:05 PDT 2022; root:xnu-8020.140.49~2/RELEASE_ARM64_T8101; -en-US) PowerShell/7.2.7 -referrer : -successful : True -created_at : 11/19/2022 6:32:42 PM -updated_at : 11/19/2022 6:32:42 PM -kind : 0 -#> -function Get-SecretLink { - <# - .SYNOPSIS - Returns a fully qualified secret link to a push of given URL Token - - .DESCRIPTION - Accepts a string value for a URL Token and retrieves a full URL link to the secret. - Returned value is a 1-step retrieval link depending on option selected during Push creation. - Returns false if URL Token is invalid, however it will return a URL if the token is valid - but the Push is expired or deleted. - - .INPUTS - [string] URL Token value - - .OUTPUTS - [string] Fully qualified URL - [bool] $False if Push URL Token is invalid. Note: Expired or deleted Pushes will still return a link. - - .EXAMPLE - Get-SecretLink -URLToken gzv65wiiuciy - https://pwpush.com/p/gzv65wiiuciy/r - - .EXAMPLE - Get-SecretLink -URLToken gzv65wiiuciy -Raw - { "url": "https://pwpush.com/p/0fkapnbo_pwp4gi8uy0/r" } - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-SecretLink.md - - .LINK - https://pwpush.com/api/1.0/passwords/preview.en.html - - .NOTES - Including this endpoint for completeness - however it is generally unnecessary. - The only thing this endpoint does is return a different value depending if "Use 1-click retrieval step" - was selected when the Push was created. Since both the 1-click and the direct links are available - regardless if that option is selected, the links are calculable and both are included by default in a - [PasswordPush] object. - - As it returns false if a Push URL token is not valid you can use it to test if a Push exists without - burning a view. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Scope='Function',Justification='Global variables are used for module session helpers.')] - [CmdletBinding()] - [Alias('Get-PushPreview')] - [OutputType('[string]')] - param( - # URL Token for the secret - [parameter(Mandatory, ValueFromPipeline)] - [ValidateLength(5, 256)] - [string]$URLToken, - - # Return the raw response body from the API call - [Parameter()] - [switch] - $Raw - ) - begin { Initialize-PassPushPosh -Verbose:$VerbosePreference -Debug:$DebugPreference } - process { - try { - $iwrSplat = @{ - 'Method' = 'Get' - 'ContentType' = 'application/json' - 'Uri' = "$Global:PPPBaseUrl/p/$URLToken/preview.json" - 'UserAgent' = $Global:PPPUserAgent - } - if ($Global:PPPHeaders) { $iwrSplat['Headers'] = $Global:PPPHeaders } - Write-Verbose "Sending HTTP request: $($iwrSplat | Out-String)" - $responseContent = Invoke-WebRequest @iwrSplat | Select-Object -ExpandProperty Content - if ($Raw) { return $responseContent } - else { return $responseContent | ConvertFrom-Json | Select-Object -ExpandProperty url } - } - catch { - Write-Verbose "An exception was caught: $($_.Exception.Message)" - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name 'PPPLastError' -Value $_ - Write-Debug -Message 'Response object set to global variable $PPPLastError' - } - } - } -} -function Initialize-PassPushPosh { - <# - .SYNOPSIS - Initialize the PassPushPosh module - - .DESCRIPTION - Sets global variables to handle the server URL and headers (authentication). - Called automatically by module Functions if it is not called explicitly prior, so you don't actually need - to call it unless you're going to use the authenticated API or alternate server, etc - Default parameters use the pwpush.com domain and anonymous authentication. - - .EXAMPLE - # Initialize with default settings - PS > Initialize-PassPushPosh - - .EXAMPLE - # Initialize with authentication - PS > Initialize-PassPushPosh -EmailAddress 'youremail@example.com' -ApiKey '239jf0jsdflskdjf' -Verbose - - VERBOSE: Initializing PassPushPosh. ApiKey: [x-kdjf], BaseUrl: https://pwpush.com - - .EXAMPLE - # Initialize with another server with authentication - PS > Initialize-PassPushPosh -BaseUrl https://myprivatepwpushinstance.com -EmailAddress 'youremail@example.com' -ApiKey '239jf0jsdflskdjf' -Verbose - - VERBOSE: Initializing PassPushPosh. ApiKey: [x-kdjf], BaseUrl: https://myprivatepwpushinstance.com - - .EXAMPLE - # Set a custom User Agent - PS > InitializePassPushPosh -UserAgent "I'm a cool dude with a cool script." - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/Initialize-PassPushPosh.md - - .NOTES - All variables set by this function start with PPP. - - PPPHeaders - - PPPUserAgent - - PPPBaseUrl - - -WhatIf setting for Set-Variable -Global is disabled, otherwise -WhatIf - calls for other functions would return incorrect data in the case this - function has not yet run. - - TODO: Review API key pattern for parameter validation - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Scope='Function',Justification='Global variables are used for module session helpers.')] - [CmdletBinding(DefaultParameterSetName='Anonymous')] - param ( - # Email address to use for authenticated calls. - [Parameter(Mandatory,Position=0,ParameterSetName='Authenticated')] - [ValidatePattern('.+\@.+\..+')] - [string]$EmailAddress, - - # API Key for authenticated calls. - [Parameter(Mandatory,Position=1,ParameterSetName='Authenticated')] - [ValidateLength(5,256)] - [string]$ApiKey, - - # Base URL for API calls. Allows use of module with private instances of Password Pusher - # Default: https://pwpush.com - [Parameter(Position=0,ParameterSetName='Anonymous')] - [Parameter(Position=2,ParameterSetName='Authenticated')] - [ValidatePattern('^https?:\/\/[a-zA-Z0-9-_]+.[a-zA-Z0-9]+')] - [string]$BaseUrl, - - # Set a specific user agent. Default user agent is a combination of the - # module info, what your OS reports itself as, and a hash based on - # your username + workstation or domain name. This way the UA can be - # semi-consistent across sessions but not identifying. - [Parameter()] - [ValidateNotNullOrEmpty()] - [string] - $UserAgent, - - # Force setting new information. If module is already initialized you can use this to - # Re-initialize with default settings. Implied if either ApiKey or BaseUrl is provided. - [Parameter()][switch]$Force - ) - if ($Global:PPPBaseURL -and $true -inotin $Force, [bool]$ApiKey, [bool]$BaseUrl, [bool]$UserAgent) { Write-Debug -Message 'PassPushPosh is already initialized.' } - else { - $defaultBaseUrl = 'https://pwpush.com' - $apiKeyOutput = if ($ApiKey) { 'x-' + $ApiKey.Substring($ApiKey.Length-4) } else { 'None' } - - if (-not $Global:PPPBaseURL) { # Not initialized - if (-not $BaseUrl) { $BaseUrl = $defaultBaseUrl } - Write-Verbose "Initializing PassPushPosh. ApiKey: [$apiKeyOutput], BaseUrl: $BaseUrl" - } elseif ($Force -or $ApiKey -or $BaseURL) { - if (-not $BaseUrl) { $BaseUrl = $defaultBaseUrl } - $oldApiKeyOutput = if ($Global:PPPApiKey) { 'x-' + $Global:PPPApiKey.Substring($Global:PPPApiKey.Length-4) } else { 'None' } - Write-Verbose "Re-initializing PassPushPosh. Old ApiKey: [$oldApiKeyOutput] New ApiKey: [$apiKeyOutput], Old BaseUrl: $Global:PPPBaseUrl New BaseUrl: $BaseUrl" - } - if ($PSCmdlet.ParameterSetName -eq 'Authenticated') { - Set-Variable -Scope Global -Name PPPHeaders -WhatIf:$false -Value @{ - 'X-User-Email' = $EmailAddress - 'X-User-Token' = $ApiKey - } - } elseif ($Global:PPPHeaders) { # Remove if present - covers case where module is reinitialized from an authenticated to an anonymous session - Remove-Variable -Scope Global -Name PPPHeaders -WhatIf:$false - } - - if (-not $UserAgent) { - $osVersion = [System.Environment]::OSVersion - $userAtDomain = "{0}@{1}" -f [System.Environment]::UserName, [System.Environment]::UserDomainName - $uAD64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($userAtDomain)) - Write-Debug "$userAtDomain transformed to $uAD64. First 20 characters $($uAD64.Substring(0,20))" - $UserAgent = "PassPushPosh/$((Get-Module -Name PassPushPosh).Version.ToString()) $osVersion/$($uAD64.Substring(0,20))" - Write-Verbose "Generated user agent: $UserAgent" - } else { - Write-Verbose "Using specified user agent: $UserAgent" - } - - Set-Variable -WhatIf:$false -Scope Global -Name PPPBaseURL -Value $BaseUrl.TrimEnd('/') - Set-Variable -WhatIf:$false -Scope Global -Name PPPUserAgent -Value $UserAgent - } -} -function New-PasswordPush { - <# - .SYNOPSIS - Create a new blank Password Push object. - - .DESCRIPTION - Creates a blank [PasswordPush]. - Generally not needed, use ConvertTo-PasswordPush - See New-Push if you're trying to create a new secret to send - - .INPUTS - None - - .OUTPUTS - [PasswordPush] - - .EXAMPLE - New-PasswordPush - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/New-PasswordPush.md - - .NOTES - TODO Rewrite - make this work including read-only properties - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope = 'Function', Justification = 'Creates a new object, no risk of overwriting data.')] - [CmdletBinding()] - param () - return [PasswordPush]::new() -} -function New-Push { - <# - .SYNOPSIS - Create a new Password Push - - .DESCRIPTION - Create a new Push on the specified Password Pusher instance. The - programmatic equivalent of going to pwpush.com and entering info. - Returns [PasswordPush] object. Link member is a link created based on - 1-step setting however both 1-step and direct links - are always provided at LinkRetrievalStep and LinkDirect. - - .EXAMPLE - $myPush = New-Push "Here's my secret!" - PS > $myPush | Select-Object Link, LinkRetrievalStep, LinkDirect - - Link : https://pwpush.com/p/gzv65wiiuciy # Requested style - LinkRetrievalStep : https://pwpush.com/p/gzv65wiiuciy/r # 1-step - LinkDirect : https://pwpush.com/p/gzv65wiiuciy # Direct - - .EXAMPLE - "Super secret secret" | New-Push -RetrievalStep | Select-Object -ExpandProperty Link - - https://pwpush.com/p/gzv65wiiuciy/r - - - .EXAMPLE - # "Burn after reading" style Push - PS > New-Push -Payload "Still secret text!" -ExpireAfterViews 1 -RetrievalStep - - .INPUTS - [string] - - .OUTPUTS - [PasswordPush] Push object - [string] Raw result of API call - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/New-Push.md - - .LINK - https://pwpush.com/api/1.0/passwords/create.en.html - - .LINK - Get-Push - - .NOTES - Maximum for -ExpireAfterDays and -ExpireAfterViews is based on the default - values for Password Pusher and what's used on the public instance - (pwpush.com). If you're using this with a private instance and want to - override that value you'll need to fork this module. - - TODO: Support [PasswordPush] input objects, testing - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Scope='Function',Justification='Global variables are used for module session helpers.')] - [CmdletBinding(SupportsShouldProcess,ConfirmImpact='Low',DefaultParameterSetName='Anonymous')] - [OutputType([PasswordPush],[string],[bool])] # Returntype should be [PasswordPush] but I've yet to find a way to add class access to a function on a module... - param( - # The password or secret text to share. - [Parameter(Mandatory=$true,ValueFromPipeline,Position=0)] - [Alias('Password')] - [ValidateNotNullOrEmpty()] - [string]$Payload, - - # Label for this Push (requires Authenticated session) - [Parameter(ParameterSetName='RequiresAuthentication')] - [ValidateNotNullOrEmpty()] - [string]$Note, - - # Expire secret link and delete after this many days. - [Parameter()] - [ValidateRange(1,90)] - [int] - $ExpireAfterDays, - - # Expire secret link after this many views. - [Parameter()] - [ValidateRange(1,100)] - [int] - $ExpireAfterViews, - - # Allow the recipient of a Push to delete it. - [Parameter()] - [switch] - $DeletableByViewer, - - # Require recipient click an extra link to view Push payload. - # Helps to avoid chat systems and URL scanners from eating up views. - # Note that the retrieval step URL is always available for a push. This - # parameter changes if the 1-click link is used in the Link parameter - # and returned from the secret link helper (Get-SecretLink) - [Parameter()] - [switch] - $RetrievalStep, - - # Return the raw response body from the API call - [Parameter()] - [switch] - $Raw - ) - - begin { - Initialize-PassPushPosh -Verbose:$VerbosePreference -Debug:$DebugPreference - } - - process { - if ($PSCmdlet.ParameterSetName -eq 'RequiresAuthentication' -and -not $Global:PPPHeaders.'X-User-Token') { Write-Error -Message 'Setting a note requires an authenticated call.'; return $false } - - $body = @{ - 'password' = @{ - 'payload' = $Payload - } - } - $shouldString = 'Submit {0} push with Payload of length {1}' -f $PSCmdlet.ParameterSetName, $Payload.Length - if ($Note) { - $body.password.note = $note - $shouldString += " with note $note" - } - if ($ExpireAfterDays) { - $body.password.expire_after_days = $ExpireAfterDays - $shouldString += ', expire after {0} days' -f $ExpireAfterDays - } - if ($ExpireAfterViews) { - $body.password.expire_after_views = $ExpireAfterViews - $shouldString += ', expire after {0} views' -f $ExpireAfterViews - } - $body.password.deletable_by_viewer = if ($DeletableByViewer) { - $shouldString += ', deletable by viewer' - $true - } else { - $shouldString += ', NOT deletable by viewer' - $false - } - $body.password.retrieval_step = if ($RetrievalStep) { - $shouldString += ', with a 1-click retrieval step' - $true - } else { - $shouldString += ', with a direct link' - $false - } - if ($VerbosePreference -eq [System.Management.Automation.ActionPreference]::Continue) { - # Sanitize input so we're not logging or outputting the payload - $vBody = $body.Clone() - $vBody.password.payload = "A payload of length $($body.password.payload.Length.ToString())" - $vBs = $vBody | ConvertTo-Json | Out-String - Write-Verbose "Call Body (sanitized): $vBs" - } - - $iwrSplat = @{ - 'Method' = 'Post' - 'ContentType' = 'application/json' - 'Body' = ($body | ConvertTo-Json) - 'Uri' = "$Global:PPPBaseUrl/p.json" - 'UserAgent' = $Global:PPPUserAgent - } - if ($Global:PPPHeaders.'X-User-Token') { $iwrSplat['Headers'] = $Global:PPPHeaders } - Write-Verbose "Sending HTTP request (minus body): $($iwrSplat | Select-Object Method,ContentType,Uri,UserAgent,Headers | Out-String)" - if ($PSCmdlet.ShouldProcess($shouldString, $iwrSplat.Uri, 'Submit new Push')) { - try { - $response = Invoke-WebRequest @iwrSplat - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name PPPLastCall -Value $response - Write-Debug 'Response to Invoke-WebRequest set to PPPLastCall Global variable' - } - if ($Raw) { - Write-Debug "Returning raw object: $($response.Content)" - return $response.Content - } - return $response.Content | ConvertTo-PasswordPush - } catch { - Write-Verbose "An exception was caught: $($_.Exception.Message)" - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name PPPLastError -Value $_ - Write-Debug -Message 'Response object set to global variable $PPPLastError' - } - } - } - } -} -function Remove-Push { - <# - .SYNOPSIS - Remove a Push - - .DESCRIPTION - Remove (invalidate) an active push. Requires the Push be either set as - deletable by viewer, or that you are authenticated as the creator of the - Push. - - If you have authorization to delete a push (deletable by viewer TRUE or - you are the Push owner) the endpoint will always return 200 OK with a Push - object, regardless if the Push was previously deleted or expired. - - If the Push URL Token is invalid OR you are not authorized to delete the - Push, the endpoint returns 404 and this function returns $false - - .INPUTS - [string] URL Token - [PasswordPush] representing the Push to remove - - .OUTPUTS - [bool] True on success, otherwise False - - .EXAMPLE - Remove-Push -URLToken bwzehzem_xu- - - .EXAMPLE - Remove-Push -URLToken -Raw - {"expired":true,"deleted":true,"expired_on":"2022-11-21T13:23:45.341Z","expire_after_days":1,"expire_after_views":4,"url_token":"bwzehzem_xu-","created_at":"2022-11-21T13:20:08.635Z","updated_at":"2022-11-21T13:23:45.342Z","deletable_by_viewer":true,"retrieval_step":false,"days_remaining":1,"views_remaining":4} - - .LINK - https://github.com/adamburley/PassPushPosh/blob/main/Docs/Remove-Push.md - - .LINK - https://pwpush.com/api/1.0/passwords/destroy.en.html - - .NOTES - TODO testing and debugging - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Scope='Function',Justification='Global variables are used for module session helpers.')] - [CmdletBinding(SupportsShouldProcess,DefaultParameterSetName='Token')] - [OutputType([PasswordPush],[string],[bool])] - param( - # URL Token for the secret - [parameter(ValueFromPipeline,ParameterSetName='Token')] - [ValidateNotNullOrEmpty()] - [Alias('Token')] - [string] - $URLToken, - - # PasswordPush object - [Parameter(ValueFromPipeline,ParameterSetName='Object')] - [PasswordPush] - $PushObject, - - # Return the raw response body from the API call - [parameter()] - [switch] - $Raw - ) - process { - try { - if ($PSCmdlet.ParameterSetName -eq 'Object') { - Write-Debug -Message "Remove-Push was passed a PasswordPush object with URLToken: [$($PushObject.URLToken)]" - if (-not $PushObject.IsDeletableByViewer -and -not $Global:PPPHeaders) { #Pre-qualify if this will succeed - Write-Warning -Message 'Unable to remove Push. Push is not marked as deletable by viewer and you are not authenticated.' - return $false - } - if ($PushObject.IsDeletableByViewer) { - Write-Verbose "Push is flagged as deletable by viewer, should be deletable." - } else { Write-Verbose "In an authenticated API session. Push will be deletable if it was created by authenticated user." } - $URLToken = $PushObject.URLToken - } else { - Write-Debug -Message "Remove-Push was passed a URLToken: [$URLToken]" - } - Write-Verbose -Message "Push with URL Token [$URLToken] will be deleted if 'Deletable by viewer' was enabled or you are the creator of the push and are authenticated." - $iwrSplat = @{ - 'Method' = 'Delete' - 'ContentType' = 'application/json' - 'Uri' = "$Global:PPPBaseUrl/p/$URLToken.json" - 'UserAgent' = $Global:PPPUserAgent - } - if ($Global:PPPHeaders) { $iwrSplat['Headers'] = $Global:PPPHeaders } - Write-Verbose "Sending HTTP request: $($iwrSplat | Out-String)" - if ($PSCmdlet.ShouldProcess('Delete',"Push with token [$URLToken]")) { - $response = Invoke-WebRequest @iwrSplat - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name PPPLastCall -Value $response - Write-Debug 'Response to Invoke-WebRequest set to PPPLastCall Global variable' - } - if ($Raw) { - Write-Debug "Returning raw object: $($response.Content)" - return $response.Content - } - return $response.Content | ConvertTo-PasswordPush - } - } catch { - if ($_.Exception.Response.StatusCode -eq 404) { - Write-Warning "Failed to delete Push. This can indicate an invalid URL Token, that the password was not marked deletable, or that you are not the owner." - return $false - } else { - Write-Verbose "An exception was caught: $($_.Exception.Message)" - if ($DebugPreference -eq [System.Management.Automation.ActionPreference]::Continue) { - Set-Variable -Scope Global -Name PPPLastError -Value $_ - Write-Debug -Message 'Response object set to global variable $PPPLastError' - } - $_ - } - } - } -} diff --git a/Modules/PassPushPosh/0.3.0/PSGetModuleInfo.xml b/Modules/PassPushPosh/1.2.1/PSGetModuleInfo.xml similarity index 53% rename from Modules/PassPushPosh/0.3.0/PSGetModuleInfo.xml rename to Modules/PassPushPosh/1.2.1/PSGetModuleInfo.xml index f18deba883e8..0189606b3555 100644 --- a/Modules/PassPushPosh/0.3.0/PSGetModuleInfo.xml +++ b/Modules/PassPushPosh/1.2.1/PSGetModuleInfo.xml @@ -7,18 +7,18 @@ PassPushPosh - 0.3.0 + 1.2.0 Module - *PassPushPosh* is a PowerShell Module for interfacing with the Password Pusher secure password / string sharing application, primarily through pwpush.com. It supports creating, retrieving, and deleting anonymous and authenticated pushes and getting Push and Dashboard data for authenticated users._x000D__x000A__x000D__x000A_Cmdlets provide clear responses to errors, support additional messaging via -Debug and -Verbose, transaction testing via -Whatif and -Confirm, and in general try to be as "Powershell-y" as possible. + PassPushPosh is a PowerShell Module for accessing the Password Pusher application via API. It supports creating, retrieving, and deleting anonymous and authenticated pushes and getting Push and Dashboard data for authenticated users. Adam Burley AdamBurley Adam Burley, 2022 -
2024-07-24T01:39:52-04:00
+
2025-02-06T18:21:26-05:00
https://www.gnu.org/licenses/gpl-3.0.en.html https://github.com/adamburley/PassPushPosh - + https://github.com/adamburley/PassPushPosh/blob/main/pwplogo85x85.png?raw=true System.Object[] @@ -26,7 +26,6 @@ System.Object - PSEdition_Desktop PSEdition_Core Windows Linux @@ -42,34 +41,47 @@ - Command + DscResource + + + + + + Function + - ConvertTo-PasswordPush Get-Dashboard Get-Push + Get-PushAccount Get-PushAuditLog Get-SecretLink Initialize-PassPushPosh - New-PasswordPush New-Push Remove-Push - Function - + RoleCapability + + + + Workflow + + + + Command + - ConvertTo-PasswordPush Get-Dashboard Get-Push + Get-PushAccount Get-PushAuditLog Get-SecretLink Initialize-PassPushPosh - New-PasswordPush New-Push Remove-Push @@ -77,27 +89,12 @@ Cmdlet - - - - - - - RoleCapability - - - - DscResource - - - - Workflow - + - 0.3.0 - Remove route translations from URI segments for compatibility with PasswordPusher v1.42.0. See pglombardo/PasswordPusher/pull/2353_x000D__x000A_ 0.2.3 - Bug fixing in New-Push. See PR #1_x000D__x000A_ 0.2.2 - Fixed issue with Get-Dashboard returning error referencing -JsonIsArray parameter_x000D__x000A_ General - Module is generally functional but has not been extensively bug-tested. Reccomend not implementing into a production environment at this time. + 1.2.0 - Add compatibility with Premium and Pro API endpoints and branding._x000D__x000A_ 1.0.0 - Major refactor, add capabilities and improve testing and build process._x000D__x000A_ 0.3.0 - Remove route translations from URI segments for compatibility with PasswordPusher v1.42.0. See pglombardo/PasswordPusher/pull/2353 @@ -112,31 +109,31 @@ Adam Burley, 2022 - *PassPushPosh* is a PowerShell Module for interfacing with the Password Pusher secure password / string sharing application, primarily through pwpush.com. It supports creating, retrieving, and deleting anonymous and authenticated pushes and getting Push and Dashboard data for authenticated users._x000D__x000A__x000D__x000A_Cmdlets provide clear responses to errors, support additional messaging via -Debug and -Verbose, transaction testing via -Whatif and -Confirm, and in general try to be as "Powershell-y" as possible. + PassPushPosh is a PowerShell Module for accessing the Password Pusher application via API. It supports creating, retrieving, and deleting anonymous and authenticated pushes and getting Push and Dashboard data for authenticated users. False - 0.3.0 - Remove route translations from URI segments for compatibility with PasswordPusher v1.42.0. See pglombardo/PasswordPusher/pull/2353_x000D__x000A_ 0.2.3 - Bug fixing in New-Push. See PR #1_x000D__x000A_ 0.2.2 - Fixed issue with Get-Dashboard returning error referencing -JsonIsArray parameter_x000D__x000A_ General - Module is generally functional but has not been extensively bug-tested. Reccomend not implementing into a production environment at this time. + 1.2.0 - Add compatibility with Premium and Pro API endpoints and branding._x000D__x000A_ 1.0.0 - Major refactor, add capabilities and improve testing and build process._x000D__x000A_ 0.3.0 - Remove route translations from URI segments for compatibility with PasswordPusher v1.42.0. See pglombardo/PasswordPusher/pull/2353 True True - 0 - 82 - 14562 - 7/24/2024 1:39:52 AM -04:00 - 7/24/2024 1:39:52 AM -04:00 - 7/24/2024 1:39:52 AM -04:00 - PSEdition_Desktop PSEdition_Core Windows Linux MacOS Password PSModule PSFunction_ConvertTo-PasswordPush PSCommand_ConvertTo-PasswordPush PSFunction_Get-Dashboard PSCommand_Get-Dashboard PSFunction_Get-Push PSCommand_Get-Push PSFunction_Get-PushAuditLog PSCommand_Get-PushAuditLog PSFunction_Get-SecretLink PSCommand_Get-SecretLink PSFunction_Initialize-PassPushPosh PSCommand_Initialize-PassPushPosh PSFunction_New-PasswordPush PSCommand_New-PasswordPush PSFunction_New-Push PSCommand_New-Push PSFunction_Remove-Push PSCommand_Remove-Push PSIncludes_Function + 2 + 221 + 14279 + 2/6/2025 6:21:26 PM -05:00 + 2/6/2025 6:21:26 PM -05:00 + 2/6/2025 6:40:00 PM -05:00 + PSEdition_Core Windows Linux MacOS Password PSModule PSFunction_Get-Dashboard PSCommand_Get-Dashboard PSFunction_Get-Push PSCommand_Get-Push PSFunction_Get-PushAccount PSCommand_Get-PushAccount PSFunction_Get-PushAuditLog PSCommand_Get-PushAuditLog PSFunction_Get-SecretLink PSCommand_Get-SecretLink PSFunction_Initialize-PassPushPosh PSCommand_Initialize-PassPushPosh PSFunction_New-Push PSCommand_New-Push PSFunction_Remove-Push PSCommand_Remove-Push PSIncludes_Function False - 2024-07-24T01:39:52Z - 0.3.0 + 2025-02-06T18:40:00Z + 1.2.0 Adam Burley false Module PassPushPosh.nuspec|PassPushPosh.psd1|PassPushPosh.psm1 5d8a1afd-a912-440f-a9b9-e79f42a05f21 - 5.1 + 7.0 Burley.dev - C:\GitHub\CIPP Workspace\CIPP-API\Modules\PassPushPosh\0.3.0 + C:\GitHub\CIPP Workspace\CIPP-API\Modules\PassPushPosh\1.2.0
diff --git a/Modules/PassPushPosh/0.3.0/PassPushPosh.psd1 b/Modules/PassPushPosh/1.2.1/PassPushPosh.psd1 similarity index 77% rename from Modules/PassPushPosh/0.3.0/PassPushPosh.psd1 rename to Modules/PassPushPosh/1.2.1/PassPushPosh.psd1 index 0245ff599c4e..0e676121021f 100644 --- a/Modules/PassPushPosh/0.3.0/PassPushPosh.psd1 +++ b/Modules/PassPushPosh/1.2.1/PassPushPosh.psd1 @@ -3,7 +3,7 @@ # # Generated by: Adam Burley # -# Generated on: 7/23/2024 +# Generated on: 2/8/2025 # @{ @@ -12,10 +12,10 @@ RootModule = 'PassPushPosh.psm1' # Version number of this module. -ModuleVersion = '0.3.0' +ModuleVersion = '1.2.1' # Supported PSEditions -# CompatiblePSEditions = @() +CompatiblePSEditions = 'Core' # ID used to uniquely identify this module GUID = '5d8a1afd-a912-440f-a9b9-e79f42a05f21' @@ -30,12 +30,10 @@ CompanyName = 'Burley.dev' Copyright = 'Adam Burley, 2022' # Description of the functionality provided by this module -Description = '*PassPushPosh* is a PowerShell Module for interfacing with the Password Pusher secure password / string sharing application, primarily through pwpush.com. It supports creating, retrieving, and deleting anonymous and authenticated pushes and getting Push and Dashboard data for authenticated users. - -Cmdlets provide clear responses to errors, support additional messaging via -Debug and -Verbose, transaction testing via -Whatif and -Confirm, and in general try to be as "Powershell-y" as possible.' +Description = 'PassPushPosh is a PowerShell Module for accessing the Password Pusher application via API. It supports creating, retrieving, and deleting anonymous and authenticated pushes and getting Push and Dashboard data for authenticated users.' # Minimum version of the PowerShell engine required by this module -PowerShellVersion = '5.1' +PowerShellVersion = '7.0' # Name of the PowerShell host required by this module # PowerShellHostName = '' @@ -71,15 +69,13 @@ PowerShellVersion = '5.1' # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'ConvertTo-PasswordPush', 'Get-Dashboard', 'Get-Push', - 'Get-PushAuditLog', 'Get-SecretLink', 'Initialize-PassPushPosh', - 'New-PasswordPush', 'New-Push', 'Remove-Push' +FunctionsToExport = @('Get-Dashboard','Get-Push','Get-PushAccount','Get-PushAuditLog','Get-SecretLink','Initialize-PassPushPosh','New-Push','Remove-Push') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module -VariablesToExport = '*' +# VariablesToExport = @() # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = 'Get-PushPreview' @@ -99,7 +95,7 @@ PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. - Tags = 'PSEdition_Desktop','PSEdition_Core','Windows','Linux','MacOS','Password' + Tags = 'PSEdition_Core','Windows','Linux','MacOS','Password' # A URL to the license for this module. LicenseUri = 'https://www.gnu.org/licenses/gpl-3.0.en.html' @@ -108,14 +104,13 @@ PrivateData = @{ ProjectUri = 'https://github.com/adamburley/PassPushPosh' # A URL to an icon representing this module. - # IconUri = '' + IconUri = 'https://github.com/adamburley/PassPushPosh/blob/main/pwplogo85x85.png?raw=true' # ReleaseNotes of this module ReleaseNotes = ' - 0.3.0 - Remove route translations from URI segments for compatibility with PasswordPusher v1.42.0. See pglombardo/PasswordPusher/pull/2353 - 0.2.3 - Bug fixing in New-Push. See PR #1 - 0.2.2 - Fixed issue with Get-Dashboard returning error referencing -JsonIsArray parameter - General - Module is generally functional but has not been extensively bug-tested. Reccomend not implementing into a production environment at this time.' + 1.2.0 - Add compatibility with Premium and Pro API endpoints and branding. + 1.0.0 - Major refactor, add capabilities and improve testing and build process. + 0.3.0 - Remove route translations from URI segments for compatibility with PasswordPusher v1.42.0. See pglombardo/PasswordPusher/pull/2353' # Prerelease string of this module # Prerelease = '' @@ -137,4 +132,3 @@ HelpInfoURI = 'https://github.com/adamburley/PassPushPosh/blob/main/Docs' # DefaultCommandPrefix = '' } - diff --git a/Modules/PassPushPosh/1.2.1/PassPushPosh.psm1 b/Modules/PassPushPosh/1.2.1/PassPushPosh.psm1 new file mode 100644 index 000000000000..e4d7643eec11 --- /dev/null +++ b/Modules/PassPushPosh/1.2.1/PassPushPosh.psm1 @@ -0,0 +1,986 @@ +#Region '.\Classes\PasswordPush.ps1' -1 + +class PasswordPush { + [string]$Note + [string]$Payload + [string] hidden $__UrlToken + [string] hidden $__LinkBase + [bool]$RetrievalStep + [bool]$IsExpired + [bool]$IsDeleted + [bool]$IsDeletableByViewer + [int]$ExpireAfterDays + [int]$DaysRemaining + [int]$ExpireAfterViews + [int]$ViewsRemaining + [DateTime]$DateCreated + [DateTime]$DateUpdated + [DateTime]$DateExpired + # Added by constructors: + #[string]$URLToken + #[string]$Link + #[string]$LinkDirect + #[string]$LinkRetrievalStep + + PasswordPush() { + # Blank constructor + } + + # Constructor to allow casting or explicit import from a PSObject Representing the result of an API call + PasswordPush([PSCustomObject]$APIresponseObject) { + throw NotImplementedException + } + + # Allow casting or explicit import from the raw Content of an API call + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Scope = 'Function', Justification = 'Global variables are used for module session helpers.')] + PasswordPush([string]$JsonResponse) { + Write-Debug 'New PasswordPush object instantiated from JsonResponse string' + Initialize-PassPushPosh # Initialize the module if not yet done. + + $_j = $JsonResponse | ConvertFrom-Json + $this.Note = $_j.note + $this.Payload = $_j.payload + $this.IsExpired = $_j.expired + $this.IsDeleted = $_j.deleted + $this.IsDeletableByViewer = $_j.deletable_by_viewer + $this.ExpireAfterDays = $_j.expire_after_days + $this.DaysRemaining = $_j.days_remaining + $this.ExpireAfterViews = $_j.expire_after_views + $this.ViewsRemaining = $_j.views_remaining + $this.DateCreated = $_j.created_at + $this.DateUpdated = $_j.updated_at + $this.DateExpired = if ($_j.expired_on) { $_j.expired_on } else { [DateTime]0 } + $this.RetrievalStep = $_j.retrieval_step + + + $this | Add-Member -Name 'UrlToken' -MemberType ScriptProperty -Value { + return $this.__UrlToken + } -SecondValue { + $this.__UrlToken = $_ + $this.__LinkBase = $_j.html_url ?? "$Script:PPPBaseUrl/p/$($this.__UrlToken)" + } + $this.__UrlToken = $_j.url_token + $this.__LinkBase = $_j.html_url ?? "$Script:PPPBaseUrl/p/$($this.__UrlToken)" + $this | Add-Member -Name 'LinkDirect' -MemberType ScriptProperty -Value { return $this.__LinkBase } -SecondValue { + Write-Warning 'LinkDirect is a read-only calculated member.' + Write-Debug 'Link* members are calculated based on the Global BaseUrl and Push Retrieval Step values' + } + $this | Add-Member -Name 'LinkRetrievalStep' -MemberType ScriptProperty -Value { return "$($this.__LinkBase)/r" } -SecondValue { + Write-Warning 'LinkRetrievalStep is a read-only calculated member.' + Write-Debug 'Link* members are calculated based on the Global BaseUrl and Push Retrieval Step values' + } + $this | Add-Member -Name 'Link' -MemberType ScriptProperty -Value { + $_Link = if ($this.RetrievalStep) { $this.LinkRetrievalStep } else { $this.LinkDirect } + Write-Debug "Presented Link: $_link" + $_Link + } -SecondValue { + Write-Warning 'Link is a read-only calculated member.' + Write-Debug 'Link* members are calculated based on the Global BaseUrl and Push Retrieval Step values' + } + } +} +#EndRegion '.\Classes\PasswordPush.ps1' 80 +#Region '.\Classes\TypeAccelerators.ps1' -1 + +# https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_classes?view=powershell-7.4#exporting-classes-with-type-accelerators +# Define the types to export with type accelerators. +$ExportableTypes =@( + [PasswordPush] +) +# Get the internal TypeAccelerators class to use its static methods. +$TypeAcceleratorsClass = [psobject].Assembly.GetType( + 'System.Management.Automation.TypeAccelerators' +) +# Ensure none of the types would clobber an existing type accelerator. +# If a type accelerator with the same name exists, throw an exception. +$ExistingTypeAccelerators = $TypeAcceleratorsClass::Get +foreach ($Type in $ExportableTypes) { + if ($Type.FullName -in $ExistingTypeAccelerators.Keys) { + $Message = @( + "Unable to register type accelerator '$($Type.FullName)'" + 'Accelerator already exists.' + ) -join ' - ' + + throw [System.Management.Automation.ErrorRecord]::new( + [System.InvalidOperationException]::new($Message), + 'TypeAcceleratorAlreadyExists', + [System.Management.Automation.ErrorCategory]::InvalidOperation, + $Type.FullName + ) + } +} +# Add type accelerators for every exportable type. +foreach ($Type in $ExportableTypes) { + $TypeAcceleratorsClass::Add($Type.FullName, $Type) +} +# Remove type accelerators when the module is removed. +($MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = { + foreach($Type in $ExportableTypes) { + $TypeAcceleratorsClass::Remove($Type.FullName) + } +}.GetNewClosure()) | Out-Null +#EndRegion '.\Classes\TypeAccelerators.ps1' 38 +#Region '.\Private\ConvertTo-PasswordPush.ps1' -1 + + <# + .SYNOPSIS + Convert API call response to a PasswordPush object + + .DESCRIPTION + Accepts a JSON string returned from the Password Pusher API and converts it to a [PasswordPush] object. + This allows calculated push retrieval URLs and a more "PowerShell" experience. + Generally you won't need to use this directly, it's automatically invoked within Register-Push and Request-Push. + + .PARAMETER JsonResponse + The string result of an API call from the Password Pusher application + + .INPUTS + [string] + + .OUTPUTS + [PasswordPush] for single object + [PasswordPush[]] for Json array data + + .EXAMPLE + # Common usage - from within the Register-Push cmdlet + PS> $myPush = Register-Push -Payload "This is my secret!" + PS> $myPush.Link # The link parameter always presents the URL as it would appear with the same settings selected on pwpush.com + + https://pwpush.com/p/rz6nryvl-d4 + + .EXAMPLE + # Manually invoking the API + PS> $rawJson = Invoke-WebRequest ` + -Uri https://pwpush.com/p.json ` + -Method Post ` + -Body '{"password": { "payload": "This is my secret!"}}' ` + -ContentType 'application/json' | + Select-Object -ExpandProperty Content + PS> $rawJson + {"expire_after_days":7,"expire_after_views":5,"expired":false,"url_token":"rz6nryvl-d4","created_at":"2022-11-18T14:16:29.821Z","updated_at":"2022-11-18T14:16:29.821Z","deleted":false,"deletable_by_viewer":true,"retrieval_step":false,"expired_on":null,"days_remaining":7,"views_remaining":5} + PS> $rawJson | ConvertTo-PasswordPush + UrlToken : rz6nryvl-d4 + LinkDirect : https://pwpush.com/p/rz6nryvl-d4 + LinkRetrievalStep : https://pwpush.com/p/rz6nryvl-d4/r + Link : https://pwpush.com/p/rz6nryvl-d4 + Payload : + RetrievalStep : False + IsExpired : False + IsDeleted : False + IsDeletableByViewer : True + ExpireAfterDays : 7 + DaysRemaining : 7 + ExpireAfterViews : 5 + ViewsRemaining : 5 + DateCreated : 11/18/2022 2:16:29 PM + DateUpdated : 11/18/2022 2:16:29 PM + DateExpired : 1/1/0001 12:00:00 AM + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/ConvertTo-PasswordPush.md + + .NOTES + Needs a rewrite / cleanup + #> +function ConvertTo-PasswordPush { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope = 'Function', Justification = 'Creates a new object, no risk of overwriting data.')] + [CmdletBinding()] + [OutputType([PasswordPush])] + param( + [parameter(Mandatory, ValueFromPipeline)] + [ValidateNotNullOrEmpty()] + $JsonResponse + ) + process { + try { + $jsonObject = if ($JsonResponse -is [string]) { $JsonResponse | ConvertFrom-Json } else { $JsonResponse } + foreach ($o in $jsonObject) { + [PasswordPush]($o | ConvertTo-Json) # TODO fix this mess + } + } + catch { + Write-Debug 'Error in ConvertTo-PasswordPush coercing JSON object to PasswordPush object' + Write-Debug "JsonResponse parameter value: [[$JsonResponse]]" + Write-Error $_ + } + } +} +#EndRegion '.\Private\ConvertTo-PasswordPush.ps1' 84 +#Region '.\Private\Format-PasswordPusherSecret.ps1' -1 + +function Format-PasswordPusherSecret { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$Secret, + + [Parameter()] + [switch]$ShowSample + ) + process { + if ($Secret -eq '') { + "length 0" + continue + } + $length = $Secret.Length + $last4 = $Secret.Substring($length - 4) + if ($ShowSample) { + "length $length ending [$last4]" + } + else { + "length $length" + } + } +} +#EndRegion '.\Private\Format-PasswordPusherSecret.ps1' 27 +#Region '.\Private\Invoke-PasswordPusherAPI.ps1' -1 + +function Invoke-PasswordPusherAPI { + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [string]$Endpoint, + [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get, + [object]$Body, + + [Switch]$ReturnErrors + ) + process { + $_uri = "$Script:PPPBaseURL/$Endpoint" + Write-Debug "Invoke-PasswordPusherAPI: $Method $_uri" + + $iwrSplat = @{ + 'Method' = $Method + 'ContentType' = 'application/json' + 'Body' = ($body | ConvertTo-Json) + 'Uri' = $_uri + 'UserAgent' = $Script:PPPUserAgent + } + if ($Script:PPPHeaders.'X-User-Token') { + $iwrSplat['Headers'] = $Script:PPPHeaders + Write-Debug "Authenticated with API token $(Format-PasswordPusherSecret -Secret $Script:PPPHeaders.'X-User-Token' -ShowSample)" + } + if ($Script:PPPHeaders.'Authorization') { + $iwrSplat['Headers'] = $Script:PPPHeaders + Write-Debug "Authenticated with API token $(Format-PasswordPusherSecret -Secret $Script:PPPHeaders.'Authorization' -ShowSample)" + } + $callInfo = "$Method $_uri" + Write-Verbose "Sending HTTP request: $callInfo" + + $call = Invoke-WebRequest @iwrSplat -SkipHttpErrorCheck + Write-Debug "Response: $($call.StatusCode) $($call.Content)" + if (Test-Json -Json $call.Content) { + $result = $call.Content | ConvertFrom-Json + if ($ReturnErrors -or $call.StatusCode -eq 200 -or $null -eq $result.error) { + $result + } else { + Write-Error -Message "$callInfo : $($call.StatusCode) $($result.error)" + } + } else { + Write-Error -Message "Parseable JSON not returned by API. $callInfo : $($call.StatusCode) $($call.Content)" + } + } +} +#EndRegion '.\Private\Invoke-PasswordPusherAPI.ps1' 47 +#Region '.\Public\Get-Dashboard.ps1' -1 + +<# + .SYNOPSIS + Get a list of active or expired Pushes for an authenticated user + + .DESCRIPTION + Retrieves a list of Pushes - active or expired - for an authenticated user. + Active and Expired are different endpoints, so to get both you'll need to make + two calls. + + .PARAMETER Dashboard + The type of dashboard to retrieve. Active or Expired. + + .INPUTS + [string] 'Active' or 'Expired' + + .OUTPUTS + [PasswordPush[]] Array of pushes with data + + .EXAMPLE + Get-Dashboard + + .EXAMPLE + Get-Dashboard Active + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-Dashboard.md + + .LINK + https://pwpush.com/api/1.0/passwords/active.en.html + + .LINK + Get-PushAuditLog + + #> +function Get-Dashboard { + [CmdletBinding()] + [OutputType([PasswordPush[]])] + param( + [parameter(Position = 0)] + [ValidateSet('Active', 'Expired')] + [ValidateNotNullOrEmpty()] + [string] + $Dashboard = 'Active' + ) + process { + if (-not $Script:PPPHeaders) { Write-Error 'Dashboard access requires authentication. Run Initialize-PassPushPosh and pass your email address and API key before retrying.' -ErrorAction Stop -Category AuthenticationError } + $uri = "p/$($Dashboard -eq 'Active' ? 'active.json' : 'expired.json')" + Invoke-PasswordPusherAPI -Endpoint $uri -Method Get | ConvertTo-PasswordPush + } +} +#EndRegion '.\Public\Get-Dashboard.ps1' 51 +#Region '.\Public\Get-Push.ps1' -1 + +<# + .SYNOPSIS + Retrieve the secret contents of a Push + + .DESCRIPTION + Get-Push accepts a URL Token string and returns the contents of a Push along with + metadata regarding that Push. Note: Get-Push will return data on an expired + Push (datestamps, etc) even if it does not return the Push contents. + + .PARAMETER URLToken + URL Token for the secret + + .PARAMETER Passhrase + An additional phrase required to view the secret. Required if the Push was created with a Passphrase. + + .INPUTS + [string] + + .OUTPUTS + [PasswordPush] + + .EXAMPLE + Get-Push -URLToken gzv65wiiuciy + + .EXAMPLE + Get-Push -URLToken gzv65wiiuciy -Passphrase "My Passphrase" + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-Push.md + + .LINK + https://pwpush.com/api/1.0/passwords.en.html + + .LINK + https://github.com/pglombardo/PasswordPusher/blob/c2909b2d5f1315f9b66939c9fbc7fd47b0cfeb03/app/controllers/passwords_controller.rb#L89 + + .LINK + New-Push + + #> +function Get-Push { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Passphrase", Justification = "DE0001: SecureString shouldn't be used")] + [CmdletBinding()] + [OutputType([PasswordPush])] + param( + [Parameter(Mandatory, ValueFromPipeline)] + [ValidateNotNullOrEmpty()] + [Alias('Token')] + $URLToken, + + [Parameter()] + [String]$Passphrase + ) + begin { Initialize-PassPushPosh -Verbose:$VerbosePreference -Debug:$DebugPreference } + process { + $endpoint = $Passphrase ? "p/$URLToken.json?passphrase=$Passphrase" : "p/$URLToken.json" + $result = Invoke-PasswordPusherAPI -Endpoint $endpoint -ReturnErrors + switch ($result.error){ + 'not-found' { Write-Error -Message "Push not found. Check the token you provided. Tokens are case-sensitive." } + 'This push has a passphrase that was incorrect or not provided.' { if ($Passphrase) { Write-Error -Message "Incorrect passphrase provided." } else { Write-Error -Message "Passphrase required. Specify with the -Passphrase parameter." } } + default { $result | ConvertTo-PasswordPush } + } + } +} +#EndRegion '.\Public\Get-Push.ps1' 65 +#Region '.\Public\Get-PushAccount.ps1' -1 + +<# + .SYNOPSIS + Get a list of accounts for an authenticated user + + .DESCRIPTION + Retrieves a list of accounts for an authenticated user. + + .LINK + Get-PushAuditLog + + #> +function Get-PushAccount { + [CmdletBinding()] + [OutputType([PasswordPush[]])] + param() + process { + if (-not $Script:PPPHeaders) { Write-Error 'Dashboard access requires authentication. Run Initialize-PassPushPosh and pass your email address and API key before retrying.' -ErrorAction Stop -Category AuthenticationError } + $uri = 'api/v1/accounts' + Invoke-PasswordPusherAPI -Endpoint $uri -Method Get + } +} +#EndRegion '.\Public\Get-PushAccount.ps1' 22 +#Region '.\Public\Get-PushAuditLog.ps1' -1 + +<# + .SYNOPSIS + Get the view log of an authenticated Push + + .DESCRIPTION + Retrieves the view log of a Push created under an authenticated session. + Returns an array of custom objects with view data. If the query is + successful but there are no results, it returns an empty array. + If there's an error, a single object is returned with information. + See "handling errors" under NOTES + + .PARAMETER URLToken + URL Token from a secret + + .INPUTS + [string] + + .OUTPUTS + [PsCustomObject[]] Array of entries. + [PsCustomObject] If there's an error in the call, it will be returned an object with a property + named 'error'. The value of that member will contain more information + + .EXAMPLE + Get-PushAuditLog -URLToken 'mytokenfromapush' + ip : 75.202.43.56,102.70.135.200 + user_agent : Mozilla/5.0 (Macintosh; Darwin 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:20:05 PDT 2022; root:xnu-8020.140.49~2/RELEASE_ARM64_T8101; + en-US) PowerShell/7.2.7 + referrer : + successful : True + created_at : 11/19/2022 6:32:42 PM + updated_at : 11/19/2022 6:32:42 PM + kind : 0 + + .EXAMPLE + # If there are no views, an empty array is returned + Get-PushAuditLog -URLToken 'mytokenthatsneverbeenseen' + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-PushAuditLog.md + + .LINK + https://pwpush.com/api/1.0/passwords/audit.en.html + + .LINK + Get-Dashboard + + .NOTES + Handling Errors: + The API returns different HTTP status codes and results depending where the + call fails. + + | HTTP RESPONSE | Error Reason | Response Body | Sample Object Returned | Note | + |------------------|---------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------| + | 401 UNAUTHORIZED | Invalid API key or email | None | @{ 'Error'= 'Authentication error. Verify email address and API key.'; 'ErrorCode'= 401 } | | + | 200 OK | Push created by another account | {"error":"That push doesn't belong to you."} | @{ 'Error'= "That Push doesn't belong to you"; 'ErrorCode'= 403 } | Function transforms error code to 403 to allow easier response management | + | 404 NOT FOUND | Invalid URL token | None | @{ 'Error'= 'Invalid token. Verify your Push URL token is correct.'; 'ErrorCode'= 404 } | This is different than the response to a delete Push query - in this case it will only return 404 if the token is invalid. | + + #> +function Get-PushAuditLog { + [CmdletBinding()] + [OutputType([PSCustomObject[]])] + param( + [parameter(Mandatory, ValueFromPipeline)] + [Alias('Token')] + [string] + $URLToken + ) + begin { + if (-not $Script:PPPHeaders) { Write-Error 'Retrieving audit logs requires authentication. Run Initialize-PassPushPosh and pass your email address and API key before retrying.' -ErrorAction Stop -Category AuthenticationError } + } + process { + $response = Invoke-PasswordPusherAPI -Endpoint "p/$URLToken/audit.json" -ReturnErrors + switch ($response.error) { + 'not-found' { Write-Error -Message "Push not found. Check the token you provided. Tokens are case-sensitive." } + { $null -ne $_ -and $_ -ne 'not-found' } { Write-Error -Message $_ } + default { $response | Select-Object -ExpandProperty views } + } + } +} +#EndRegion '.\Public\Get-PushAuditLog.ps1' 80 +#Region '.\Public\Get-SecretLink.ps1' -1 + +<# + .SYNOPSIS + Returns a fully qualified secret link to a push of given URL Token + + .DESCRIPTION + Accepts a string value for a URL Token and retrieves a full URL link to the secret. + Returned value is a 1-step retrieval link depending on option selected during Push creation. + Returns false if URL Token is invalid, however it will return a URL if the token is valid + but the Push is expired or deleted. + + .PARAMETER URLToken + URL Token for the secret + + .INPUTS + [string] URL Token value + + .OUTPUTS + [string] Fully qualified URL + + .EXAMPLE + Get-SecretLink -URLToken gzv65wiiuciy + https://pwpush.com/p/gzv65wiiuciy/r + + .EXAMPLE + Get-SecretLink -URLToken gzv65wiiuciy -Raw + { "url": "https://pwpush.com/p/0fkapnbo_pwp4gi8uy0/r" } + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/Get-SecretLink.md + + .LINK + https://pwpush.com/api/1.0/passwords/preview.en.html + + .NOTES + Including this endpoint for completeness - however it is generally unnecessary. + The only thing this endpoint does is return a different value depending if "Use 1-click retrieval step" + was selected when the Push was created. Since both the 1-click and the direct links are available + regardless if that option is selected, the links are calculable and both are included by default in a + [PasswordPush] object. + + As it returns false if a Push URL token is not valid you can use it to test if a Push exists without + burning a view. + #> +function Get-SecretLink { + [CmdletBinding()] + [Alias('Get-PushPreview')] + [OutputType('[string]')] + param( + [parameter(Mandatory, ValueFromPipeline)] + [Alias('Token')] + [ValidateLength(5, 256)] + [string]$URLToken + ) + begin { Initialize-PassPushPosh -Verbose:$VerbosePreference -Debug:$DebugPreference } + process { + Invoke-PasswordPusherAPI -Endpoint "p/$URLToken/preview.json" | Select-Object -ExpandProperty url + } +} +#EndRegion '.\Public\Get-SecretLink.ps1' 59 +#Region '.\Public\Initialize-PassPushPosh.ps1' -1 + +<# + .SYNOPSIS + Initialize the PassPushPosh module + + .DESCRIPTION + Initialize-PassPushPosh sets variables for the module's use during the remainder of the session. + Server URL and User Agent values are set by default but may be overridden. + If invoked with email address and API key, calls are sent as authenticated. Otherwise they default to + anonymous. + + This function is called automatically if needed, defaulting to the public pwpush.com service. + + .PARAMETER AccountType + For paid users, specify the account type as Premium or Pro. Not required for free accounts and self-hosted. + + .PARAMETER EmailAddress + Email address for authenticated calls. + + .PARAMETER ApiKey + API key for authenticated calls. + + .PARAMETER BaseUrl + Base URL for API calls. Allows use of module with private instances of Password Pusher + Default: https://pwpush.com + + .PARAMETER UserAgent + Set a specific user agent. Default user agent is a combination of the + module info, what your OS reports itself as, and a hash based on + your username + workstation or domain name. This way the UA can be + semi-consistent across sessions but not identifying. + + Note: User agent must meet [RFC9110](https://www.rfc-editor.org/rfc/rfc9110#name-user-agent) specifications or the Password Pusher API will reject the call. + + .PARAMETER Force + Force setting new information. If module is already initialized you can use this to + Re-initialize with default settings. Implied if either ApiKey or BaseUrl is provided. + + .EXAMPLE + # Initialize with default settings + PS > Initialize-PassPushPosh + + .EXAMPLE + # Initialize with authentication + PS > Initialize-PassPushPosh -EmailAddress 'youremail@example.com' -ApiKey '239jf0jsdflskdjf' -Verbose + + VERBOSE: Initializing PassPushPosh. ApiKey: [x-kdjf], BaseUrl: https://pwpush.com + + .EXAMPLE + # Initialize with another server with authentication + PS > Initialize-PassPushPosh -BaseUrl https://myprivatepwpushinstance.com -EmailAddress 'youremail@example.com' -ApiKey '239jf0jsdflskdjf' -Verbose + + VERBOSE: Initializing PassPushPosh. ApiKey: [x-kdjf], BaseUrl: https://myprivatepwpushinstance.com + + .EXAMPLE + # Set a custom User Agent + PS > InitializePassPushPosh -UserAgent "My-CoolUserAgent/1.12.1" + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/Initialize-PassPushPosh.md + + .NOTES + -WhatIf setting for Set-Variable -Script is disabled, otherwise -WhatIf + calls for other functions would return incorrect data in the case this + function has not yet run. + #> +function Initialize-PassPushPosh { + [CmdletBinding(DefaultParameterSetName = 'Anonymous')] + param ( + [Parameter(ParameterSetName = 'Pro')] + [ValidateSet('Premium', 'Pro')] + [string]$AccountType = 'Pro', + + [Parameter(Mandatory, Position = 0, ParameterSetName = 'Authenticated')] + [ValidatePattern('.+\@.+\..+', ErrorMessage = 'Please specify a valid email address')] + [string]$EmailAddress, + + [Parameter(Mandatory, ParameterSetName = 'Pro')] + [Parameter(Mandatory, Position = 1, ParameterSetName = 'Authenticated')] + [ValidateLength(5, 256)] + [string]$ApiKey, + + [Parameter(Position = 0, ParameterSetName = 'Anonymous')] + [Parameter(Position = 2, ParameterSetName = 'Authenticated')] + [Parameter(ParameterSetName = 'Pro')] + [ValidatePattern('^https?:\/\/[a-zA-Z0-9-_]+.[a-zA-Z0-9]+')] + [string]$BaseUrl, + + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] + $UserAgent, + + [Parameter()][switch]$Force + ) + if ($Script:PPPBaseURL -and $true -inotin $Force, [bool]$ApiKey, [bool]$BaseUrl, [bool]$UserAgent) { Write-Debug -Message 'PassPushPosh is already initialized.' } + else { + $defaultBaseUrl = 'https://pwpush.com' + $apiKeyOutput = $ApiKey ? (Format-PasswordPusherSecret -Secret $ApiKey -ShowSample) : 'None' + + if (-not $Script:PPPBaseURL) { + # Not initialized + if (-not $BaseUrl) { $BaseUrl = $defaultBaseUrl } + Write-Verbose "Initializing PassPushPosh. ApiKey: [$apiKeyOutput], BaseUrl: $BaseUrl" + } + elseif ($Force -or $ApiKey -or $BaseURL) { + if (-not $BaseUrl) { $BaseUrl = $defaultBaseUrl } + $oldApiKeyOutput = if ($Script:PPPApiKey) { Format-PasswordPusherSecret -Secret $Script:PPPApiKey -ShowSample } else { 'None' } + Write-Verbose "Re-initializing PassPushPosh. Old ApiKey: [$oldApiKeyOutput] New ApiKey: [$apiKeyOutput], Old BaseUrl: $Script:PPPBaseUrl New BaseUrl: $BaseUrl" + } + if ($PSCmdlet.ParameterSetName -eq 'Authenticated') { + + Set-Variable -Scope Script -Name PPPHeaders -WhatIf:$false -Value @{ + 'X-User-Email' = $EmailAddress + 'X-User-Token' = $ApiKey + } + } + elseif ($PSCmdlet.ParameterSetName -eq 'Pro') { + Write-Debug "Initializing for paid tier $($AccountType)" + Set-Variable -Scope Script -Name PPPHeaders -WhatIf:$false -Value @{ + 'Authorization' = "Bearer $ApiKey" + } + } + elseif ($Script:PPPHeaders) { + # Remove if present - covers case where module is reinitialized from an authenticated to an anonymous session + Remove-Variable -Scope Script -Name PPPHeaders -WhatIf:$false + } + + if (-not $UserAgent) { + $osVersion = [System.Environment]::OSVersion + $userAtDomain = '{0}@{1}' -f [System.Environment]::UserName, [System.Environment]::UserDomainName + $uAD64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($userAtDomain)) + Write-Debug "$userAtDomain transformed to $uAD64. First 20 characters $($uAD64.Substring(0,20))" + # Version tag is replaced by the semantic version number at build time. See PassPushPosh/issues/11 for context + $UserAgent = "PassPushPosh/1.2.1 $osVersion/$($uAD64.Substring(0,20))" + # $UserAgent = "PassPushPosh/$((Get-Module -Name PassPushPosh).Version.ToString()) $osVersion/$($uAD64.Substring(0,20))" + Write-Verbose "Generated user agent: $UserAgent" + } + else { + Write-Verbose "Using specified user agent: $UserAgent" + } + + Set-Variable -WhatIf:$false -Scope Script -Name PPPBaseURL -Value $BaseUrl.TrimEnd('/') + Set-Variable -WhatIf:$false -Scope Script -Name PPPUserAgent -Value $UserAgent + } +} +#EndRegion '.\Public\Initialize-PassPushPosh.ps1' 146 +#Region '.\Public\New-Push.ps1' -1 + +<# + .SYNOPSIS + Create a new Push + + .DESCRIPTION + Create a new Push on the specified Password Pusher instance. The + programmatic equivalent of going to pwpush.com and entering info. + Returns [PasswordPush] object. Link member is a link created based on + 1-step setting however both 1-step and direct links + are always provided at LinkRetrievalStep and LinkDirect properties. + + .PARAMETER Payload + The URL password or secret text to share. + + .PARAMETER Passphrase + Require recipients to enter this passphrase to view the created push. + + .PARAMETER Note + The note for this push. Visible only to the push creator. Requires authentication. + + .PARAMETER ExpireAfterDays + Expire secret link and delete after this many days. + + .PARAMETER ExpireAfterViews + Expire secret link and delete after this many views. + + .PARAMETER DeletableByViewer + Allow the recipient of a Push to delete it. + + .PARAMETER RetrievalStep + Require recipient click an extra link to view Push payload. + Helps to avoid chat systems and URL scanners from eating up views. + Note that the retrieval step URL is always available for a push. This + parameter changes if the 1-click link is used in the Link parameter + and returned from the secret link helper (Get-SecretLink) + + .PARAMETER AccountId + Account ID to associate with this push. Requires authentication. + + .INPUTS + [string] + + .OUTPUTS + [PasswordPush] Representation of the submitted push + + .EXAMPLE + $myPush = New-Push "Here's my secret!" + PS > $myPush | Select-Object Link, LinkRetrievalStep, LinkDirect + + Link : https://pwpush.com/p/gzv65wiiuciy # Requested style + LinkRetrievalStep : https://pwpush.com/p/gzv65wiiuciy/r # 1-step + LinkDirect : https://pwpush.com/p/gzv65wiiuciy # Direct + + .EXAMPLE + "Super secret secret" | New-Push -RetrievalStep | Select-Object -ExpandProperty Link + + https://pwpush.com/p/gzv65wiiuciy/r + + + .EXAMPLE + # "Burn after reading" style Push + PS > New-Push -Payload "Still secret text!" -ExpireAfterViews 1 -RetrievalStep + + .LINK + https://github.com/adamburley/PassPushPosh/blob/main/Docs/New-Push.md + + .LINK + https://pwpush.com/api/1.0/passwords/create.en.html + + .LINK + https://github.com/pglombardo/PasswordPusher/blob/c2909b2d5f1315f9b66939c9fbc7fd47b0cfeb03/app/controllers/passwords_controller.rb#L120 + + .LINK + Get-Push + + .NOTES + Maximum for -ExpireAfterDays and -ExpireAfterViews is based on the default + values for Password Pusher and what's used on the public instance + (pwpush.com). If you're using this with a private instance and want to + override that value you'll need to fork this module. + #> +function New-Push { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', 'Passphrase', Justification = "DE0001: SecureString shouldn't be used")] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low', DefaultParameterSetName = 'Anonymous')] + [OutputType([PasswordPush])] + param( + [Parameter(Mandatory = $true, ValueFromPipeline, Position = 0)] + [Alias('Password')] + [ValidateNotNullOrEmpty()] + [string]$Payload, + + [Parameter()] + [string]$Passphrase, + + [Parameter(ParameterSetName = 'Authenticated')] + [ValidateScript({ $null -ne $Script:PPPHeaders.'X-User-Token' -or $null -ne $Script:PPPHeaders.Authorization }, ErrorMessage = 'Adding a note requires authentication.')] + [ValidateNotNullOrEmpty()] + [string]$Note, + + [Parameter()] + [ValidateRange(1, 90)] + [int] + $ExpireAfterDays, + + [Parameter()] + [ValidateRange(1, 100)] + [int] + $ExpireAfterViews, + + [Parameter()] + [switch] + $DeletableByViewer, + + [Parameter()] + [switch] + $RetrievalStep, + + [Parameter()] + [ValidateScript({ $null -ne $Script:PPPHeaders.Authorization }, ErrorMessage = 'Adding an account id requires authentication.')] + $AccountId + ) + + begin { + Initialize-PassPushPosh -Verbose:$VerbosePreference -Debug:$DebugPreference + } + process { + $body = @{ + 'password' = @{ + 'payload' = $Payload + } + } + $shouldString = 'Submit {0} push with Payload of length {1}' -f $PSCmdlet.ParameterSetName, $Payload.Length + if ($Passphrase) { + $body.password.passphrase = $Passphrase + $shouldString += ", with passphrase of length $($Passphrase.Length)" + } + if ($Note) { + $body.password.note = $note + $shouldString += ", with note $note" + } + if ($ExpireAfterDays) { + $body.password.expire_after_days = $ExpireAfterDays + $shouldString += ', expire after {0} days' -f $ExpireAfterDays + } + if ($ExpireAfterViews) { + $body.password.expire_after_views = $ExpireAfterViews + $shouldString += ', expire after {0} views' -f $ExpireAfterViews + } + if ($AccountId) { + $body.account_id = $AccountId + $shouldString += ', with account ID {0}' -f $AccountId + } + $body.password.deletable_by_viewer = if ($DeletableByViewer) { + $shouldString += ', deletable by viewer' + $true + } else { + $shouldString += ', NOT deletable by viewer' + $false + } + $body.password.retrieval_step = if ($RetrievalStep) { + $shouldString += ', with a 1-click retrieval step' + $true + } else { + $shouldString += ', with a direct link' + $false + } + if ($PSCmdlet.ShouldProcess($shouldString, $iwrSplat.Uri, 'Submit new Push')) { + $response = Invoke-PasswordPusherAPI -Endpoint 'p.json' -Method Post -Body $body + $response | ConvertTo-PasswordPush + } + } +} +#EndRegion '.\Public\New-Push.ps1' 173 +#Region '.\Public\Remove-Push.ps1' -1 + +<# +.SYNOPSIS +Remove a Push + +.DESCRIPTION +Remove (invalidate) an active push. Requires the Push be either set as +deletable by viewer, or that you are authenticated as the creator of the +Push. + +If you have authorization to delete a push (deletable by viewer TRUE or +you are the Push owner) the endpoint will always return 200 OK with a Push +object, regardless if the Push was previously deleted or expired. + +If the Push URL Token is invalid OR you are not authorized to delete the +Push, the endpoint returns 404 and this function returns $false + +.PARAMETER URLToken +URL Token for the secret + +.PARAMETER PushObject +PasswordPush object + +.INPUTS +[string] URL Token +[PasswordPush] representing the Push to remove + +.OUTPUTS +[bool] True on success, otherwise False + +.EXAMPLE +Remove-Push -URLToken bwzehzem_xu- + +.EXAMPLE +Remove-Push -URLToken + +.LINK +https://github.com/adamburley/PassPushPosh/blob/main/Docs/Remove-Push.md + +.LINK +https://pwpush.com/api/1.0/passwords/destroy.en.html + +.NOTES +TODO testing and debugging +#> +function Remove-Push { + [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Token')] + [OutputType([PasswordPush], [bool])] + param( + [parameter(ValueFromPipeline, ParameterSetName = 'Token')] + [ValidateNotNullOrEmpty()] + [Alias('Token')] + [string] + $URLToken, + + [Parameter(ValueFromPipeline, ParameterSetName = 'Object')] + [PasswordPush] + $PushObject + ) + process { + if ($PSCmdlet.ParameterSetName -eq 'Object') { + Write-Debug -Message "Remove-Push was passed a PasswordPush object with URLToken: [$($PushObject.URLToken)]" + if (-not $PushObject.IsDeletableByViewer -and -not $Script:PPPHeaders) { + #Pre-qualify if this will succeed + Write-Warning -Message 'Unable to remove Push. Push is not marked as deletable by viewer and you are not authenticated.' + continue + } + if ($PushObject.IsDeletableByViewer) { + Write-Verbose "Push is flagged as deletable by viewer, should be deletable." + } + else { Write-Verbose "In an authenticated API session. Push will be deletable if it was created by authenticated user." } + $URLToken = $PushObject.URLToken + } + else { + Write-Debug -Message "Remove-Push was passed a URLToken: [$URLToken]" + } + Write-Verbose -Message "Push with URL Token [$URLToken] will be deleted if 'Deletable by viewer' was enabled or you are the creator of the push and are authenticated." + if ($PSCmdlet.ShouldProcess('Delete', "Push with token [$URLToken]")) { + $result = Invoke-PasswordPusherAPI -Endpoint "p/$URLToken.json" -Method 'Delete' -ReturnErrors + if ($result.error) { + Write-Error -Message "Unable to remove Push with token [$URLToken]. Error: $($result.error)" + } + else { + $result | ConvertTo-PasswordPush + } + } + } +} +#EndRegion '.\Public\Remove-Push.ps1' 88 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000000..6da14aa0a7c9 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,58 @@ +services: + azurite: + image: mcr.microsoft.com/azure-storage/azurite + container_name: azurite + ports: + - "10000:10000" + - "10001:10001" + - "10002:10002" + networks: + - func-network + environment: + - AZURITE_ACCOUNTS=devstoreaccount1:Eby8vdM02xNoBnZf6KgBVU4= + + cippapi: + build: + context: . + dockerfile: Dockerfile + environment: + - FUNCTIONS_WORKER_RUNTIME=${FUNCTIONS_WORKER_RUNTIME} + - FUNCTIONS_WORKER_RUNTIME_VERSION=${FUNCTIONS_WORKER_RUNTIME_VERSION} + - AzureWebJobsStorage=${AzureWebJobsStorage} + - ApplicationID=${ApplicationID} + - ApplicationSecret=${ApplicationSecret} + - RefreshToken=${RefreshToken} + - TenantID=${TenantID} + - DEV_SKIP_BPA_TIMER=${DEV_SKIP_BPA_TIMER} + - DEV_SKIP_DOMAIN_TIMER=${DEV_SKIP_DOMAIN_TIMER} + - SetFromProfile=${SetFromProfile} + - FUNCTIONS_EXTENSION_VERSION=${FUNCTIONS_EXTENSION_VERSION} + - AzureWebJobs.BestPracticeAnalyser_OrchestrationStarterTimer.Disabled=true + - AzureWebJobs.Domain_OrchestrationStarterTimer.Disabled=true + - WEBSITE_HOSTNAME=cippapi + depends_on: + - azurite + networks: + - func-network + deploy: + replicas: 3 + + nginx: + image: nginx:alpine + container_name: nginx + ports: + - "7071:80" + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + - cippapi + networks: + - func-network + healthcheck: + test: ["CMD", "curl", "-f", "http://cippapi:7071"] + interval: 30s + retries: 5 + +networks: + func-network: + driver: bridge diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 000000000000..30a773880a02 --- /dev/null +++ b/nginx.conf @@ -0,0 +1,20 @@ +events {} + +http { + upstream functionapp_backend { + server cippapi:80; + } + + server { + listen 80; + + location / { + proxy_pass http://functionapp_backend; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection keep-alive; + proxy_set_header Host $host; + proxy_cache_bypass $http_upgrade; + } + } +} diff --git a/version_latest.txt b/version_latest.txt index 1996c504476f..b26a34e47056 100644 --- a/version_latest.txt +++ b/version_latest.txt @@ -1 +1 @@ -7.1.3 +7.2.1