Functions/Security/Grant-RsCatalogItemRole.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# Copyright (c) 2016 Microsoft Corporation. All Rights Reserved.
# Licensed under the MIT License (MIT)


function Grant-RsCatalogItemRole
{
    <#
        .SYNOPSIS
            This script grants access to catalog items to users/groups.

        .DESCRIPTION
            This script grants the specified role access to the specified user/group on the specified catalog item using either current user's credentials or specified credentials.

        .PARAMETER Identity
            Specify the user or group name to grant access to.

        .PARAMETER RoleName
            Specify the name of the role you want to grant on the catalog item.

        .PARAMETER Path
            Specify the path to catalog item on the server.

        .PARAMETER Strict
            Setting this parameter causes the function to replace all soft terminations with exceptions.
            When trying to grant permissions already assigned, this will cause a terminating error.

        .PARAMETER ReportServerUri
            Specify the Report Server URL to your SQL Server Reporting Services Instance.
            Use the "Connect-RsReportServer" function to set/update a default value.

        .PARAMETER Credential
            Specify the credentials to use when connecting to the Report Server.
            Use the "Connect-RsReportServer" function to set/update a default value.

        .PARAMETER Proxy
            Report server proxy to use.
            Use "New-RsWebServiceProxy" to generate a proxy object for reuse.
            Useful when repeatedly having to connect to multiple different Report Server.

        .EXAMPLE
            Grant-RsCatalogItemRole -Identity 'johnd' -RoleName 'Browser' -Path '/My Folder/SalesReport'
            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/reportserver using current user's credentials and then grant Browser access to user 'johnd' on catalog item found at '/My Folder/SalesReport'.

        .EXAMPLE
            Grant-RsCatalogItemRole -ReportServerUri 'http://localhost/reportserver_sql2012' -Identity 'johnd' -RoleName 'Browser' -Path '/My Folder/SalesReport'
            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/reportserver_2012 using current user's credentials and then grant Browser access to user 'johnd' on catalog item found at '/My Folder/SalesReport'.

        .EXAMPLE
            Grant-RsCatalogItemRole -Credential 'CaptainAwesome' -Identity 'johnd' -RoleName 'Browser' -Path '/My Folder/SalesReport'
            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/reportserver using CaptainAwesome's credentials and then grant Browser access to user 'johnd' on catalog item found at '/My Folder/SalesReport'.
    #>


    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param
    (
        [Alias('UserOrGroupName')]
        [Parameter(Mandatory = $True)]
        [string]
        $Identity,

        [Parameter(Mandatory = $True)]
        [string]
        $RoleName,

        [Alias('ItemPath')]
        [Parameter(Mandatory = $True)]
        [string]
        $Path,

        [switch]
        $Strict,

        [string]
        $ReportServerUri,

        [Alias('ReportServerCredentials')]
        [System.Management.Automation.PSCredential]
        $Credential,

        $Proxy
    )

    if ($PSCmdlet.ShouldProcess((Get-ShouldProcessTargetweb -BoundParameters $PSBoundParameters), "Grant $RoleName on $Path to $Identity"))
    {
        $Proxy = New-RsWebServiceProxyHelper -BoundParameters $PSBoundParameters

        #region Retrieving and checking roles and policies
        # retrieving roles from the proxy
        Write-Verbose "Retrieving valid roles for Catalog items..."
        try
        {
            $roles = $proxy.ListRoles("Catalog", $null)
        }
        catch
        {
            throw (New-Object System.Exception("Error retrieving roles for catalog items! $($_.Exception.Message)", $_.Exception))
        }

        # validating the role name provided by user
        if ($roles.Name -notcontains $RoleName)
        {
            throw "Role name is not valid. Valid options are: $($roles.Name -join ", ")"
        }

        # retrieving existing policies for the current item
        try
        {
            Write-Verbose "Retrieving policies for $Path..."
            $inheritsParentPolicy = $false
            $policies = $proxy.GetPolicies($Path, [ref]$inheritsParentPolicy)
        }
        catch
        {
            throw (New-Object System.Exception("Error retrieving existing policies for $Path! $($_.Exception.Message)", $_.Exception))
        }
        Write-Verbose "Policies retrieved: $($Policies.Length)!"

        # checking if the specified role already exists on the specified user/group name for specified catalog item
        if (($policies | Where-Object { $_.GroupUserName -eq $Identity }).Roles.Name -contains $RoleName)
        {
            if ($Strict)
            {
                throw "$($Identity) already has $($RoleName) privileges on $Path"
            }
            else
            {
                Write-Warning "$($Identity) already has $($RoleName) privileges on $Path"
                return
            }
        }
        #endregion Retrieving and checking roles and policies

        #region Assign Permissions
        # determining namespace of the proxy and the names of needed data types
        $namespace = $proxy.GetType().Namespace
        $policyDataType = $namespace + '.Policy'
        $roleDataType = $namespace + '.Role'

        #Return all policies that contain the user/group we want to add
        $policy = $policies | Where-Object { $_.GroupUserName -eq $Identity } | Select-Object -First 1

        # creating new policy
        if (-not $policy)
        {
            $policy = New-Object -TypeName $policyDataType
            $policy.GroupUserName = $Identity
            $policy.Roles = @()
            #Add new policy to the folder's policies
            $policies += $policy
        }

        # creating new role
        $role = $policy.Roles | Where-Object { $_.Name -eq $RoleName } | Select-Object -First 1
        if (-not $role)
        {
            $role = New-Object -TypeName $roleDataType
            $role.Name = $RoleName
            #Add the role to the new Policy
            $policy.Roles += $role
        }

        # updating policies on the item
        try
        {
            Write-Verbose "Granting $($role.Name) to $($policy.GroupUserName) on $Path..."
            $proxy.SetPolicies($Path, $policies)
            Write-Verbose "Granted $($role.Name) to $($policy.GroupUserName) on $Path!"
        }
        catch
        {
            throw (New-Object System.Exception("Error occurred while granting $($role.Name) to $($policy.GroupUserName) on $Path! Please verify if you have typed the user full name. You can get the current permissions by running the Get-RsCatalogItemRole command. $($_.Exception.Message)", $_.Exception))
        }
        #endregion Assign Permissions
    }
}
New-Alias -Name "Grant-AccessOnCatalogItem" -Value Grant-RsCatalogItemRole -Scope Global