diff --git a/services/authorization/mgmt/2015-07-01/authorization/classic_administrators.go b/services/authorization/mgmt/2015-07-01/authorization/classic_administrators.go new file mode 100644 index 000000000000..063e8e6e9324 --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/classic_administrators.go @@ -0,0 +1,90 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// ClassicAdministratorsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type ClassicAdministratorsClient struct { + ManagementClient +} + +// NewClassicAdministratorsClient creates an instance of the ClassicAdministratorsClient client. +func NewClassicAdministratorsClient(p pipeline.Pipeline) ClassicAdministratorsClient { + return ClassicAdministratorsClient{NewManagementClient(p)} +} + +// List gets service administrator, account administrator, and co-administrators for the subscription. +func (client ClassicAdministratorsClient) List(ctx context.Context) (*ClassicAdministratorListResult, error) { + req, err := client.listPreparer() + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ClassicAdministratorListResult), err +} + +// listPreparer prepares the List request. +func (client ClassicAdministratorsClient) listPreparer() (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client ClassicAdministratorsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ClassicAdministratorListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/classicadministrators.go b/services/authorization/mgmt/2015-07-01/authorization/classicadministrators.go deleted file mode 100644 index ef906747c7c6..000000000000 --- a/services/authorization/mgmt/2015-07-01/authorization/classicadministrators.go +++ /dev/null @@ -1,133 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// ClassicAdministratorsClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type ClassicAdministratorsClient struct { - BaseClient -} - -// NewClassicAdministratorsClient creates an instance of the ClassicAdministratorsClient client. -func NewClassicAdministratorsClient(subscriptionID string) ClassicAdministratorsClient { - return NewClassicAdministratorsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewClassicAdministratorsClientWithBaseURI creates an instance of the ClassicAdministratorsClient client. -func NewClassicAdministratorsClientWithBaseURI(baseURI string, subscriptionID string) ClassicAdministratorsClient { - return ClassicAdministratorsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets service administrator, account administrator, and co-administrators for the subscription. -func (client ClassicAdministratorsClient) List(ctx context.Context) (result ClassicAdministratorListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.calr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "List", resp, "Failure sending request") - return - } - - result.calr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ClassicAdministratorsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ClassicAdministratorsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ClassicAdministratorsClient) ListResponder(resp *http.Response) (result ClassicAdministratorListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ClassicAdministratorsClient) listNextResults(lastResults ClassicAdministratorListResult) (result ClassicAdministratorListResult, err error) { - req, err := lastResults.classicAdministratorListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ClassicAdministratorsClient) ListComplete(ctx context.Context) (result ClassicAdministratorListResultIterator, err error) { - result.page, err = client.List(ctx) - return -} diff --git a/services/authorization/mgmt/2015-07-01/authorization/client.go b/services/authorization/mgmt/2015-07-01/authorization/client.go index cdce45f42202..e0feeb1bbfdd 100644 --- a/services/authorization/mgmt/2015-07-01/authorization/client.go +++ b/services/authorization/mgmt/2015-07-01/authorization/client.go @@ -1,9 +1,3 @@ -// Package authorization implements the Azure ARM Authorization service API version 2015-07-01. -// -// Role based access control provides you a way to apply granular level policy administration down to individual -// resources or resource groups. These operations enable you to manage role definitions and role assignments. A role -// definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure -// Active Directory users. package authorization // Copyright (c) Microsoft and contributors. All rights reserved. @@ -24,31 +18,46 @@ package authorization // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( - "github.com/Azure/go-autorest/autorest" + "github.com/Azure/azure-pipeline-go/pipeline" + "net/url" ) const ( - // DefaultBaseURI is the default URI used for the service Authorization - DefaultBaseURI = "https://management.azure.com" + // ServiceVersion specifies the version of the operations used in this package. + ServiceVersion = "2015-07-01" + // DefaultBaseURL is the default URL used for the service Authorization + DefaultBaseURL = "https://management.azure.com" ) -// BaseClient is the base client for Authorization. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string +// ManagementClient is the base client for Authorization. +type ManagementClient struct { + url url.URL + p pipeline.Pipeline } -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) +// NewManagementClient creates an instance of the ManagementClient client. +func NewManagementClient(p pipeline.Pipeline) ManagementClient { + u, err := url.Parse(DefaultBaseURL) + if err != nil { + panic(err) + } + return NewManagementClientWithURL(*u, p) } -// NewWithBaseURI creates an instance of the BaseClient client. -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, +// NewManagementClientWithURL creates an instance of the ManagementClient client. +func NewManagementClientWithURL(url url.URL, p pipeline.Pipeline) ManagementClient { + return ManagementClient{ + url: url, + p: p, } } + +// URL returns a copy of the URL for this client. +func (mc ManagementClient) URL() url.URL { + return mc.url +} + +// Pipeline returns the pipeline for this client. +func (mc ManagementClient) Pipeline() pipeline.Pipeline { + return mc.p +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/models.go b/services/authorization/mgmt/2015-07-01/authorization/models.go index e18aeced9729..5b9a26f66091 100644 --- a/services/authorization/mgmt/2015-07-01/authorization/models.go +++ b/services/authorization/mgmt/2015-07-01/authorization/models.go @@ -18,12 +18,31 @@ package authorization // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/to" "net/http" ) -// ClassicAdministrator classic Administrators +// Marker represents an opaque value used in paged responses. +type Marker struct { + val *string +} + +// NotDone returns true if the list enumeration should be started or is not yet complete. Specifically, NotDone returns true +// for a just-initialized (zero value) Marker indicating that you should make an initial request to get a result portion from +// the service. NotDone also returns true whenever the service returns an interim result portion. NotDone returns false only +// after the service has returned the final result portion. +func (m Marker) NotDone() bool { + return m.val == nil || *m.val != "" +} + +// UnmarshalXML implements the xml.Unmarshaler interface for Marker. +func (m *Marker) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var out string + err := d.DecodeElement(&out, &start) + m.val = &out + return err +} + +// ClassicAdministrator - Classic Administrators type ClassicAdministrator struct { // ID - The ID of the administrator. ID *string `json:"id,omitempty"` @@ -35,109 +54,31 @@ type ClassicAdministrator struct { Properties *ClassicAdministratorProperties `json:"properties,omitempty"` } -// ClassicAdministratorListResult classicAdministrator list result information. +// ClassicAdministratorListResult - ClassicAdministrator list result information. type ClassicAdministratorListResult struct { - autorest.Response `json:"-"` + rawResponse *http.Response // Value - An array of administrators. - Value *[]ClassicAdministrator `json:"value,omitempty"` + Value []ClassicAdministrator `json:"value,omitempty"` // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ClassicAdministratorListResultIterator provides access to a complete listing of ClassicAdministrator values. -type ClassicAdministratorListResultIterator struct { - i int - page ClassicAdministratorListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ClassicAdministratorListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ClassicAdministratorListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ClassicAdministratorListResultIterator) Response() ClassicAdministratorListResult { - return iter.page.Response() + NextLink Marker `json:"NextLink"` } -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ClassicAdministratorListResultIterator) Value() ClassicAdministrator { - if !iter.page.NotDone() { - return ClassicAdministrator{} - } - return iter.page.Values()[iter.i] +// Response returns the raw HTTP response object. +func (calr ClassicAdministratorListResult) Response() *http.Response { + return calr.rawResponse } -// IsEmpty returns true if the ListResult contains no values. -func (calr ClassicAdministratorListResult) IsEmpty() bool { - return calr.Value == nil || len(*calr.Value) == 0 +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (calr ClassicAdministratorListResult) StatusCode() int { + return calr.rawResponse.StatusCode } -// classicAdministratorListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (calr ClassicAdministratorListResult) classicAdministratorListResultPreparer() (*http.Request, error) { - if calr.NextLink == nil || len(to.String(calr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(calr.NextLink))) +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (calr ClassicAdministratorListResult) Status() string { + return calr.rawResponse.Status } -// ClassicAdministratorListResultPage contains a page of ClassicAdministrator values. -type ClassicAdministratorListResultPage struct { - fn func(ClassicAdministratorListResult) (ClassicAdministratorListResult, error) - calr ClassicAdministratorListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ClassicAdministratorListResultPage) Next() error { - next, err := page.fn(page.calr) - if err != nil { - return err - } - page.calr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ClassicAdministratorListResultPage) NotDone() bool { - return !page.calr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ClassicAdministratorListResultPage) Response() ClassicAdministratorListResult { - return page.calr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ClassicAdministratorListResultPage) Values() []ClassicAdministrator { - if page.calr.IsEmpty() { - return nil - } - return *page.calr.Value -} - -// ClassicAdministratorProperties classic Administrator properties. +// ClassicAdministratorProperties - Classic Administrator properties. type ClassicAdministratorProperties struct { // EmailAddress - The email address of the administrator. EmailAddress *string `json:"emailAddress,omitempty"` @@ -145,117 +86,39 @@ type ClassicAdministratorProperties struct { Role *string `json:"role,omitempty"` } -// Permission role definition permissions. +// Permission - Role definition permissions. type Permission struct { // Actions - Allowed actions. - Actions *[]string `json:"actions,omitempty"` + Actions []string `json:"actions,omitempty"` // NotActions - Denied actions. - NotActions *[]string `json:"notActions,omitempty"` + NotActions []string `json:"notActions,omitempty"` } -// PermissionGetResult permissions information. +// PermissionGetResult - Permissions information. type PermissionGetResult struct { - autorest.Response `json:"-"` + rawResponse *http.Response // Value - An array of permissions. - Value *[]Permission `json:"value,omitempty"` + Value []Permission `json:"value,omitempty"` // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PermissionGetResultIterator provides access to a complete listing of Permission values. -type PermissionGetResultIterator struct { - i int - page PermissionGetResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PermissionGetResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PermissionGetResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PermissionGetResultIterator) Response() PermissionGetResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PermissionGetResultIterator) Value() Permission { - if !iter.page.NotDone() { - return Permission{} - } - return iter.page.Values()[iter.i] + NextLink Marker `json:"NextLink"` } -// IsEmpty returns true if the ListResult contains no values. -func (pgr PermissionGetResult) IsEmpty() bool { - return pgr.Value == nil || len(*pgr.Value) == 0 +// Response returns the raw HTTP response object. +func (pgr PermissionGetResult) Response() *http.Response { + return pgr.rawResponse } -// permissionGetResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pgr PermissionGetResult) permissionGetResultPreparer() (*http.Request, error) { - if pgr.NextLink == nil || len(to.String(pgr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pgr.NextLink))) +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pgr PermissionGetResult) StatusCode() int { + return pgr.rawResponse.StatusCode } -// PermissionGetResultPage contains a page of Permission values. -type PermissionGetResultPage struct { - fn func(PermissionGetResult) (PermissionGetResult, error) - pgr PermissionGetResult +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pgr PermissionGetResult) Status() string { + return pgr.rawResponse.Status } -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PermissionGetResultPage) Next() error { - next, err := page.fn(page.pgr) - if err != nil { - return err - } - page.pgr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PermissionGetResultPage) NotDone() bool { - return !page.pgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PermissionGetResultPage) Response() PermissionGetResult { - return page.pgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PermissionGetResultPage) Values() []Permission { - if page.pgr.IsEmpty() { - return nil - } - return *page.pgr.Value -} - -// ProviderOperation operation +// ProviderOperation - Operation type ProviderOperation struct { // Name - The operation name. Name *string `json:"name,omitempty"` @@ -266,12 +129,12 @@ type ProviderOperation struct { // Origin - The operation origin. Origin *string `json:"origin,omitempty"` // Properties - The operation properties. - Properties *map[string]interface{} `json:"properties,omitempty"` + Properties map[string]interface{} `json:"properties,omitempty"` } -// ProviderOperationsMetadata provider Operations metadata +// ProviderOperationsMetadata - Provider Operations metadata type ProviderOperationsMetadata struct { - autorest.Response `json:"-"` + rawResponse *http.Response // ID - The provider id. ID *string `json:"id,omitempty"` // Name - The provider name. @@ -281,127 +144,63 @@ type ProviderOperationsMetadata struct { // DisplayName - The provider display name. DisplayName *string `json:"displayName,omitempty"` // ResourceTypes - The provider resource types - ResourceTypes *[]ResourceType `json:"resourceTypes,omitempty"` + ResourceTypes []ResourceType `json:"resourceTypes,omitempty"` // Operations - The provider operations. - Operations *[]ProviderOperation `json:"operations,omitempty"` -} - -// ProviderOperationsMetadataListResult provider operations metadata list -type ProviderOperationsMetadataListResult struct { - autorest.Response `json:"-"` - // Value - The list of providers. - Value *[]ProviderOperationsMetadata `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ProviderOperationsMetadataListResultIterator provides access to a complete listing of ProviderOperationsMetadata -// values. -type ProviderOperationsMetadataListResultIterator struct { - i int - page ProviderOperationsMetadataListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ProviderOperationsMetadataListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ProviderOperationsMetadataListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ProviderOperationsMetadataListResultIterator) Response() ProviderOperationsMetadataListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ProviderOperationsMetadataListResultIterator) Value() ProviderOperationsMetadata { - if !iter.page.NotDone() { - return ProviderOperationsMetadata{} - } - return iter.page.Values()[iter.i] + Operations []ProviderOperation `json:"operations,omitempty"` } -// IsEmpty returns true if the ListResult contains no values. -func (pomlr ProviderOperationsMetadataListResult) IsEmpty() bool { - return pomlr.Value == nil || len(*pomlr.Value) == 0 +// Response returns the raw HTTP response object. +func (pom ProviderOperationsMetadata) Response() *http.Response { + return pom.rawResponse } -// providerOperationsMetadataListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pomlr ProviderOperationsMetadataListResult) providerOperationsMetadataListResultPreparer() (*http.Request, error) { - if pomlr.NextLink == nil || len(to.String(pomlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pomlr.NextLink))) +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pom ProviderOperationsMetadata) StatusCode() int { + return pom.rawResponse.StatusCode } -// ProviderOperationsMetadataListResultPage contains a page of ProviderOperationsMetadata values. -type ProviderOperationsMetadataListResultPage struct { - fn func(ProviderOperationsMetadataListResult) (ProviderOperationsMetadataListResult, error) - pomlr ProviderOperationsMetadataListResult +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pom ProviderOperationsMetadata) Status() string { + return pom.rawResponse.Status } -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ProviderOperationsMetadataListResultPage) Next() error { - next, err := page.fn(page.pomlr) - if err != nil { - return err - } - page.pomlr = next - return nil +// ProviderOperationsMetadataListResult - Provider operations metadata list +type ProviderOperationsMetadataListResult struct { + rawResponse *http.Response + // Value - The list of providers. + Value []ProviderOperationsMetadata `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` } -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ProviderOperationsMetadataListResultPage) NotDone() bool { - return !page.pomlr.IsEmpty() +// Response returns the raw HTTP response object. +func (pomlr ProviderOperationsMetadataListResult) Response() *http.Response { + return pomlr.rawResponse } -// Response returns the raw server response from the last page request. -func (page ProviderOperationsMetadataListResultPage) Response() ProviderOperationsMetadataListResult { - return page.pomlr +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pomlr ProviderOperationsMetadataListResult) StatusCode() int { + return pomlr.rawResponse.StatusCode } -// Values returns the slice of values for the current page or nil if there are no values. -func (page ProviderOperationsMetadataListResultPage) Values() []ProviderOperationsMetadata { - if page.pomlr.IsEmpty() { - return nil - } - return *page.pomlr.Value +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pomlr ProviderOperationsMetadataListResult) Status() string { + return pomlr.rawResponse.Status } -// ResourceType resource Type +// ResourceType - Resource Type type ResourceType struct { // Name - The resource type name. Name *string `json:"name,omitempty"` // DisplayName - The resource type display name. DisplayName *string `json:"displayName,omitempty"` // Operations - The resource type operations. - Operations *[]ProviderOperation `json:"operations,omitempty"` + Operations []ProviderOperation `json:"operations,omitempty"` } -// RoleAssignment role Assignments +// RoleAssignment - Role Assignments type RoleAssignment struct { - autorest.Response `json:"-"` + rawResponse *http.Response // ID - The role assignment ID. ID *string `json:"id,omitempty"` // Name - The role assignment name. @@ -412,121 +211,58 @@ type RoleAssignment struct { Properties *RoleAssignmentPropertiesWithScope `json:"properties,omitempty"` } -// RoleAssignmentCreateParameters role assignment create parameters. +// Response returns the raw HTTP response object. +func (ra RoleAssignment) Response() *http.Response { + return ra.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (ra RoleAssignment) StatusCode() int { + return ra.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (ra RoleAssignment) Status() string { + return ra.rawResponse.Status +} + +// RoleAssignmentCreateParameters - Role assignment create parameters. type RoleAssignmentCreateParameters struct { // Properties - Role assignment properties. Properties *RoleAssignmentProperties `json:"properties,omitempty"` } -// RoleAssignmentFilter role Assignments filter +// RoleAssignmentFilter - Role Assignments filter type RoleAssignmentFilter struct { // PrincipalID - Returns role assignment of the specific principal. PrincipalID *string `json:"principalId,omitempty"` } -// RoleAssignmentListResult role assignment list operation result. +// RoleAssignmentListResult - Role assignment list operation result. type RoleAssignmentListResult struct { - autorest.Response `json:"-"` + rawResponse *http.Response // Value - Role assignment list. - Value *[]RoleAssignment `json:"value,omitempty"` + Value []RoleAssignment `json:"value,omitempty"` // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RoleAssignmentListResultIterator provides access to a complete listing of RoleAssignment values. -type RoleAssignmentListResultIterator struct { - i int - page RoleAssignmentListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RoleAssignmentListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RoleAssignmentListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RoleAssignmentListResultIterator) Response() RoleAssignmentListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RoleAssignmentListResultIterator) Value() RoleAssignment { - if !iter.page.NotDone() { - return RoleAssignment{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (ralr RoleAssignmentListResult) IsEmpty() bool { - return ralr.Value == nil || len(*ralr.Value) == 0 -} - -// roleAssignmentListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ralr RoleAssignmentListResult) roleAssignmentListResultPreparer() (*http.Request, error) { - if ralr.NextLink == nil || len(to.String(ralr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ralr.NextLink))) -} - -// RoleAssignmentListResultPage contains a page of RoleAssignment values. -type RoleAssignmentListResultPage struct { - fn func(RoleAssignmentListResult) (RoleAssignmentListResult, error) - ralr RoleAssignmentListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RoleAssignmentListResultPage) Next() error { - next, err := page.fn(page.ralr) - if err != nil { - return err - } - page.ralr = next - return nil + NextLink Marker `json:"NextLink"` } -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RoleAssignmentListResultPage) NotDone() bool { - return !page.ralr.IsEmpty() +// Response returns the raw HTTP response object. +func (ralr RoleAssignmentListResult) Response() *http.Response { + return ralr.rawResponse } -// Response returns the raw server response from the last page request. -func (page RoleAssignmentListResultPage) Response() RoleAssignmentListResult { - return page.ralr +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (ralr RoleAssignmentListResult) StatusCode() int { + return ralr.rawResponse.StatusCode } -// Values returns the slice of values for the current page or nil if there are no values. -func (page RoleAssignmentListResultPage) Values() []RoleAssignment { - if page.ralr.IsEmpty() { - return nil - } - return *page.ralr.Value +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (ralr RoleAssignmentListResult) Status() string { + return ralr.rawResponse.Status } -// RoleAssignmentProperties role assignment properties. +// RoleAssignmentProperties - Role assignment properties. type RoleAssignmentProperties struct { // RoleDefinitionID - The role definition ID used in the role assignment. RoleDefinitionID *string `json:"roleDefinitionId,omitempty"` @@ -534,7 +270,7 @@ type RoleAssignmentProperties struct { PrincipalID *string `json:"principalId,omitempty"` } -// RoleAssignmentPropertiesWithScope role assignment properties with scope. +// RoleAssignmentPropertiesWithScope - Role assignment properties with scope. type RoleAssignmentPropertiesWithScope struct { // Scope - The role assignment scope. Scope *string `json:"scope,omitempty"` @@ -544,9 +280,9 @@ type RoleAssignmentPropertiesWithScope struct { PrincipalID *string `json:"principalId,omitempty"` } -// RoleDefinition role definition. +// RoleDefinition - Role definition. type RoleDefinition struct { - autorest.Response `json:"-"` + rawResponse *http.Response // ID - The role definition ID. ID *string `json:"id,omitempty"` // Name - The role definition name. @@ -557,115 +293,52 @@ type RoleDefinition struct { Properties *RoleDefinitionProperties `json:"properties,omitempty"` } -// RoleDefinitionFilter role Definitions filter -type RoleDefinitionFilter struct { - // RoleName - Returns role definition with the specific name. - RoleName *string `json:"roleName,omitempty"` -} - -// RoleDefinitionListResult role definition list operation result. -type RoleDefinitionListResult struct { - autorest.Response `json:"-"` - // Value - Role definition list. - Value *[]RoleDefinition `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` +// Response returns the raw HTTP response object. +func (rd RoleDefinition) Response() *http.Response { + return rd.rawResponse } -// RoleDefinitionListResultIterator provides access to a complete listing of RoleDefinition values. -type RoleDefinitionListResultIterator struct { - i int - page RoleDefinitionListResultPage +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (rd RoleDefinition) StatusCode() int { + return rd.rawResponse.StatusCode } -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RoleDefinitionListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (rd RoleDefinition) Status() string { + return rd.rawResponse.Status } -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RoleDefinitionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RoleDefinitionListResultIterator) Response() RoleDefinitionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RoleDefinitionListResultIterator) Value() RoleDefinition { - if !iter.page.NotDone() { - return RoleDefinition{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (rdlr RoleDefinitionListResult) IsEmpty() bool { - return rdlr.Value == nil || len(*rdlr.Value) == 0 -} - -// roleDefinitionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rdlr RoleDefinitionListResult) roleDefinitionListResultPreparer() (*http.Request, error) { - if rdlr.NextLink == nil || len(to.String(rdlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rdlr.NextLink))) -} - -// RoleDefinitionListResultPage contains a page of RoleDefinition values. -type RoleDefinitionListResultPage struct { - fn func(RoleDefinitionListResult) (RoleDefinitionListResult, error) - rdlr RoleDefinitionListResult +// RoleDefinitionFilter - Role Definitions filter +type RoleDefinitionFilter struct { + // RoleName - Returns role definition with the specific name. + RoleName *string `json:"roleName,omitempty"` } -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RoleDefinitionListResultPage) Next() error { - next, err := page.fn(page.rdlr) - if err != nil { - return err - } - page.rdlr = next - return nil +// RoleDefinitionListResult - Role definition list operation result. +type RoleDefinitionListResult struct { + rawResponse *http.Response + // Value - Role definition list. + Value []RoleDefinition `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` } -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RoleDefinitionListResultPage) NotDone() bool { - return !page.rdlr.IsEmpty() +// Response returns the raw HTTP response object. +func (rdlr RoleDefinitionListResult) Response() *http.Response { + return rdlr.rawResponse } -// Response returns the raw server response from the last page request. -func (page RoleDefinitionListResultPage) Response() RoleDefinitionListResult { - return page.rdlr +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (rdlr RoleDefinitionListResult) StatusCode() int { + return rdlr.rawResponse.StatusCode } -// Values returns the slice of values for the current page or nil if there are no values. -func (page RoleDefinitionListResultPage) Values() []RoleDefinition { - if page.rdlr.IsEmpty() { - return nil - } - return *page.rdlr.Value +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (rdlr RoleDefinitionListResult) Status() string { + return rdlr.rawResponse.Status } -// RoleDefinitionProperties role definition properties. +// RoleDefinitionProperties - Role definition properties. type RoleDefinitionProperties struct { // RoleName - The role name. RoleName *string `json:"roleName,omitempty"` @@ -674,7 +347,7 @@ type RoleDefinitionProperties struct { // Type - The role type. Type *string `json:"type,omitempty"` // Permissions - Role definition permissions. - Permissions *[]Permission `json:"permissions,omitempty"` + Permissions []Permission `json:"permissions,omitempty"` // AssignableScopes - Role definition assignable scopes. - AssignableScopes *[]string `json:"assignableScopes,omitempty"` + AssignableScopes []string `json:"assignableScopes,omitempty"` } diff --git a/services/authorization/mgmt/2015-07-01/authorization/permissions.go b/services/authorization/mgmt/2015-07-01/authorization/permissions.go index 935be1f5a688..1c387e6ad92b 100644 --- a/services/authorization/mgmt/2015-07-01/authorization/permissions.go +++ b/services/authorization/mgmt/2015-07-01/authorization/permissions.go @@ -19,8 +19,9 @@ package authorization import ( "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" "net/http" ) @@ -29,17 +30,12 @@ import ( // assignments. A role definition describes the set of actions that can be performed on resources. A role assignment // grants access to Azure Active Directory users. type PermissionsClient struct { - BaseClient + ManagementClient } // NewPermissionsClient creates an instance of the PermissionsClient client. -func NewPermissionsClient(subscriptionID string) PermissionsClient { - return NewPermissionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPermissionsClientWithBaseURI creates an instance of the PermissionsClient client. -func NewPermissionsClientWithBaseURI(baseURI string, subscriptionID string) PermissionsClient { - return PermissionsClient{NewWithBaseURI(baseURI, subscriptionID)} +func NewPermissionsClient(p pipeline.Pipeline) PermissionsClient { + return PermissionsClient{NewManagementClient(p)} } // ListForResource gets all permissions the caller has for a resource. @@ -48,189 +44,105 @@ func NewPermissionsClientWithBaseURI(baseURI string, subscriptionID string) Perm // resourceProviderNamespace is the namespace of the resource provider. parentResourcePath is the parent resource // identity. resourceType is the resource type of the resource. resourceName is the name of the resource to get the // permissions for. -func (client PermissionsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result PermissionGetResultPage, err error) { - result.fn = client.listForResourceNextResults - req, err := client.ListForResourcePreparer(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName) +func (client PermissionsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (*PermissionGetResult, error) { + req, err := client.listForResourcePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResource", nil, "Failure preparing request") - return + return nil, err } - - resp, err := client.ListForResourceSender(req) + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceResponder}, req) if err != nil { - result.pgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResource", resp, "Failure sending request") - return + return nil, err } + return resp.(*PermissionGetResult), err +} - result.pgr, err = client.ListForResourceResponder(resp) +// listForResourcePreparer prepares the ListForResource request. +func (client PermissionsClient) listForResourcePreparer(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions" + req, err := pipeline.NewRequest("GET", u, nil) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResource", resp, "Failure responding to request") + return req, pipeline.NewError(err, "failed to create request") } - - return + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil } -// ListForResourcePreparer prepares the ListForResource request. -func (client PermissionsClient) ListForResourcePreparer(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "parentResourcePath": parentResourcePath, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "resourceName": autorest.Encode("path", resourceName), - "resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace), - "resourceType": resourceType, - "subscriptionId": autorest.Encode("path", client.SubscriptionID), +// listForResourceResponder handles the response to the ListForResource request. +func (client PermissionsClient) listForResourceResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceSender sends the ListForResource request. The method will close the -// http.Response Body if it receives an error. -func (client PermissionsClient) ListForResourceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceResponder handles the response to the ListForResource request. The method always -// closes the http.Response Body. -func (client PermissionsClient) ListForResourceResponder(resp *http.Response) (result PermissionGetResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceNextResults retrieves the next set of results, if any. -func (client PermissionsClient) listForResourceNextResults(lastResults PermissionGetResult) (result PermissionGetResult, err error) { - req, err := lastResults.permissionGetResultPreparer() + result := &PermissionGetResult{rawResponse: resp.Response()} if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return + return result, err } - resp, err := client.ListForResourceSender(req) + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceNextResults", resp, "Failure sending next results request") + return result, NewResponseError(err, resp.Response(), "failed to read response body") } - result, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceNextResults", resp, "Failure responding to next results request") + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } } - return -} - -// ListForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client PermissionsClient) ListForResourceComplete(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result PermissionGetResultIterator, err error) { - result.page, err = client.ListForResource(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName) - return + return result, nil } // ListForResourceGroup gets all permissions the caller has for a resource group. // // resourceGroupName is the name of the resource group to get the permissions for. The name is case insensitive. -func (client PermissionsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string) (result PermissionGetResultPage, err error) { - result.fn = client.listForResourceGroupNextResults - req, err := client.ListForResourceGroupPreparer(ctx, resourceGroupName) +func (client PermissionsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string) (*PermissionGetResult, error) { + req, err := client.listForResourceGroupPreparer(resourceGroupName) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResourceGroup", nil, "Failure preparing request") - return + return nil, err } - - resp, err := client.ListForResourceGroupSender(req) + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceGroupResponder}, req) if err != nil { - result.pgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResourceGroup", resp, "Failure sending request") - return + return nil, err } + return resp.(*PermissionGetResult), err +} - result.pgr, err = client.ListForResourceGroupResponder(resp) +// listForResourceGroupPreparer prepares the ListForResourceGroup request. +func (client PermissionsClient) listForResourceGroupPreparer(resourceGroupName string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions" + req, err := pipeline.NewRequest("GET", u, nil) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResourceGroup", resp, "Failure responding to request") + return req, pipeline.NewError(err, "failed to create request") } - - return + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil } -// ListForResourceGroupPreparer prepares the ListForResourceGroup request. -func (client PermissionsClient) ListForResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), +// listForResourceGroupResponder handles the response to the ListForResourceGroup request. +func (client PermissionsClient) listForResourceGroupResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PermissionsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always -// closes the http.Response Body. -func (client PermissionsClient) ListForResourceGroupResponder(resp *http.Response) (result PermissionGetResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceGroupNextResults retrieves the next set of results, if any. -func (client PermissionsClient) listForResourceGroupNextResults(lastResults PermissionGetResult) (result PermissionGetResult, err error) { - req, err := lastResults.permissionGetResultPreparer() + result := &PermissionGetResult{rawResponse: resp.Response()} if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceGroupNextResults", nil, "Failure preparing next results request") + return result, err } - if req == nil { - return - } - resp, err := client.ListForResourceGroupSender(req) + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceGroupNextResults", resp, "Failure sending next results request") + return result, NewResponseError(err, resp.Response(), "failed to read response body") } - result, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceGroupNextResults", resp, "Failure responding to next results request") + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } } - return -} - -// ListForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PermissionsClient) ListForResourceGroupComplete(ctx context.Context, resourceGroupName string) (result PermissionGetResultIterator, err error) { - result.page, err = client.ListForResourceGroup(ctx, resourceGroupName) - return + return result, nil } diff --git a/services/authorization/mgmt/2015-07-01/authorization/provider_operations_metadata.go b/services/authorization/mgmt/2015-07-01/authorization/provider_operations_metadata.go new file mode 100644 index 000000000000..9ef7439aa2f5 --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/provider_operations_metadata.go @@ -0,0 +1,152 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// ProviderOperationsMetadataClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type ProviderOperationsMetadataClient struct { + ManagementClient +} + +// NewProviderOperationsMetadataClient creates an instance of the ProviderOperationsMetadataClient client. +func NewProviderOperationsMetadataClient(p pipeline.Pipeline) ProviderOperationsMetadataClient { + return ProviderOperationsMetadataClient{NewManagementClient(p)} +} + +// Get gets provider operations metadata for the specified resource provider. +// +// resourceProviderNamespace is the namespace of the resource provider. expand is specifies whether to expand the +// values. +func (client ProviderOperationsMetadataClient) Get(ctx context.Context, resourceProviderNamespace string, expand *string) (*ProviderOperationsMetadata, error) { + req, err := client.getPreparer(resourceProviderNamespace, expand) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ProviderOperationsMetadata), err +} + +// getPreparer prepares the Get request. +func (client ProviderOperationsMetadataClient) getPreparer(resourceProviderNamespace string, expand *string) (pipeline.Request, error) { + u := client.url + u.Path = "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + if expand != nil { + params.Set("$expand", *expand) + } + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client ProviderOperationsMetadataClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ProviderOperationsMetadata{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List gets provider operations metadata for all resource providers. +// +// expand is specifies whether to expand the values. +func (client ProviderOperationsMetadataClient) List(ctx context.Context, expand *string) (*ProviderOperationsMetadataListResult, error) { + req, err := client.listPreparer(expand) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ProviderOperationsMetadataListResult), err +} + +// listPreparer prepares the List request. +func (client ProviderOperationsMetadataClient) listPreparer(expand *string) (pipeline.Request, error) { + u := client.url + u.Path = "/providers/Microsoft.Authorization/providerOperations" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + if expand != nil { + params.Set("$expand", *expand) + } + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client ProviderOperationsMetadataClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ProviderOperationsMetadataListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/provideroperationsmetadata.go b/services/authorization/mgmt/2015-07-01/authorization/provideroperationsmetadata.go deleted file mode 100644 index b6069641030d..000000000000 --- a/services/authorization/mgmt/2015-07-01/authorization/provideroperationsmetadata.go +++ /dev/null @@ -1,202 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// ProviderOperationsMetadataClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type ProviderOperationsMetadataClient struct { - BaseClient -} - -// NewProviderOperationsMetadataClient creates an instance of the ProviderOperationsMetadataClient client. -func NewProviderOperationsMetadataClient(subscriptionID string) ProviderOperationsMetadataClient { - return NewProviderOperationsMetadataClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewProviderOperationsMetadataClientWithBaseURI creates an instance of the ProviderOperationsMetadataClient client. -func NewProviderOperationsMetadataClientWithBaseURI(baseURI string, subscriptionID string) ProviderOperationsMetadataClient { - return ProviderOperationsMetadataClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets provider operations metadata for the specified resource provider. -// -// resourceProviderNamespace is the namespace of the resource provider. expand is specifies whether to expand the -// values. -func (client ProviderOperationsMetadataClient) Get(ctx context.Context, resourceProviderNamespace string, expand string) (result ProviderOperationsMetadata, err error) { - req, err := client.GetPreparer(ctx, resourceProviderNamespace, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client ProviderOperationsMetadataClient) GetPreparer(ctx context.Context, resourceProviderNamespace string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace), - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ProviderOperationsMetadataClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ProviderOperationsMetadataClient) GetResponder(resp *http.Response) (result ProviderOperationsMetadata, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets provider operations metadata for all resource providers. -// -// expand is specifies whether to expand the values. -func (client ProviderOperationsMetadataClient) List(ctx context.Context, expand string) (result ProviderOperationsMetadataListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pomlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "List", resp, "Failure sending request") - return - } - - result.pomlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ProviderOperationsMetadataClient) ListPreparer(ctx context.Context, expand string) (*http.Request, error) { - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Authorization/providerOperations"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ProviderOperationsMetadataClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ProviderOperationsMetadataClient) ListResponder(resp *http.Response) (result ProviderOperationsMetadataListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ProviderOperationsMetadataClient) listNextResults(lastResults ProviderOperationsMetadataListResult) (result ProviderOperationsMetadataListResult, err error) { - req, err := lastResults.providerOperationsMetadataListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProviderOperationsMetadataClient) ListComplete(ctx context.Context, expand string) (result ProviderOperationsMetadataListResultIterator, err error) { - result.page, err = client.List(ctx, expand) - return -} diff --git a/services/authorization/mgmt/2015-07-01/authorization/responder_policy.go b/services/authorization/mgmt/2015-07-01/authorization/responder_policy.go new file mode 100644 index 000000000000..06f946241b6e --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/responder_policy.go @@ -0,0 +1,81 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/xml" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" +) + +type responder func(resp pipeline.Response) (result pipeline.Response, err error) + +// ResponderPolicyFactory is a Factory capable of creating a responder pipeline. +type responderPolicyFactory struct { + responder responder +} + +// New creates a responder policy factory. +func (arpf responderPolicyFactory) New(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.Policy { + return responderPolicy{next: next, responder: arpf.responder} +} + +type responderPolicy struct { + next pipeline.Policy + responder responder +} + +// Do sends the request to the service and validates/deserializes the HTTP response. +func (arp responderPolicy) Do(ctx context.Context, request pipeline.Request) (pipeline.Response, error) { + resp, err := arp.next.Do(ctx, request) + if err != nil { + return resp, err + } + return arp.responder(resp) +} + +// validateResponse checks an HTTP response's status code against a legal set of codes. +// If the response code is not legal, then validateResponse reads all of the response's body +// (containing error information) and returns a response error. +func validateResponse(resp pipeline.Response, successStatusCodes ...int) error { + if resp == nil { + return NewResponseError(nil, nil, "nil response") + } + responseCode := resp.Response().StatusCode + for _, i := range successStatusCodes { + if i == responseCode { + return nil + } + } + // only close the body in the failure case. in the + // success case responders will close the body as required. + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return NewResponseError(err, resp.Response(), "failed to read response body") + } + // the service code, description and details will be populated during unmarshalling + responseError := NewResponseError(nil, resp.Response(), resp.Response().Status) + if len(b) > 0 { + if err = xml.Unmarshal(b, &responseError); err != nil { + return NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return responseError +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/response_error.go b/services/authorization/mgmt/2015-07-01/authorization/response_error.go new file mode 100644 index 000000000000..3704b446893e --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/response_error.go @@ -0,0 +1,110 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "fmt" + "github.com/Azure/azure-pipeline-go/pipeline" + "net" + "net/http" +) + +// if you want to provide custom error handling set this variable to your constructor function +var responseErrorFactory func(cause error, response *http.Response, description string) error + +// ResponseError identifies a responder-generated network or response parsing error. +type ResponseError interface { + // Error exposes the Error(), Temporary() and Timeout() methods. + net.Error // Includes the Go error interface + + // Response returns the HTTP response. You may examine this but you should not modify it. + Response() *http.Response +} + +// NewResponseError creates an error object that implements the error interface. +func NewResponseError(cause error, response *http.Response, description string) error { + if responseErrorFactory != nil { + return responseErrorFactory(cause, response, description) + } + return &responseError{ + ErrorNode: pipeline.ErrorNode{}.Initialize(cause, 3), + response: response, + description: description, + } +} + +// responseError is the internal struct that implements the public ResponseError interface. +type responseError struct { + pipeline.ErrorNode // This is embedded so that responseError "inherits" Error, Temporary, Timeout, and Cause + response *http.Response + description string +} + +// Error implements the error interface's Error method to return a string representation of the error. +func (e *responseError) Error() string { + b := &bytes.Buffer{} + fmt.Fprintf(b, "===== RESPONSE ERROR (Code=%v) =====\n", e.response.StatusCode) + fmt.Fprintf(b, "Status=%s, Description: %s\n", e.response.Status, e.description) + s := b.String() + return e.ErrorNode.Error(s) +} + +// Response implements the ResponseError interface's method to return the HTTP response. +func (e *responseError) Response() *http.Response { + return e.response +} + +// RFC7807 PROBLEM ------------------------------------------------------------------------------------ +// RFC7807Problem ... This type can be publicly embedded in another type that wants to add additional members. +/*type RFC7807Problem struct { + // Mandatory: A (relative) URI reference identifying the problem type (it MAY refer to human-readable documentation). + typeURI string // Should default to "about:blank" + // Optional: Short, human-readable summary (maybe localized). + title string + // Optional: HTTP status code generated by the origin server + status int + // Optional: Human-readable explanation for this problem occurance. + // Should help client correct the problem. Clients should NOT parse this string. + detail string + // Optional: A (relative) URI identifying this specific problem occurence (it may or may not be dereferenced). + instance string +} +// NewRFC7807Problem ... +func NewRFC7807Problem(typeURI string, status int, titleFormat string, a ...interface{}) error { + return &RFC7807Problem{ + typeURI: typeURI, + status: status, + title: fmt.Sprintf(titleFormat, a...), + } +} +// Error returns the error information as a string. +func (e *RFC7807Problem) Error() string { + return e.title +} +// TypeURI ... +func (e *RFC7807Problem) TypeURI() string { + if e.typeURI == "" { + e.typeURI = "about:blank" + } + return e.typeURI +} +// Members ... +func (e *RFC7807Problem) Members() (status int, title, detail, instance string) { + return e.status, e.title, e.detail, e.instance +}*/ diff --git a/services/authorization/mgmt/2015-07-01/authorization/role_assignments.go b/services/authorization/mgmt/2015-07-01/authorization/role_assignments.go new file mode 100644 index 000000000000..0696fd5f7972 --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/role_assignments.go @@ -0,0 +1,623 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// RoleAssignmentsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type RoleAssignmentsClient struct { + ManagementClient +} + +// NewRoleAssignmentsClient creates an instance of the RoleAssignmentsClient client. +func NewRoleAssignmentsClient(p pipeline.Pipeline) RoleAssignmentsClient { + return RoleAssignmentsClient{NewManagementClient(p)} +} + +// Create creates a role assignment. +// +// scope is the scope of the role assignment to create. The scope can be any REST resource instance. For example, use +// '/subscriptions/{subscription-id}/' for a subscription, +// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and +// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' +// for a resource. roleAssignmentName is the name of the role assignment to create. It can be any valid GUID. +// parameters is parameters for the role assignment. +func (client RoleAssignmentsClient) Create(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (*RoleAssignment, error) { + req, err := client.createPreparer(scope, roleAssignmentName, parameters) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// createPreparer prepares the Create request. +func (client RoleAssignmentsClient) createPreparer(scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(parameters) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createResponder handles the response to the Create request. +func (client RoleAssignmentsClient) createResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// CreateByID creates a role assignment by ID. +// +// roleAssignmentID is the fully qualified ID of the role assignment, including the scope, resource name and resource +// type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: +// /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. +// parameters is parameters for the role assignment. +func (client RoleAssignmentsClient) CreateByID(ctx context.Context, roleAssignmentID string, parameters RoleAssignmentCreateParameters) (*RoleAssignment, error) { + req, err := client.createByIDPreparer(roleAssignmentID, parameters) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// createByIDPreparer prepares the CreateByID request. +func (client RoleAssignmentsClient) createByIDPreparer(roleAssignmentID string, parameters RoleAssignmentCreateParameters) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleAssignmentId}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(parameters) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createByIDResponder handles the response to the CreateByID request. +func (client RoleAssignmentsClient) createByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Delete deletes a role assignment. +// +// scope is the scope of the role assignment to delete. roleAssignmentName is the name of the role assignment to +// delete. +func (client RoleAssignmentsClient) Delete(ctx context.Context, scope string, roleAssignmentName string) (*RoleAssignment, error) { + req, err := client.deletePreparer(scope, roleAssignmentName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// deletePreparer prepares the Delete request. +func (client RoleAssignmentsClient) deletePreparer(scope string, roleAssignmentName string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteResponder handles the response to the Delete request. +func (client RoleAssignmentsClient) deleteResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// DeleteByID deletes a role assignment. +// +// roleAssignmentID is the fully qualified ID of the role assignment, including the scope, resource name and resource +// type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: +// /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. +func (client RoleAssignmentsClient) DeleteByID(ctx context.Context, roleAssignmentID string) (*RoleAssignment, error) { + req, err := client.deleteByIDPreparer(roleAssignmentID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// deleteByIDPreparer prepares the DeleteByID request. +func (client RoleAssignmentsClient) deleteByIDPreparer(roleAssignmentID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleAssignmentId}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteByIDResponder handles the response to the DeleteByID request. +func (client RoleAssignmentsClient) deleteByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Get get the specified role assignment. +// +// scope is the scope of the role assignment. roleAssignmentName is the name of the role assignment to get. +func (client RoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (*RoleAssignment, error) { + req, err := client.getPreparer(scope, roleAssignmentName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// getPreparer prepares the Get request. +func (client RoleAssignmentsClient) getPreparer(scope string, roleAssignmentName string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client RoleAssignmentsClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// GetByID gets a role assignment by ID. +// +// roleAssignmentID is the fully qualified ID of the role assignment, including the scope, resource name and resource +// type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: +// /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. +func (client RoleAssignmentsClient) GetByID(ctx context.Context, roleAssignmentID string) (*RoleAssignment, error) { + req, err := client.getByIDPreparer(roleAssignmentID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// getByIDPreparer prepares the GetByID request. +func (client RoleAssignmentsClient) getByIDPreparer(roleAssignmentID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleAssignmentId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getByIDResponder handles the response to the GetByID request. +func (client RoleAssignmentsClient) getByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List gets all role assignments for the subscription. +// +// filter is the filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the +// scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified +// principal. +func (client RoleAssignmentsClient) List(ctx context.Context, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listPreparer(filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listPreparer prepares the List request. +func (client RoleAssignmentsClient) listPreparer(filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client RoleAssignmentsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResource gets role assignments for a resource. +// +// resourceGroupName is the name of the resource group. resourceProviderNamespace is the namespace of the resource +// provider. parentResourcePath is the parent resource identity. resourceType is the resource type of the resource. +// resourceName is the name of the resource to get role assignments for. filter is the filter to apply on the +// operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq +// {id} to return all role assignments at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForResourcePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForResourcePreparer prepares the ListForResource request. +func (client RoleAssignmentsClient) listForResourcePreparer(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceResponder handles the response to the ListForResource request. +func (client RoleAssignmentsClient) listForResourceResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResourceGroup gets role assignments for a resource group. +// +// resourceGroupName is the name of the resource group. filter is the filter to apply on the operation. Use +// $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return +// all role assignments at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForResourceGroupPreparer(resourceGroupName, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceGroupResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForResourceGroupPreparer prepares the ListForResourceGroup request. +func (client RoleAssignmentsClient) listForResourceGroupPreparer(resourceGroupName string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceGroupResponder handles the response to the ListForResourceGroup request. +func (client RoleAssignmentsClient) listForResourceGroupResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForScope gets role assignments for a scope. +// +// scope is the scope of the role assignments. filter is the filter to apply on the operation. Use $filter=atScope() to +// return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments +// at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForScope(ctx context.Context, scope string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForScopePreparer(scope, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForScopeResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForScopePreparer prepares the ListForScope request. +func (client RoleAssignmentsClient) listForScopePreparer(scope string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForScopeResponder handles the response to the ListForScope request. +func (client RoleAssignmentsClient) listForScopeResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/role_definitions.go b/services/authorization/mgmt/2015-07-01/authorization/role_definitions.go new file mode 100644 index 000000000000..956e51b7a3ba --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/role_definitions.go @@ -0,0 +1,322 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// RoleDefinitionsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type RoleDefinitionsClient struct { + ManagementClient +} + +// NewRoleDefinitionsClient creates an instance of the RoleDefinitionsClient client. +func NewRoleDefinitionsClient(p pipeline.Pipeline) RoleDefinitionsClient { + return RoleDefinitionsClient{NewManagementClient(p)} +} + +// CreateOrUpdate creates or updates a role definition. +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. roleDefinition is the +// values for the role definition. +func (client RoleDefinitionsClient) CreateOrUpdate(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (*RoleDefinition, error) { + req, err := client.createOrUpdatePreparer(scope, roleDefinitionID, roleDefinition) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createOrUpdateResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// createOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RoleDefinitionsClient) createOrUpdatePreparer(scope string, roleDefinitionID string, roleDefinition RoleDefinition) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(roleDefinition) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createOrUpdateResponder handles the response to the CreateOrUpdate request. +func (client RoleDefinitionsClient) createOrUpdateResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Delete deletes a role definition. +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition to delete. +func (client RoleDefinitionsClient) Delete(ctx context.Context, scope string, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.deletePreparer(scope, roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// deletePreparer prepares the Delete request. +func (client RoleDefinitionsClient) deletePreparer(scope string, roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteResponder handles the response to the Delete request. +func (client RoleDefinitionsClient) deleteResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Get get role definition by name (GUID). +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. +func (client RoleDefinitionsClient) Get(ctx context.Context, scope string, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.getPreparer(scope, roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// getPreparer prepares the Get request. +func (client RoleDefinitionsClient) getPreparer(scope string, roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client RoleDefinitionsClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// GetByID gets a role definition by ID. +// +// roleDefinitionID is the fully qualified role definition ID. Use the format, +// /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level +// role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role +// definitions. +func (client RoleDefinitionsClient) GetByID(ctx context.Context, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.getByIDPreparer(roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// getByIDPreparer prepares the GetByID request. +func (client RoleDefinitionsClient) getByIDPreparer(roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleDefinitionId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getByIDResponder handles the response to the GetByID request. +func (client RoleDefinitionsClient) getByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List get all role definitions that are applicable at scope and above. +// +// scope is the scope of the role definition. filter is the filter to apply on the operation. Use atScopeAndBelow +// filter to search below the given scope as well. +func (client RoleDefinitionsClient) List(ctx context.Context, scope string, filter *string) (*RoleDefinitionListResult, error) { + req, err := client.listPreparer(scope, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinitionListResult), err +} + +// listPreparer prepares the List request. +func (client RoleDefinitionsClient) listPreparer(scope string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client RoleDefinitionsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinitionListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/roleassignments.go b/services/authorization/mgmt/2015-07-01/authorization/roleassignments.go deleted file mode 100644 index 45a7e6afac2b..000000000000 --- a/services/authorization/mgmt/2015-07-01/authorization/roleassignments.go +++ /dev/null @@ -1,843 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// RoleAssignmentsClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type RoleAssignmentsClient struct { - BaseClient -} - -// NewRoleAssignmentsClient creates an instance of the RoleAssignmentsClient client. -func NewRoleAssignmentsClient(subscriptionID string) RoleAssignmentsClient { - return NewRoleAssignmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoleAssignmentsClientWithBaseURI creates an instance of the RoleAssignmentsClient client. -func NewRoleAssignmentsClientWithBaseURI(baseURI string, subscriptionID string) RoleAssignmentsClient { - return RoleAssignmentsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create creates a role assignment. -// -// scope is the scope of the role assignment to create. The scope can be any REST resource instance. For example, use -// '/subscriptions/{subscription-id}/' for a subscription, -// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and -// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' -// for a resource. roleAssignmentName is the name of the role assignment to create. It can be any valid GUID. -// parameters is parameters for the role assignment. -func (client RoleAssignmentsClient) Create(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (result RoleAssignment, err error) { - req, err := client.CreatePreparer(ctx, scope, roleAssignmentName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Create", resp, "Failure responding to request") - } - - return -} - -// CreatePreparer prepares the Create request. -func (client RoleAssignmentsClient) CreatePreparer(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentName": autorest.Encode("path", roleAssignmentName), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsJSON(), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) CreateResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateByID creates a role assignment by ID. -// -// roleAssignmentID is the fully qualified ID of the role assignment, including the scope, resource name and resource -// type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: -// /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. -// parameters is parameters for the role assignment. -func (client RoleAssignmentsClient) CreateByID(ctx context.Context, roleAssignmentID string, parameters RoleAssignmentCreateParameters) (result RoleAssignment, err error) { - req, err := client.CreateByIDPreparer(ctx, roleAssignmentID, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "CreateByID", nil, "Failure preparing request") - return - } - - resp, err := client.CreateByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "CreateByID", resp, "Failure sending request") - return - } - - result, err = client.CreateByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "CreateByID", resp, "Failure responding to request") - } - - return -} - -// CreateByIDPreparer prepares the CreateByID request. -func (client RoleAssignmentsClient) CreateByIDPreparer(ctx context.Context, roleAssignmentID string, parameters RoleAssignmentCreateParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentId": roleAssignmentID, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsJSON(), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleAssignmentId}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateByIDSender sends the CreateByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) CreateByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateByIDResponder handles the response to the CreateByID request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) CreateByIDResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a role assignment. -// -// scope is the scope of the role assignment to delete. roleAssignmentName is the name of the role assignment to -// delete. -func (client RoleAssignmentsClient) Delete(ctx context.Context, scope string, roleAssignmentName string) (result RoleAssignment, err error) { - req, err := client.DeletePreparer(ctx, scope, roleAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoleAssignmentsClient) DeletePreparer(ctx context.Context, scope string, roleAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentName": autorest.Encode("path", roleAssignmentName), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) DeleteResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteByID deletes a role assignment. -// -// roleAssignmentID is the fully qualified ID of the role assignment, including the scope, resource name and resource -// type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: -// /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. -func (client RoleAssignmentsClient) DeleteByID(ctx context.Context, roleAssignmentID string) (result RoleAssignment, err error) { - req, err := client.DeleteByIDPreparer(ctx, roleAssignmentID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "DeleteByID", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "DeleteByID", resp, "Failure sending request") - return - } - - result, err = client.DeleteByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "DeleteByID", resp, "Failure responding to request") - } - - return -} - -// DeleteByIDPreparer prepares the DeleteByID request. -func (client RoleAssignmentsClient) DeleteByIDPreparer(ctx context.Context, roleAssignmentID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentId": roleAssignmentID, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleAssignmentId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteByIDSender sends the DeleteByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) DeleteByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteByIDResponder handles the response to the DeleteByID request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) DeleteByIDResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get get the specified role assignment. -// -// scope is the scope of the role assignment. roleAssignmentName is the name of the role assignment to get. -func (client RoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (result RoleAssignment, err error) { - req, err := client.GetPreparer(ctx, scope, roleAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoleAssignmentsClient) GetPreparer(ctx context.Context, scope string, roleAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentName": autorest.Encode("path", roleAssignmentName), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) GetResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetByID gets a role assignment by ID. -// -// roleAssignmentID is the fully qualified ID of the role assignment, including the scope, resource name and resource -// type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: -// /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. -func (client RoleAssignmentsClient) GetByID(ctx context.Context, roleAssignmentID string) (result RoleAssignment, err error) { - req, err := client.GetByIDPreparer(ctx, roleAssignmentID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "GetByID", nil, "Failure preparing request") - return - } - - resp, err := client.GetByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "GetByID", resp, "Failure sending request") - return - } - - result, err = client.GetByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "GetByID", resp, "Failure responding to request") - } - - return -} - -// GetByIDPreparer prepares the GetByID request. -func (client RoleAssignmentsClient) GetByIDPreparer(ctx context.Context, roleAssignmentID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentId": roleAssignmentID, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleAssignmentId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetByIDSender sends the GetByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) GetByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetByIDResponder handles the response to the GetByID request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) GetByIDResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all role assignments for the subscription. -// -// filter is the filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the -// scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified -// principal. -func (client RoleAssignmentsClient) List(ctx context.Context, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "List", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client RoleAssignmentsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListComplete(ctx context.Context, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.List(ctx, filter) - return -} - -// ListForResource gets role assignments for a resource. -// -// resourceGroupName is the name of the resource group. resourceProviderNamespace is the namespace of the resource -// provider. parentResourcePath is the parent resource identity. resourceType is the resource type of the resource. -// resourceName is the name of the resource to get role assignments for. filter is the filter to apply on the -// operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq -// {id} to return all role assignments at, above or below the scope for the specified principal. -func (client RoleAssignmentsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listForResourceNextResults - req, err := client.ListForResourcePreparer(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListForResourceSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResource", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResource", resp, "Failure responding to request") - } - - return -} - -// ListForResourcePreparer prepares the ListForResource request. -func (client RoleAssignmentsClient) ListForResourcePreparer(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "parentResourcePath": parentResourcePath, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "resourceName": autorest.Encode("path", resourceName), - "resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace), - "resourceType": resourceType, - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceSender sends the ListForResource request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListForResourceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceResponder handles the response to the ListForResource request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListForResourceResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listForResourceNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListForResourceComplete(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.ListForResource(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) - return -} - -// ListForResourceGroup gets role assignments for a resource group. -// -// resourceGroupName is the name of the resource group. filter is the filter to apply on the operation. Use -// $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return -// all role assignments at, above or below the scope for the specified principal. -func (client RoleAssignmentsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listForResourceGroupNextResults - req, err := client.ListForResourceGroupPreparer(ctx, resourceGroupName, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListForResourceGroupSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResourceGroup", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResourceGroup", resp, "Failure responding to request") - } - - return -} - -// ListForResourceGroupPreparer prepares the ListForResourceGroup request. -func (client RoleAssignmentsClient) ListForResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListForResourceGroupResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceGroupNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listForResourceGroupNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListForResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.ListForResourceGroup(ctx, resourceGroupName, filter) - return -} - -// ListForScope gets role assignments for a scope. -// -// scope is the scope of the role assignments. filter is the filter to apply on the operation. Use $filter=atScope() to -// return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments -// at, above or below the scope for the specified principal. -func (client RoleAssignmentsClient) ListForScope(ctx context.Context, scope string, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listForScopeNextResults - req, err := client.ListForScopePreparer(ctx, scope, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForScope", nil, "Failure preparing request") - return - } - - resp, err := client.ListForScopeSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForScope", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListForScopeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForScope", resp, "Failure responding to request") - } - - return -} - -// ListForScopePreparer prepares the ListForScope request. -func (client RoleAssignmentsClient) ListForScopePreparer(ctx context.Context, scope string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForScopeSender sends the ListForScope request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListForScopeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListForScopeResponder handles the response to the ListForScope request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListForScopeResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForScopeNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listForScopeNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForScopeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForScopeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForScopeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForScopeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForScopeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForScopeComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListForScopeComplete(ctx context.Context, scope string, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.ListForScope(ctx, scope, filter) - return -} diff --git a/services/authorization/mgmt/2015-07-01/authorization/roledefinitions.go b/services/authorization/mgmt/2015-07-01/authorization/roledefinitions.go deleted file mode 100644 index d143d5d7ae5a..000000000000 --- a/services/authorization/mgmt/2015-07-01/authorization/roledefinitions.go +++ /dev/null @@ -1,404 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// RoleDefinitionsClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type RoleDefinitionsClient struct { - BaseClient -} - -// NewRoleDefinitionsClient creates an instance of the RoleDefinitionsClient client. -func NewRoleDefinitionsClient(subscriptionID string) RoleDefinitionsClient { - return NewRoleDefinitionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoleDefinitionsClientWithBaseURI creates an instance of the RoleDefinitionsClient client. -func NewRoleDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) RoleDefinitionsClient { - return RoleDefinitionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a role definition. -// -// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. roleDefinition is the -// values for the role definition. -func (client RoleDefinitionsClient) CreateOrUpdate(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (result RoleDefinition, err error) { - req, err := client.CreateOrUpdatePreparer(ctx, scope, roleDefinitionID, roleDefinition) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RoleDefinitionsClient) CreateOrUpdatePreparer(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": autorest.Encode("path", roleDefinitionID), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsJSON(), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", pathParameters), - autorest.WithJSON(roleDefinition), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) CreateOrUpdateResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a role definition. -// -// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition to delete. -func (client RoleDefinitionsClient) Delete(ctx context.Context, scope string, roleDefinitionID string) (result RoleDefinition, err error) { - req, err := client.DeletePreparer(ctx, scope, roleDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoleDefinitionsClient) DeletePreparer(ctx context.Context, scope string, roleDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": autorest.Encode("path", roleDefinitionID), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) DeleteResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get get role definition by name (GUID). -// -// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. -func (client RoleDefinitionsClient) Get(ctx context.Context, scope string, roleDefinitionID string) (result RoleDefinition, err error) { - req, err := client.GetPreparer(ctx, scope, roleDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoleDefinitionsClient) GetPreparer(ctx context.Context, scope string, roleDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": autorest.Encode("path", roleDefinitionID), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) GetResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetByID gets a role definition by ID. -// -// roleDefinitionID is the fully qualified role definition ID. Use the format, -// /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level -// role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role -// definitions. -func (client RoleDefinitionsClient) GetByID(ctx context.Context, roleDefinitionID string) (result RoleDefinition, err error) { - req, err := client.GetByIDPreparer(ctx, roleDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "GetByID", nil, "Failure preparing request") - return - } - - resp, err := client.GetByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "GetByID", resp, "Failure sending request") - return - } - - result, err = client.GetByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "GetByID", resp, "Failure responding to request") - } - - return -} - -// GetByIDPreparer prepares the GetByID request. -func (client RoleDefinitionsClient) GetByIDPreparer(ctx context.Context, roleDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": roleDefinitionID, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleDefinitionId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetByIDSender sends the GetByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) GetByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetByIDResponder handles the response to the GetByID request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) GetByIDResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get all role definitions that are applicable at scope and above. -// -// scope is the scope of the role definition. filter is the filter to apply on the operation. Use atScopeAndBelow -// filter to search below the given scope as well. -func (client RoleDefinitionsClient) List(ctx context.Context, scope string, filter string) (result RoleDefinitionListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, scope, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "List", resp, "Failure sending request") - return - } - - result.rdlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client RoleDefinitionsClient) ListPreparer(ctx context.Context, scope string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) ListResponder(resp *http.Response) (result RoleDefinitionListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RoleDefinitionsClient) listNextResults(lastResults RoleDefinitionListResult) (result RoleDefinitionListResult, err error) { - req, err := lastResults.roleDefinitionListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleDefinitionsClient) ListComplete(ctx context.Context, scope string, filter string) (result RoleDefinitionListResultIterator, err error) { - result.page, err = client.List(ctx, scope, filter) - return -} diff --git a/services/authorization/mgmt/2015-07-01/authorization/validation.go b/services/authorization/mgmt/2015-07-01/authorization/validation.go new file mode 100644 index 000000000000..e44edeb29921 --- /dev/null +++ b/services/authorization/mgmt/2015-07-01/authorization/validation.go @@ -0,0 +1,381 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "fmt" + "github.com/Azure/azure-pipeline-go/pipeline" + "reflect" + "regexp" + "strings" +) + +// Constraint stores constraint name, target field name +// Rule and chain validations. +type constraint struct { + // Target field name for validation. + target string + + // Constraint name e.g. minLength, MaxLength, Pattern, etc. + name string + + // Rule for constraint e.g. greater than 10, less than 5 etc. + rule interface{} + + // Chain validations for struct type + chain []constraint +} + +// Validation stores parameter-wise validation. +type validation struct { + targetValue interface{} + constraints []constraint +} + +// Constraint list +const ( + empty = "Empty" + null = "Null" + readOnly = "ReadOnly" + pattern = "Pattern" + maxLength = "MaxLength" + minLength = "MinLength" + maxItems = "MaxItems" + minItems = "MinItems" + multipleOf = "MultipleOf" + uniqueItems = "UniqueItems" + inclusiveMaximum = "InclusiveMaximum" + exclusiveMaximum = "ExclusiveMaximum" + exclusiveMinimum = "ExclusiveMinimum" + inclusiveMinimum = "InclusiveMinimum" +) + +// Validate method validates constraints on parameter +// passed in validation array. +func validate(m []validation) error { + for _, item := range m { + v := reflect.ValueOf(item.targetValue) + for _, constraint := range item.constraints { + var err error + switch v.Kind() { + case reflect.Ptr: + err = validatePtr(v, constraint) + case reflect.String: + err = validateString(v, constraint) + case reflect.Struct: + err = validateStruct(v, constraint) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + err = validateInt(v, constraint) + case reflect.Float32, reflect.Float64: + err = validateFloat(v, constraint) + case reflect.Array, reflect.Slice, reflect.Map: + err = validateArrayMap(v, constraint) + default: + err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) + } + if err != nil { + return err + } + } + } + return nil +} + +func validateStruct(x reflect.Value, v constraint, name ...string) error { + //Get field name from target name which is in format a.b.c + s := strings.Split(v.target, ".") + f := x.FieldByName(s[len(s)-1]) + if isZero(f) { + return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.target)) + } + err := validate([]validation{ + { + targetValue: getInterfaceValue(f), + constraints: []constraint{v}, + }, + }) + return err +} + +func validatePtr(x reflect.Value, v constraint) error { + if v.name == readOnly { + if !x.IsNil() { + return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") + } + return nil + } + if x.IsNil() { + return checkNil(x, v) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x.Elem()), + constraints: v.chain, + }, + }) + } + return nil +} + +func validateInt(x reflect.Value, v constraint) error { + i := x.Int() + r, ok := v.rule.(int) + if !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + switch v.name { + case multipleOf: + if i%int64(r) != 0 { + return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) + } + case exclusiveMinimum: + if i <= int64(r) { + return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) + } + case exclusiveMaximum: + if i >= int64(r) { + return createError(x, v, fmt.Sprintf("value must be less than %v", r)) + } + case inclusiveMinimum: + if i < int64(r) { + return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) + } + case inclusiveMaximum: + if i > int64(r) { + return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) + } + default: + return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.name)) + } + return nil +} + +func validateFloat(x reflect.Value, v constraint) error { + f := x.Float() + r, ok := v.rule.(float64) + if !ok { + return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.name, v.rule)) + } + switch v.name { + case exclusiveMinimum: + if f <= r { + return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) + } + case exclusiveMaximum: + if f >= r { + return createError(x, v, fmt.Sprintf("value must be less than %v", r)) + } + case inclusiveMinimum: + if f < r { + return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) + } + case inclusiveMaximum: + if f > r { + return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) + } + default: + return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.name)) + } + return nil +} + +func validateString(x reflect.Value, v constraint) error { + s := x.String() + switch v.name { + case empty: + if len(s) == 0 { + return checkEmpty(x, v) + } + case pattern: + reg, err := regexp.Compile(v.rule.(string)) + if err != nil { + return createError(x, v, err.Error()) + } + if !reg.MatchString(s) { + return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.rule)) + } + case maxLength: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + if len(s) > v.rule.(int) { + return createError(x, v, fmt.Sprintf("value length must be less than %v", v.rule)) + } + case minLength: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + if len(s) < v.rule.(int) { + return createError(x, v, fmt.Sprintf("value length must be greater than %v", v.rule)) + } + case readOnly: + if len(s) > 0 { + return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") + } + default: + return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.name)) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x), + constraints: v.chain, + }, + }) + } + return nil +} + +func validateArrayMap(x reflect.Value, v constraint) error { + switch v.name { + case null: + if x.IsNil() { + return checkNil(x, v) + } + case empty: + if x.IsNil() || x.Len() == 0 { + return checkEmpty(x, v) + } + case maxItems: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.name, v.rule)) + } + if x.Len() > v.rule.(int) { + return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.rule, x.Len())) + } + case minItems: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.name, v.rule)) + } + if x.Len() < v.rule.(int) { + return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.rule, x.Len())) + } + case uniqueItems: + if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { + if !checkForUniqueInArray(x) { + return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.target, x)) + } + } else if x.Kind() == reflect.Map { + if !checkForUniqueInMap(x) { + return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.target, x)) + } + } else { + return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.name, x.Kind())) + } + case readOnly: + if x.Len() != 0 { + return createError(x, v, "readonly parameter; must send as nil or empty in request") + } + case pattern: + reg, err := regexp.Compile(v.rule.(string)) + if err != nil { + return createError(x, v, err.Error()) + } + keys := x.MapKeys() + for _, k := range keys { + if !reg.MatchString(k.String()) { + return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.rule)) + } + } + default: + return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.name)) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x), + constraints: v.chain, + }, + }) + } + return nil +} + +func checkNil(x reflect.Value, v constraint) error { + if _, ok := v.rule.(bool); !ok { + return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.name, v.rule)) + } + if v.rule.(bool) { + return createError(x, v, "value can not be null; required parameter") + } + return nil +} + +func checkEmpty(x reflect.Value, v constraint) error { + if _, ok := v.rule.(bool); !ok { + return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.name, v.rule)) + } + if v.rule.(bool) { + return createError(x, v, "value can not be null or empty; required parameter") + } + return nil +} + +func checkForUniqueInArray(x reflect.Value) bool { + if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { + return false + } + arrOfInterface := make([]interface{}, x.Len()) + for i := 0; i < x.Len(); i++ { + arrOfInterface[i] = x.Index(i).Interface() + } + m := make(map[interface{}]bool) + for _, val := range arrOfInterface { + if m[val] { + return false + } + m[val] = true + } + return true +} + +func checkForUniqueInMap(x reflect.Value) bool { + if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { + return false + } + mapOfInterface := make(map[interface{}]interface{}, x.Len()) + keys := x.MapKeys() + for _, k := range keys { + mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() + } + m := make(map[interface{}]bool) + for _, val := range mapOfInterface { + if m[val] { + return false + } + m[val] = true + } + return true +} + +func getInterfaceValue(x reflect.Value) interface{} { + if x.Kind() == reflect.Invalid { + return nil + } + return x.Interface() +} + +func isZero(x interface{}) bool { + return x == reflect.Zero(reflect.TypeOf(x)).Interface() +} + +func createError(x reflect.Value, v constraint, message string) error { + return pipeline.NewError(nil, fmt.Sprintf("validation failed: parameter=%s constraint=%s value=%#v details: %s", + v.target, v.name, getInterfaceValue(x), message)) +} diff --git a/services/authorization/mgmt/2015-07-01/authorization/version.go b/services/authorization/mgmt/2015-07-01/authorization/version.go index ea3d2316383a..6e82bbcb2ac1 100644 --- a/services/authorization/mgmt/2015-07-01/authorization/version.go +++ b/services/authorization/mgmt/2015-07-01/authorization/version.go @@ -19,10 +19,10 @@ package authorization // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/v12.1.1-beta services" + return "Azure-SDK-For-Go/v12.2.1-beta arm-authorization/2015-07-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return "v12.1.1-beta" + return "v12.2.1-beta" } diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/classic_administrators.go b/services/authorization/mgmt/2017-10-01-preview/authorization/classic_administrators.go new file mode 100644 index 000000000000..063e8e6e9324 --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/classic_administrators.go @@ -0,0 +1,90 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// ClassicAdministratorsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type ClassicAdministratorsClient struct { + ManagementClient +} + +// NewClassicAdministratorsClient creates an instance of the ClassicAdministratorsClient client. +func NewClassicAdministratorsClient(p pipeline.Pipeline) ClassicAdministratorsClient { + return ClassicAdministratorsClient{NewManagementClient(p)} +} + +// List gets service administrator, account administrator, and co-administrators for the subscription. +func (client ClassicAdministratorsClient) List(ctx context.Context) (*ClassicAdministratorListResult, error) { + req, err := client.listPreparer() + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ClassicAdministratorListResult), err +} + +// listPreparer prepares the List request. +func (client ClassicAdministratorsClient) listPreparer() (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client ClassicAdministratorsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ClassicAdministratorListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/classicadministrators.go b/services/authorization/mgmt/2017-10-01-preview/authorization/classicadministrators.go deleted file mode 100644 index 8527db7aafeb..000000000000 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/classicadministrators.go +++ /dev/null @@ -1,133 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// ClassicAdministratorsClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type ClassicAdministratorsClient struct { - BaseClient -} - -// NewClassicAdministratorsClient creates an instance of the ClassicAdministratorsClient client. -func NewClassicAdministratorsClient(subscriptionID string) ClassicAdministratorsClient { - return NewClassicAdministratorsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewClassicAdministratorsClientWithBaseURI creates an instance of the ClassicAdministratorsClient client. -func NewClassicAdministratorsClientWithBaseURI(baseURI string, subscriptionID string) ClassicAdministratorsClient { - return ClassicAdministratorsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets service administrator, account administrator, and co-administrators for the subscription. -func (client ClassicAdministratorsClient) List(ctx context.Context) (result ClassicAdministratorListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.calr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "List", resp, "Failure sending request") - return - } - - result.calr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ClassicAdministratorsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ClassicAdministratorsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ClassicAdministratorsClient) ListResponder(resp *http.Response) (result ClassicAdministratorListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ClassicAdministratorsClient) listNextResults(lastResults ClassicAdministratorListResult) (result ClassicAdministratorListResult, err error) { - req, err := lastResults.classicAdministratorListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ClassicAdministratorsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ClassicAdministratorsClient) ListComplete(ctx context.Context) (result ClassicAdministratorListResultIterator, err error) { - result.page, err = client.List(ctx) - return -} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/client.go b/services/authorization/mgmt/2017-10-01-preview/authorization/client.go index 6b6f6de95ef0..ec71e4b27367 100644 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/client.go +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/client.go @@ -1,9 +1,3 @@ -// Package authorization implements the Azure ARM Authorization service API version . -// -// Role based access control provides you a way to apply granular level policy administration down to individual -// resources or resource groups. These operations enable you to manage role definitions and role assignments. A role -// definition describes the set of actions that can be performed on resources. A role assignment grants access to Azure -// Active Directory users. package authorization // Copyright (c) Microsoft and contributors. All rights reserved. @@ -24,31 +18,46 @@ package authorization // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( - "github.com/Azure/go-autorest/autorest" + "github.com/Azure/azure-pipeline-go/pipeline" + "net/url" ) const ( - // DefaultBaseURI is the default URI used for the service Authorization - DefaultBaseURI = "https://management.azure.com" + // ServiceVersion specifies the version of the operations used in this package. + ServiceVersion = "" + // DefaultBaseURL is the default URL used for the service Authorization + DefaultBaseURL = "https://management.azure.com" ) -// BaseClient is the base client for Authorization. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string +// ManagementClient is the base client for Authorization. +type ManagementClient struct { + url url.URL + p pipeline.Pipeline } -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) +// NewManagementClient creates an instance of the ManagementClient client. +func NewManagementClient(p pipeline.Pipeline) ManagementClient { + u, err := url.Parse(DefaultBaseURL) + if err != nil { + panic(err) + } + return NewManagementClientWithURL(*u, p) } -// NewWithBaseURI creates an instance of the BaseClient client. -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, +// NewManagementClientWithURL creates an instance of the ManagementClient client. +func NewManagementClientWithURL(url url.URL, p pipeline.Pipeline) ManagementClient { + return ManagementClient{ + url: url, + p: p, } } + +// URL returns a copy of the URL for this client. +func (mc ManagementClient) URL() url.URL { + return mc.url +} + +// Pipeline returns the pipeline for this client. +func (mc ManagementClient) Pipeline() pipeline.Pipeline { + return mc.p +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/models.go b/services/authorization/mgmt/2017-10-01-preview/authorization/models.go index 77cbd6986988..67eb4a94856a 100644 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/models.go +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/models.go @@ -18,13 +18,31 @@ package authorization // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/to" "net/http" ) -// ClassicAdministrator classic Administrators +// Marker represents an opaque value used in paged responses. +type Marker struct { + val *string +} + +// NotDone returns true if the list enumeration should be started or is not yet complete. Specifically, NotDone returns true +// for a just-initialized (zero value) Marker indicating that you should make an initial request to get a result portion from +// the service. NotDone also returns true whenever the service returns an interim result portion. NotDone returns false only +// after the service has returned the final result portion. +func (m Marker) NotDone() bool { + return m.val == nil || *m.val != "" +} + +// UnmarshalXML implements the xml.Unmarshaler interface for Marker. +func (m *Marker) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var out string + err := d.DecodeElement(&out, &start) + m.val = &out + return err +} + +// ClassicAdministrator - Classic Administrators type ClassicAdministrator struct { // ID - The ID of the administrator. ID *string `json:"id,omitempty"` @@ -32,165 +50,35 @@ type ClassicAdministrator struct { Name *string `json:"name,omitempty"` // Type - The type of the administrator. Type *string `json:"type,omitempty"` - // ClassicAdministratorProperties - Properties for the classic administrator. + // Properties - Properties for the classic administrator. *ClassicAdministratorProperties `json:"properties,omitempty"` } -// UnmarshalJSON is the custom unmarshaler for ClassicAdministrator struct. -func (ca *ClassicAdministrator) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - var v *json.RawMessage - - v = m["id"] - if v != nil { - var ID string - err = json.Unmarshal(*m["id"], &ID) - if err != nil { - return err - } - ca.ID = &ID - } - - v = m["name"] - if v != nil { - var name string - err = json.Unmarshal(*m["name"], &name) - if err != nil { - return err - } - ca.Name = &name - } - - v = m["type"] - if v != nil { - var typeVar string - err = json.Unmarshal(*m["type"], &typeVar) - if err != nil { - return err - } - ca.Type = &typeVar - } - - v = m["properties"] - if v != nil { - var properties ClassicAdministratorProperties - err = json.Unmarshal(*m["properties"], &properties) - if err != nil { - return err - } - ca.ClassicAdministratorProperties = &properties - } - - return nil -} - -// ClassicAdministratorListResult classicAdministrator list result information. +// ClassicAdministratorListResult - ClassicAdministrator list result information. type ClassicAdministratorListResult struct { - autorest.Response `json:"-"` + rawResponse *http.Response // Value - An array of administrators. - Value *[]ClassicAdministrator `json:"value,omitempty"` + Value []ClassicAdministrator `json:"value,omitempty"` // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ClassicAdministratorListResultIterator provides access to a complete listing of ClassicAdministrator values. -type ClassicAdministratorListResultIterator struct { - i int - page ClassicAdministratorListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ClassicAdministratorListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ClassicAdministratorListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ClassicAdministratorListResultIterator) Response() ClassicAdministratorListResult { - return iter.page.Response() + NextLink Marker `json:"NextLink"` } -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ClassicAdministratorListResultIterator) Value() ClassicAdministrator { - if !iter.page.NotDone() { - return ClassicAdministrator{} - } - return iter.page.Values()[iter.i] +// Response returns the raw HTTP response object. +func (calr ClassicAdministratorListResult) Response() *http.Response { + return calr.rawResponse } -// IsEmpty returns true if the ListResult contains no values. -func (calr ClassicAdministratorListResult) IsEmpty() bool { - return calr.Value == nil || len(*calr.Value) == 0 +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (calr ClassicAdministratorListResult) StatusCode() int { + return calr.rawResponse.StatusCode } -// classicAdministratorListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (calr ClassicAdministratorListResult) classicAdministratorListResultPreparer() (*http.Request, error) { - if calr.NextLink == nil || len(to.String(calr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(calr.NextLink))) +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (calr ClassicAdministratorListResult) Status() string { + return calr.rawResponse.Status } -// ClassicAdministratorListResultPage contains a page of ClassicAdministrator values. -type ClassicAdministratorListResultPage struct { - fn func(ClassicAdministratorListResult) (ClassicAdministratorListResult, error) - calr ClassicAdministratorListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ClassicAdministratorListResultPage) Next() error { - next, err := page.fn(page.calr) - if err != nil { - return err - } - page.calr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ClassicAdministratorListResultPage) NotDone() bool { - return !page.calr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ClassicAdministratorListResultPage) Response() ClassicAdministratorListResult { - return page.calr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ClassicAdministratorListResultPage) Values() []ClassicAdministrator { - if page.calr.IsEmpty() { - return nil - } - return *page.calr.Value -} - -// ClassicAdministratorProperties classic Administrator properties. +// ClassicAdministratorProperties - Classic Administrator properties. type ClassicAdministratorProperties struct { // EmailAddress - The email address of the administrator. EmailAddress *string `json:"emailAddress,omitempty"` @@ -198,117 +86,39 @@ type ClassicAdministratorProperties struct { Role *string `json:"role,omitempty"` } -// Permission role definition permissions. +// Permission - Role definition permissions. type Permission struct { // Actions - Allowed actions. - Actions *[]string `json:"actions,omitempty"` + Actions []string `json:"actions,omitempty"` // NotActions - Denied actions. - NotActions *[]string `json:"notActions,omitempty"` + NotActions []string `json:"notActions,omitempty"` } -// PermissionGetResult permissions information. +// PermissionGetResult - Permissions information. type PermissionGetResult struct { - autorest.Response `json:"-"` + rawResponse *http.Response // Value - An array of permissions. - Value *[]Permission `json:"value,omitempty"` + Value []Permission `json:"value,omitempty"` // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PermissionGetResultIterator provides access to a complete listing of Permission values. -type PermissionGetResultIterator struct { - i int - page PermissionGetResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PermissionGetResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PermissionGetResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PermissionGetResultIterator) Response() PermissionGetResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PermissionGetResultIterator) Value() Permission { - if !iter.page.NotDone() { - return Permission{} - } - return iter.page.Values()[iter.i] + NextLink Marker `json:"NextLink"` } -// IsEmpty returns true if the ListResult contains no values. -func (pgr PermissionGetResult) IsEmpty() bool { - return pgr.Value == nil || len(*pgr.Value) == 0 +// Response returns the raw HTTP response object. +func (pgr PermissionGetResult) Response() *http.Response { + return pgr.rawResponse } -// permissionGetResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pgr PermissionGetResult) permissionGetResultPreparer() (*http.Request, error) { - if pgr.NextLink == nil || len(to.String(pgr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pgr.NextLink))) +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pgr PermissionGetResult) StatusCode() int { + return pgr.rawResponse.StatusCode } -// PermissionGetResultPage contains a page of Permission values. -type PermissionGetResultPage struct { - fn func(PermissionGetResult) (PermissionGetResult, error) - pgr PermissionGetResult +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pgr PermissionGetResult) Status() string { + return pgr.rawResponse.Status } -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PermissionGetResultPage) Next() error { - next, err := page.fn(page.pgr) - if err != nil { - return err - } - page.pgr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PermissionGetResultPage) NotDone() bool { - return !page.pgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PermissionGetResultPage) Response() PermissionGetResult { - return page.pgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PermissionGetResultPage) Values() []Permission { - if page.pgr.IsEmpty() { - return nil - } - return *page.pgr.Value -} - -// ProviderOperation operation +// ProviderOperation - Operation type ProviderOperation struct { // Name - The operation name. Name *string `json:"name,omitempty"` @@ -319,12 +129,12 @@ type ProviderOperation struct { // Origin - The operation origin. Origin *string `json:"origin,omitempty"` // Properties - The operation properties. - Properties *map[string]interface{} `json:"properties,omitempty"` + Properties map[string]interface{} `json:"properties,omitempty"` } -// ProviderOperationsMetadata provider Operations metadata +// ProviderOperationsMetadata - Provider Operations metadata type ProviderOperationsMetadata struct { - autorest.Response `json:"-"` + rawResponse *http.Response // ID - The provider id. ID *string `json:"id,omitempty"` // Name - The provider name. @@ -334,218 +144,95 @@ type ProviderOperationsMetadata struct { // DisplayName - The provider display name. DisplayName *string `json:"displayName,omitempty"` // ResourceTypes - The provider resource types - ResourceTypes *[]ResourceType `json:"resourceTypes,omitempty"` + ResourceTypes []ResourceType `json:"resourceTypes,omitempty"` // Operations - The provider operations. - Operations *[]ProviderOperation `json:"operations,omitempty"` -} - -// ProviderOperationsMetadataListResult provider operations metadata list -type ProviderOperationsMetadataListResult struct { - autorest.Response `json:"-"` - // Value - The list of providers. - Value *[]ProviderOperationsMetadata `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ProviderOperationsMetadataListResultIterator provides access to a complete listing of ProviderOperationsMetadata -// values. -type ProviderOperationsMetadataListResultIterator struct { - i int - page ProviderOperationsMetadataListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ProviderOperationsMetadataListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ProviderOperationsMetadataListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ProviderOperationsMetadataListResultIterator) Response() ProviderOperationsMetadataListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ProviderOperationsMetadataListResultIterator) Value() ProviderOperationsMetadata { - if !iter.page.NotDone() { - return ProviderOperationsMetadata{} - } - return iter.page.Values()[iter.i] + Operations []ProviderOperation `json:"operations,omitempty"` } -// IsEmpty returns true if the ListResult contains no values. -func (pomlr ProviderOperationsMetadataListResult) IsEmpty() bool { - return pomlr.Value == nil || len(*pomlr.Value) == 0 +// Response returns the raw HTTP response object. +func (pom ProviderOperationsMetadata) Response() *http.Response { + return pom.rawResponse } -// providerOperationsMetadataListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pomlr ProviderOperationsMetadataListResult) providerOperationsMetadataListResultPreparer() (*http.Request, error) { - if pomlr.NextLink == nil || len(to.String(pomlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pomlr.NextLink))) +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pom ProviderOperationsMetadata) StatusCode() int { + return pom.rawResponse.StatusCode } -// ProviderOperationsMetadataListResultPage contains a page of ProviderOperationsMetadata values. -type ProviderOperationsMetadataListResultPage struct { - fn func(ProviderOperationsMetadataListResult) (ProviderOperationsMetadataListResult, error) - pomlr ProviderOperationsMetadataListResult +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pom ProviderOperationsMetadata) Status() string { + return pom.rawResponse.Status } -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ProviderOperationsMetadataListResultPage) Next() error { - next, err := page.fn(page.pomlr) - if err != nil { - return err - } - page.pomlr = next - return nil +// ProviderOperationsMetadataListResult - Provider operations metadata list +type ProviderOperationsMetadataListResult struct { + rawResponse *http.Response + // Value - The list of providers. + Value []ProviderOperationsMetadata `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` } -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ProviderOperationsMetadataListResultPage) NotDone() bool { - return !page.pomlr.IsEmpty() +// Response returns the raw HTTP response object. +func (pomlr ProviderOperationsMetadataListResult) Response() *http.Response { + return pomlr.rawResponse } -// Response returns the raw server response from the last page request. -func (page ProviderOperationsMetadataListResultPage) Response() ProviderOperationsMetadataListResult { - return page.pomlr +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pomlr ProviderOperationsMetadataListResult) StatusCode() int { + return pomlr.rawResponse.StatusCode } -// Values returns the slice of values for the current page or nil if there are no values. -func (page ProviderOperationsMetadataListResultPage) Values() []ProviderOperationsMetadata { - if page.pomlr.IsEmpty() { - return nil - } - return *page.pomlr.Value +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pomlr ProviderOperationsMetadataListResult) Status() string { + return pomlr.rawResponse.Status } -// ResourceType resource Type +// ResourceType - Resource Type type ResourceType struct { // Name - The resource type name. Name *string `json:"name,omitempty"` // DisplayName - The resource type display name. DisplayName *string `json:"displayName,omitempty"` // Operations - The resource type operations. - Operations *[]ProviderOperation `json:"operations,omitempty"` + Operations []ProviderOperation `json:"operations,omitempty"` } -// RoleAssignment role Assignments +// RoleAssignment - Role Assignments type RoleAssignment struct { - autorest.Response `json:"-"` + rawResponse *http.Response // ID - The role assignment ID. ID *string `json:"id,omitempty"` // Name - The role assignment name. Name *string `json:"name,omitempty"` // Type - The role assignment type. Type *string `json:"type,omitempty"` - // RoleAssignmentPropertiesWithScope - Role assignment properties. + // Properties - Role assignment properties. *RoleAssignmentPropertiesWithScope `json:"properties,omitempty"` } -// UnmarshalJSON is the custom unmarshaler for RoleAssignment struct. -func (ra *RoleAssignment) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - var v *json.RawMessage - - v = m["id"] - if v != nil { - var ID string - err = json.Unmarshal(*m["id"], &ID) - if err != nil { - return err - } - ra.ID = &ID - } - - v = m["name"] - if v != nil { - var name string - err = json.Unmarshal(*m["name"], &name) - if err != nil { - return err - } - ra.Name = &name - } - - v = m["type"] - if v != nil { - var typeVar string - err = json.Unmarshal(*m["type"], &typeVar) - if err != nil { - return err - } - ra.Type = &typeVar - } - - v = m["properties"] - if v != nil { - var properties RoleAssignmentPropertiesWithScope - err = json.Unmarshal(*m["properties"], &properties) - if err != nil { - return err - } - ra.RoleAssignmentPropertiesWithScope = &properties - } - - return nil -} - -// RoleAssignmentCreateParameters role assignment create parameters. -type RoleAssignmentCreateParameters struct { - // RoleAssignmentProperties - Role assignment properties. - *RoleAssignmentProperties `json:"properties,omitempty"` +// Response returns the raw HTTP response object. +func (ra RoleAssignment) Response() *http.Response { + return ra.rawResponse } -// UnmarshalJSON is the custom unmarshaler for RoleAssignmentCreateParameters struct. -func (racp *RoleAssignmentCreateParameters) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - var v *json.RawMessage +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (ra RoleAssignment) StatusCode() int { + return ra.rawResponse.StatusCode +} - v = m["properties"] - if v != nil { - var properties RoleAssignmentProperties - err = json.Unmarshal(*m["properties"], &properties) - if err != nil { - return err - } - racp.RoleAssignmentProperties = &properties - } +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (ra RoleAssignment) Status() string { + return ra.rawResponse.Status +} - return nil +// RoleAssignmentCreateParameters - Role assignment create parameters. +type RoleAssignmentCreateParameters struct { + // Properties - Role assignment properties. + *RoleAssignmentProperties `json:"properties,omitempty"` } -// RoleAssignmentFilter role Assignments filter +// RoleAssignmentFilter - Role Assignments filter type RoleAssignmentFilter struct { // PrincipalID - Returns role assignment of the specific principal. PrincipalID *string `json:"principalId,omitempty"` @@ -553,109 +240,31 @@ type RoleAssignmentFilter struct { CanDelegate *bool `json:"canDelegate,omitempty"` } -// RoleAssignmentListResult role assignment list operation result. +// RoleAssignmentListResult - Role assignment list operation result. type RoleAssignmentListResult struct { - autorest.Response `json:"-"` + rawResponse *http.Response // Value - Role assignment list. - Value *[]RoleAssignment `json:"value,omitempty"` + Value []RoleAssignment `json:"value,omitempty"` // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RoleAssignmentListResultIterator provides access to a complete listing of RoleAssignment values. -type RoleAssignmentListResultIterator struct { - i int - page RoleAssignmentListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RoleAssignmentListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RoleAssignmentListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RoleAssignmentListResultIterator) Response() RoleAssignmentListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RoleAssignmentListResultIterator) Value() RoleAssignment { - if !iter.page.NotDone() { - return RoleAssignment{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (ralr RoleAssignmentListResult) IsEmpty() bool { - return ralr.Value == nil || len(*ralr.Value) == 0 -} - -// roleAssignmentListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ralr RoleAssignmentListResult) roleAssignmentListResultPreparer() (*http.Request, error) { - if ralr.NextLink == nil || len(to.String(ralr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ralr.NextLink))) -} - -// RoleAssignmentListResultPage contains a page of RoleAssignment values. -type RoleAssignmentListResultPage struct { - fn func(RoleAssignmentListResult) (RoleAssignmentListResult, error) - ralr RoleAssignmentListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RoleAssignmentListResultPage) Next() error { - next, err := page.fn(page.ralr) - if err != nil { - return err - } - page.ralr = next - return nil + NextLink Marker `json:"NextLink"` } -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RoleAssignmentListResultPage) NotDone() bool { - return !page.ralr.IsEmpty() +// Response returns the raw HTTP response object. +func (ralr RoleAssignmentListResult) Response() *http.Response { + return ralr.rawResponse } -// Response returns the raw server response from the last page request. -func (page RoleAssignmentListResultPage) Response() RoleAssignmentListResult { - return page.ralr +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (ralr RoleAssignmentListResult) StatusCode() int { + return ralr.rawResponse.StatusCode } -// Values returns the slice of values for the current page or nil if there are no values. -func (page RoleAssignmentListResultPage) Values() []RoleAssignment { - if page.ralr.IsEmpty() { - return nil - } - return *page.ralr.Value +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (ralr RoleAssignmentListResult) Status() string { + return ralr.rawResponse.Status } -// RoleAssignmentProperties role assignment properties. +// RoleAssignmentProperties - Role assignment properties. type RoleAssignmentProperties struct { // RoleDefinitionID - The role definition ID used in the role assignment. RoleDefinitionID *string `json:"roleDefinitionId,omitempty"` @@ -665,7 +274,7 @@ type RoleAssignmentProperties struct { CanDelegate *bool `json:"canDelegate,omitempty"` } -// RoleAssignmentPropertiesWithScope role assignment properties with scope. +// RoleAssignmentPropertiesWithScope - Role assignment properties with scope. type RoleAssignmentPropertiesWithScope struct { // Scope - The role assignment scope. Scope *string `json:"scope,omitempty"` @@ -677,180 +286,65 @@ type RoleAssignmentPropertiesWithScope struct { CanDelegate *bool `json:"canDelegate,omitempty"` } -// RoleDefinition role definition. +// RoleDefinition - Role definition. type RoleDefinition struct { - autorest.Response `json:"-"` + rawResponse *http.Response // ID - The role definition ID. ID *string `json:"id,omitempty"` // Name - The role definition name. Name *string `json:"name,omitempty"` // Type - The role definition type. Type *string `json:"type,omitempty"` - // RoleDefinitionProperties - Role definition properties. + // Properties - Role definition properties. *RoleDefinitionProperties `json:"properties,omitempty"` } -// UnmarshalJSON is the custom unmarshaler for RoleDefinition struct. -func (rd *RoleDefinition) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - var v *json.RawMessage - - v = m["id"] - if v != nil { - var ID string - err = json.Unmarshal(*m["id"], &ID) - if err != nil { - return err - } - rd.ID = &ID - } - - v = m["name"] - if v != nil { - var name string - err = json.Unmarshal(*m["name"], &name) - if err != nil { - return err - } - rd.Name = &name - } - - v = m["type"] - if v != nil { - var typeVar string - err = json.Unmarshal(*m["type"], &typeVar) - if err != nil { - return err - } - rd.Type = &typeVar - } - - v = m["properties"] - if v != nil { - var properties RoleDefinitionProperties - err = json.Unmarshal(*m["properties"], &properties) - if err != nil { - return err - } - rd.RoleDefinitionProperties = &properties - } - - return nil -} - -// RoleDefinitionFilter role Definitions filter -type RoleDefinitionFilter struct { - // RoleName - Returns role definition with the specific name. - RoleName *string `json:"roleName,omitempty"` -} - -// RoleDefinitionListResult role definition list operation result. -type RoleDefinitionListResult struct { - autorest.Response `json:"-"` - // Value - Role definition list. - Value *[]RoleDefinition `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` +// Response returns the raw HTTP response object. +func (rd RoleDefinition) Response() *http.Response { + return rd.rawResponse } -// RoleDefinitionListResultIterator provides access to a complete listing of RoleDefinition values. -type RoleDefinitionListResultIterator struct { - i int - page RoleDefinitionListResultPage +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (rd RoleDefinition) StatusCode() int { + return rd.rawResponse.StatusCode } -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RoleDefinitionListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (rd RoleDefinition) Status() string { + return rd.rawResponse.Status } -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RoleDefinitionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RoleDefinitionListResultIterator) Response() RoleDefinitionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RoleDefinitionListResultIterator) Value() RoleDefinition { - if !iter.page.NotDone() { - return RoleDefinition{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (rdlr RoleDefinitionListResult) IsEmpty() bool { - return rdlr.Value == nil || len(*rdlr.Value) == 0 -} - -// roleDefinitionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rdlr RoleDefinitionListResult) roleDefinitionListResultPreparer() (*http.Request, error) { - if rdlr.NextLink == nil || len(to.String(rdlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rdlr.NextLink))) -} - -// RoleDefinitionListResultPage contains a page of RoleDefinition values. -type RoleDefinitionListResultPage struct { - fn func(RoleDefinitionListResult) (RoleDefinitionListResult, error) - rdlr RoleDefinitionListResult +// RoleDefinitionFilter - Role Definitions filter +type RoleDefinitionFilter struct { + // RoleName - Returns role definition with the specific name. + RoleName *string `json:"roleName,omitempty"` } -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RoleDefinitionListResultPage) Next() error { - next, err := page.fn(page.rdlr) - if err != nil { - return err - } - page.rdlr = next - return nil +// RoleDefinitionListResult - Role definition list operation result. +type RoleDefinitionListResult struct { + rawResponse *http.Response + // Value - Role definition list. + Value []RoleDefinition `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` } -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RoleDefinitionListResultPage) NotDone() bool { - return !page.rdlr.IsEmpty() +// Response returns the raw HTTP response object. +func (rdlr RoleDefinitionListResult) Response() *http.Response { + return rdlr.rawResponse } -// Response returns the raw server response from the last page request. -func (page RoleDefinitionListResultPage) Response() RoleDefinitionListResult { - return page.rdlr +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (rdlr RoleDefinitionListResult) StatusCode() int { + return rdlr.rawResponse.StatusCode } -// Values returns the slice of values for the current page or nil if there are no values. -func (page RoleDefinitionListResultPage) Values() []RoleDefinition { - if page.rdlr.IsEmpty() { - return nil - } - return *page.rdlr.Value +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (rdlr RoleDefinitionListResult) Status() string { + return rdlr.rawResponse.Status } -// RoleDefinitionProperties role definition properties. +// RoleDefinitionProperties - Role definition properties. type RoleDefinitionProperties struct { // RoleName - The role name. RoleName *string `json:"roleName,omitempty"` @@ -859,7 +353,7 @@ type RoleDefinitionProperties struct { // RoleType - The role type. RoleType *string `json:"type,omitempty"` // Permissions - Role definition permissions. - Permissions *[]Permission `json:"permissions,omitempty"` + Permissions []Permission `json:"permissions,omitempty"` // AssignableScopes - Role definition assignable scopes. - AssignableScopes *[]string `json:"assignableScopes,omitempty"` + AssignableScopes []string `json:"assignableScopes,omitempty"` } diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/permissions.go b/services/authorization/mgmt/2017-10-01-preview/authorization/permissions.go index 935be1f5a688..9fb0a80e1a26 100644 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/permissions.go +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/permissions.go @@ -19,8 +19,9 @@ package authorization import ( "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" "net/http" ) @@ -29,17 +30,12 @@ import ( // assignments. A role definition describes the set of actions that can be performed on resources. A role assignment // grants access to Azure Active Directory users. type PermissionsClient struct { - BaseClient + ManagementClient } // NewPermissionsClient creates an instance of the PermissionsClient client. -func NewPermissionsClient(subscriptionID string) PermissionsClient { - return NewPermissionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPermissionsClientWithBaseURI creates an instance of the PermissionsClient client. -func NewPermissionsClientWithBaseURI(baseURI string, subscriptionID string) PermissionsClient { - return PermissionsClient{NewWithBaseURI(baseURI, subscriptionID)} +func NewPermissionsClient(p pipeline.Pipeline) PermissionsClient { + return PermissionsClient{NewManagementClient(p)} } // ListForResource gets all permissions the caller has for a resource. @@ -48,189 +44,105 @@ func NewPermissionsClientWithBaseURI(baseURI string, subscriptionID string) Perm // resourceProviderNamespace is the namespace of the resource provider. parentResourcePath is the parent resource // identity. resourceType is the resource type of the resource. resourceName is the name of the resource to get the // permissions for. -func (client PermissionsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result PermissionGetResultPage, err error) { - result.fn = client.listForResourceNextResults - req, err := client.ListForResourcePreparer(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName) +func (client PermissionsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (*PermissionGetResult, error) { + req, err := client.listForResourcePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResource", nil, "Failure preparing request") - return + return nil, err } - - resp, err := client.ListForResourceSender(req) + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceResponder}, req) if err != nil { - result.pgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResource", resp, "Failure sending request") - return + return nil, err } + return resp.(*PermissionGetResult), err +} - result.pgr, err = client.ListForResourceResponder(resp) +// listForResourcePreparer prepares the ListForResource request. +func (client PermissionsClient) listForResourcePreparer(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions" + req, err := pipeline.NewRequest("GET", u, nil) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResource", resp, "Failure responding to request") + return req, pipeline.NewError(err, "failed to create request") } - - return + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil } -// ListForResourcePreparer prepares the ListForResource request. -func (client PermissionsClient) ListForResourcePreparer(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "parentResourcePath": parentResourcePath, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "resourceName": autorest.Encode("path", resourceName), - "resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace), - "resourceType": resourceType, - "subscriptionId": autorest.Encode("path", client.SubscriptionID), +// listForResourceResponder handles the response to the ListForResource request. +func (client PermissionsClient) listForResourceResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceSender sends the ListForResource request. The method will close the -// http.Response Body if it receives an error. -func (client PermissionsClient) ListForResourceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceResponder handles the response to the ListForResource request. The method always -// closes the http.Response Body. -func (client PermissionsClient) ListForResourceResponder(resp *http.Response) (result PermissionGetResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceNextResults retrieves the next set of results, if any. -func (client PermissionsClient) listForResourceNextResults(lastResults PermissionGetResult) (result PermissionGetResult, err error) { - req, err := lastResults.permissionGetResultPreparer() + result := &PermissionGetResult{rawResponse: resp.Response()} if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return + return result, err } - resp, err := client.ListForResourceSender(req) + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceNextResults", resp, "Failure sending next results request") + return result, NewResponseError(err, resp.Response(), "failed to read response body") } - result, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceNextResults", resp, "Failure responding to next results request") + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } } - return -} - -// ListForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client PermissionsClient) ListForResourceComplete(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result PermissionGetResultIterator, err error) { - result.page, err = client.ListForResource(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName) - return + return result, nil } // ListForResourceGroup gets all permissions the caller has for a resource group. // // resourceGroupName is the name of the resource group to get the permissions for. The name is case insensitive. -func (client PermissionsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string) (result PermissionGetResultPage, err error) { - result.fn = client.listForResourceGroupNextResults - req, err := client.ListForResourceGroupPreparer(ctx, resourceGroupName) +func (client PermissionsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string) (*PermissionGetResult, error) { + req, err := client.listForResourceGroupPreparer(resourceGroupName) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResourceGroup", nil, "Failure preparing request") - return + return nil, err } - - resp, err := client.ListForResourceGroupSender(req) + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceGroupResponder}, req) if err != nil { - result.pgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResourceGroup", resp, "Failure sending request") - return + return nil, err } + return resp.(*PermissionGetResult), err +} - result.pgr, err = client.ListForResourceGroupResponder(resp) +// listForResourceGroupPreparer prepares the ListForResourceGroup request. +func (client PermissionsClient) listForResourceGroupPreparer(resourceGroupName string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions" + req, err := pipeline.NewRequest("GET", u, nil) if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "ListForResourceGroup", resp, "Failure responding to request") + return req, pipeline.NewError(err, "failed to create request") } - - return + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil } -// ListForResourceGroupPreparer prepares the ListForResourceGroup request. -func (client PermissionsClient) ListForResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), +// listForResourceGroupResponder handles the response to the ListForResourceGroup request. +func (client PermissionsClient) listForResourceGroupResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PermissionsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always -// closes the http.Response Body. -func (client PermissionsClient) ListForResourceGroupResponder(resp *http.Response) (result PermissionGetResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceGroupNextResults retrieves the next set of results, if any. -func (client PermissionsClient) listForResourceGroupNextResults(lastResults PermissionGetResult) (result PermissionGetResult, err error) { - req, err := lastResults.permissionGetResultPreparer() + result := &PermissionGetResult{rawResponse: resp.Response()} if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceGroupNextResults", nil, "Failure preparing next results request") + return result, err } - if req == nil { - return - } - resp, err := client.ListForResourceGroupSender(req) + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceGroupNextResults", resp, "Failure sending next results request") + return result, NewResponseError(err, resp.Response(), "failed to read response body") } - result, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.PermissionsClient", "listForResourceGroupNextResults", resp, "Failure responding to next results request") + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } } - return -} - -// ListForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PermissionsClient) ListForResourceGroupComplete(ctx context.Context, resourceGroupName string) (result PermissionGetResultIterator, err error) { - result.page, err = client.ListForResourceGroup(ctx, resourceGroupName) - return + return result, nil } diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/provider_operations_metadata.go b/services/authorization/mgmt/2017-10-01-preview/authorization/provider_operations_metadata.go new file mode 100644 index 000000000000..9ef7439aa2f5 --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/provider_operations_metadata.go @@ -0,0 +1,152 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// ProviderOperationsMetadataClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type ProviderOperationsMetadataClient struct { + ManagementClient +} + +// NewProviderOperationsMetadataClient creates an instance of the ProviderOperationsMetadataClient client. +func NewProviderOperationsMetadataClient(p pipeline.Pipeline) ProviderOperationsMetadataClient { + return ProviderOperationsMetadataClient{NewManagementClient(p)} +} + +// Get gets provider operations metadata for the specified resource provider. +// +// resourceProviderNamespace is the namespace of the resource provider. expand is specifies whether to expand the +// values. +func (client ProviderOperationsMetadataClient) Get(ctx context.Context, resourceProviderNamespace string, expand *string) (*ProviderOperationsMetadata, error) { + req, err := client.getPreparer(resourceProviderNamespace, expand) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ProviderOperationsMetadata), err +} + +// getPreparer prepares the Get request. +func (client ProviderOperationsMetadataClient) getPreparer(resourceProviderNamespace string, expand *string) (pipeline.Request, error) { + u := client.url + u.Path = "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + if expand != nil { + params.Set("$expand", *expand) + } + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client ProviderOperationsMetadataClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ProviderOperationsMetadata{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List gets provider operations metadata for all resource providers. +// +// expand is specifies whether to expand the values. +func (client ProviderOperationsMetadataClient) List(ctx context.Context, expand *string) (*ProviderOperationsMetadataListResult, error) { + req, err := client.listPreparer(expand) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ProviderOperationsMetadataListResult), err +} + +// listPreparer prepares the List request. +func (client ProviderOperationsMetadataClient) listPreparer(expand *string) (pipeline.Request, error) { + u := client.url + u.Path = "/providers/Microsoft.Authorization/providerOperations" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", APIVersion) + if expand != nil { + params.Set("$expand", *expand) + } + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client ProviderOperationsMetadataClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ProviderOperationsMetadataListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/provideroperationsmetadata.go b/services/authorization/mgmt/2017-10-01-preview/authorization/provideroperationsmetadata.go deleted file mode 100644 index d27e98e87b9c..000000000000 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/provideroperationsmetadata.go +++ /dev/null @@ -1,202 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// ProviderOperationsMetadataClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type ProviderOperationsMetadataClient struct { - BaseClient -} - -// NewProviderOperationsMetadataClient creates an instance of the ProviderOperationsMetadataClient client. -func NewProviderOperationsMetadataClient(subscriptionID string) ProviderOperationsMetadataClient { - return NewProviderOperationsMetadataClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewProviderOperationsMetadataClientWithBaseURI creates an instance of the ProviderOperationsMetadataClient client. -func NewProviderOperationsMetadataClientWithBaseURI(baseURI string, subscriptionID string) ProviderOperationsMetadataClient { - return ProviderOperationsMetadataClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets provider operations metadata for the specified resource provider. -// -// resourceProviderNamespace is the namespace of the resource provider. expand is specifies whether to expand the -// values. -func (client ProviderOperationsMetadataClient) Get(ctx context.Context, resourceProviderNamespace string, expand string) (result ProviderOperationsMetadata, err error) { - req, err := client.GetPreparer(ctx, resourceProviderNamespace, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client ProviderOperationsMetadataClient) GetPreparer(ctx context.Context, resourceProviderNamespace string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace), - } - - const APIVersion = "" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ProviderOperationsMetadataClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ProviderOperationsMetadataClient) GetResponder(resp *http.Response) (result ProviderOperationsMetadata, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets provider operations metadata for all resource providers. -// -// expand is specifies whether to expand the values. -func (client ProviderOperationsMetadataClient) List(ctx context.Context, expand string) (result ProviderOperationsMetadataListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pomlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "List", resp, "Failure sending request") - return - } - - result.pomlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ProviderOperationsMetadataClient) ListPreparer(ctx context.Context, expand string) (*http.Request, error) { - const APIVersion = "" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Authorization/providerOperations"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ProviderOperationsMetadataClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ProviderOperationsMetadataClient) ListResponder(resp *http.Response) (result ProviderOperationsMetadataListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ProviderOperationsMetadataClient) listNextResults(lastResults ProviderOperationsMetadataListResult) (result ProviderOperationsMetadataListResult, err error) { - req, err := lastResults.providerOperationsMetadataListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.ProviderOperationsMetadataClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProviderOperationsMetadataClient) ListComplete(ctx context.Context, expand string) (result ProviderOperationsMetadataListResultIterator, err error) { - result.page, err = client.List(ctx, expand) - return -} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/responder_policy.go b/services/authorization/mgmt/2017-10-01-preview/authorization/responder_policy.go new file mode 100644 index 000000000000..06f946241b6e --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/responder_policy.go @@ -0,0 +1,81 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/xml" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" +) + +type responder func(resp pipeline.Response) (result pipeline.Response, err error) + +// ResponderPolicyFactory is a Factory capable of creating a responder pipeline. +type responderPolicyFactory struct { + responder responder +} + +// New creates a responder policy factory. +func (arpf responderPolicyFactory) New(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.Policy { + return responderPolicy{next: next, responder: arpf.responder} +} + +type responderPolicy struct { + next pipeline.Policy + responder responder +} + +// Do sends the request to the service and validates/deserializes the HTTP response. +func (arp responderPolicy) Do(ctx context.Context, request pipeline.Request) (pipeline.Response, error) { + resp, err := arp.next.Do(ctx, request) + if err != nil { + return resp, err + } + return arp.responder(resp) +} + +// validateResponse checks an HTTP response's status code against a legal set of codes. +// If the response code is not legal, then validateResponse reads all of the response's body +// (containing error information) and returns a response error. +func validateResponse(resp pipeline.Response, successStatusCodes ...int) error { + if resp == nil { + return NewResponseError(nil, nil, "nil response") + } + responseCode := resp.Response().StatusCode + for _, i := range successStatusCodes { + if i == responseCode { + return nil + } + } + // only close the body in the failure case. in the + // success case responders will close the body as required. + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return NewResponseError(err, resp.Response(), "failed to read response body") + } + // the service code, description and details will be populated during unmarshalling + responseError := NewResponseError(nil, resp.Response(), resp.Response().Status) + if len(b) > 0 { + if err = xml.Unmarshal(b, &responseError); err != nil { + return NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return responseError +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/response_error.go b/services/authorization/mgmt/2017-10-01-preview/authorization/response_error.go new file mode 100644 index 000000000000..3704b446893e --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/response_error.go @@ -0,0 +1,110 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "fmt" + "github.com/Azure/azure-pipeline-go/pipeline" + "net" + "net/http" +) + +// if you want to provide custom error handling set this variable to your constructor function +var responseErrorFactory func(cause error, response *http.Response, description string) error + +// ResponseError identifies a responder-generated network or response parsing error. +type ResponseError interface { + // Error exposes the Error(), Temporary() and Timeout() methods. + net.Error // Includes the Go error interface + + // Response returns the HTTP response. You may examine this but you should not modify it. + Response() *http.Response +} + +// NewResponseError creates an error object that implements the error interface. +func NewResponseError(cause error, response *http.Response, description string) error { + if responseErrorFactory != nil { + return responseErrorFactory(cause, response, description) + } + return &responseError{ + ErrorNode: pipeline.ErrorNode{}.Initialize(cause, 3), + response: response, + description: description, + } +} + +// responseError is the internal struct that implements the public ResponseError interface. +type responseError struct { + pipeline.ErrorNode // This is embedded so that responseError "inherits" Error, Temporary, Timeout, and Cause + response *http.Response + description string +} + +// Error implements the error interface's Error method to return a string representation of the error. +func (e *responseError) Error() string { + b := &bytes.Buffer{} + fmt.Fprintf(b, "===== RESPONSE ERROR (Code=%v) =====\n", e.response.StatusCode) + fmt.Fprintf(b, "Status=%s, Description: %s\n", e.response.Status, e.description) + s := b.String() + return e.ErrorNode.Error(s) +} + +// Response implements the ResponseError interface's method to return the HTTP response. +func (e *responseError) Response() *http.Response { + return e.response +} + +// RFC7807 PROBLEM ------------------------------------------------------------------------------------ +// RFC7807Problem ... This type can be publicly embedded in another type that wants to add additional members. +/*type RFC7807Problem struct { + // Mandatory: A (relative) URI reference identifying the problem type (it MAY refer to human-readable documentation). + typeURI string // Should default to "about:blank" + // Optional: Short, human-readable summary (maybe localized). + title string + // Optional: HTTP status code generated by the origin server + status int + // Optional: Human-readable explanation for this problem occurance. + // Should help client correct the problem. Clients should NOT parse this string. + detail string + // Optional: A (relative) URI identifying this specific problem occurence (it may or may not be dereferenced). + instance string +} +// NewRFC7807Problem ... +func NewRFC7807Problem(typeURI string, status int, titleFormat string, a ...interface{}) error { + return &RFC7807Problem{ + typeURI: typeURI, + status: status, + title: fmt.Sprintf(titleFormat, a...), + } +} +// Error returns the error information as a string. +func (e *RFC7807Problem) Error() string { + return e.title +} +// TypeURI ... +func (e *RFC7807Problem) TypeURI() string { + if e.typeURI == "" { + e.typeURI = "about:blank" + } + return e.typeURI +} +// Members ... +func (e *RFC7807Problem) Members() (status int, title, detail, instance string) { + return e.status, e.title, e.detail, e.instance +}*/ diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/role_assignments.go b/services/authorization/mgmt/2017-10-01-preview/authorization/role_assignments.go new file mode 100644 index 000000000000..b763e10e479e --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/role_assignments.go @@ -0,0 +1,616 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// RoleAssignmentsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type RoleAssignmentsClient struct { + ManagementClient +} + +// NewRoleAssignmentsClient creates an instance of the RoleAssignmentsClient client. +func NewRoleAssignmentsClient(p pipeline.Pipeline) RoleAssignmentsClient { + return RoleAssignmentsClient{NewManagementClient(p)} +} + +// Create creates a role assignment. +// +// scope is the scope of the role assignment to create. The scope can be any REST resource instance. For example, use +// '/subscriptions/{subscription-id}/' for a subscription, +// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and +// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' +// for a resource. roleAssignmentName is the name of the role assignment to create. It can be any valid GUID. +// parameters is parameters for the role assignment. +func (client RoleAssignmentsClient) Create(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (*RoleAssignment, error) { + req, err := client.createPreparer(scope, roleAssignmentName, parameters) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// createPreparer prepares the Create request. +func (client RoleAssignmentsClient) createPreparer(scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(parameters) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createResponder handles the response to the Create request. +func (client RoleAssignmentsClient) createResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// CreateByID creates a role assignment by ID. +// +// roleAssignmentID is the ID of the role assignment to create. parameters is parameters for the role assignment. +func (client RoleAssignmentsClient) CreateByID(ctx context.Context, roleAssignmentID string, parameters RoleAssignmentCreateParameters) (*RoleAssignment, error) { + req, err := client.createByIDPreparer(roleAssignmentID, parameters) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// createByIDPreparer prepares the CreateByID request. +func (client RoleAssignmentsClient) createByIDPreparer(roleAssignmentID string, parameters RoleAssignmentCreateParameters) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleAssignmentId}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(parameters) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createByIDResponder handles the response to the CreateByID request. +func (client RoleAssignmentsClient) createByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Delete deletes a role assignment. +// +// scope is the scope of the role assignment to delete. roleAssignmentName is the name of the role assignment to +// delete. +func (client RoleAssignmentsClient) Delete(ctx context.Context, scope string, roleAssignmentName string) (*RoleAssignment, error) { + req, err := client.deletePreparer(scope, roleAssignmentName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// deletePreparer prepares the Delete request. +func (client RoleAssignmentsClient) deletePreparer(scope string, roleAssignmentName string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteResponder handles the response to the Delete request. +func (client RoleAssignmentsClient) deleteResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// DeleteByID deletes a role assignment. +// +// roleAssignmentID is the ID of the role assignment to delete. +func (client RoleAssignmentsClient) DeleteByID(ctx context.Context, roleAssignmentID string) (*RoleAssignment, error) { + req, err := client.deleteByIDPreparer(roleAssignmentID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// deleteByIDPreparer prepares the DeleteByID request. +func (client RoleAssignmentsClient) deleteByIDPreparer(roleAssignmentID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleAssignmentId}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteByIDResponder handles the response to the DeleteByID request. +func (client RoleAssignmentsClient) deleteByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Get get the specified role assignment. +// +// scope is the scope of the role assignment. roleAssignmentName is the name of the role assignment to get. +func (client RoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (*RoleAssignment, error) { + req, err := client.getPreparer(scope, roleAssignmentName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// getPreparer prepares the Get request. +func (client RoleAssignmentsClient) getPreparer(scope string, roleAssignmentName string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client RoleAssignmentsClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// GetByID gets a role assignment by ID. +// +// roleAssignmentID is the ID of the role assignment to get. +func (client RoleAssignmentsClient) GetByID(ctx context.Context, roleAssignmentID string) (*RoleAssignment, error) { + req, err := client.getByIDPreparer(roleAssignmentID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// getByIDPreparer prepares the GetByID request. +func (client RoleAssignmentsClient) getByIDPreparer(roleAssignmentID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleAssignmentId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getByIDResponder handles the response to the GetByID request. +func (client RoleAssignmentsClient) getByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List gets all role assignments for the subscription. +// +// filter is the filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the +// scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified +// principal. +func (client RoleAssignmentsClient) List(ctx context.Context, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listPreparer(filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listPreparer prepares the List request. +func (client RoleAssignmentsClient) listPreparer(filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client RoleAssignmentsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResource gets role assignments for a resource. +// +// resourceGroupName is the name of the resource group. resourceProviderNamespace is the namespace of the resource +// provider. parentResourcePath is the parent resource identity. resourceType is the resource type of the resource. +// resourceName is the name of the resource to get role assignments for. filter is the filter to apply on the +// operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq +// {id} to return all role assignments at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForResourcePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForResourcePreparer prepares the ListForResource request. +func (client RoleAssignmentsClient) listForResourcePreparer(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceResponder handles the response to the ListForResource request. +func (client RoleAssignmentsClient) listForResourceResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResourceGroup gets role assignments for a resource group. +// +// resourceGroupName is the name of the resource group. filter is the filter to apply on the operation. Use +// $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return +// all role assignments at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForResourceGroupPreparer(resourceGroupName, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceGroupResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForResourceGroupPreparer prepares the ListForResourceGroup request. +func (client RoleAssignmentsClient) listForResourceGroupPreparer(resourceGroupName string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceGroupResponder handles the response to the ListForResourceGroup request. +func (client RoleAssignmentsClient) listForResourceGroupResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForScope gets role assignments for a scope. +// +// scope is the scope of the role assignments. filter is the filter to apply on the operation. Use $filter=atScope() to +// return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments +// at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForScope(ctx context.Context, scope string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForScopePreparer(scope, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForScopeResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForScopePreparer prepares the ListForScope request. +func (client RoleAssignmentsClient) listForScopePreparer(scope string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2017-10-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForScopeResponder handles the response to the ListForScope request. +func (client RoleAssignmentsClient) listForScopeResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/role_definitions.go b/services/authorization/mgmt/2017-10-01-preview/authorization/role_definitions.go new file mode 100644 index 000000000000..11898f412952 --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/role_definitions.go @@ -0,0 +1,322 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// RoleDefinitionsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type RoleDefinitionsClient struct { + ManagementClient +} + +// NewRoleDefinitionsClient creates an instance of the RoleDefinitionsClient client. +func NewRoleDefinitionsClient(p pipeline.Pipeline) RoleDefinitionsClient { + return RoleDefinitionsClient{NewManagementClient(p)} +} + +// CreateOrUpdate creates or updates a role definition. +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. roleDefinition is the +// values for the role definition. +func (client RoleDefinitionsClient) CreateOrUpdate(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (*RoleDefinition, error) { + req, err := client.createOrUpdatePreparer(scope, roleDefinitionID, roleDefinition) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createOrUpdateResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// createOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RoleDefinitionsClient) createOrUpdatePreparer(scope string, roleDefinitionID string, roleDefinition RoleDefinition) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(roleDefinition) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createOrUpdateResponder handles the response to the CreateOrUpdate request. +func (client RoleDefinitionsClient) createOrUpdateResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Delete deletes a role definition. +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition to delete. +func (client RoleDefinitionsClient) Delete(ctx context.Context, scope string, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.deletePreparer(scope, roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// deletePreparer prepares the Delete request. +func (client RoleDefinitionsClient) deletePreparer(scope string, roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteResponder handles the response to the Delete request. +func (client RoleDefinitionsClient) deleteResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Get get role definition by name (GUID). +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. +func (client RoleDefinitionsClient) Get(ctx context.Context, scope string, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.getPreparer(scope, roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// getPreparer prepares the Get request. +func (client RoleDefinitionsClient) getPreparer(scope string, roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client RoleDefinitionsClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// GetByID gets a role definition by ID. +// +// roleDefinitionID is the fully qualified role definition ID. Use the format, +// /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level +// role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role +// definitions. +func (client RoleDefinitionsClient) GetByID(ctx context.Context, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.getByIDPreparer(roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// getByIDPreparer prepares the GetByID request. +func (client RoleDefinitionsClient) getByIDPreparer(roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleDefinitionId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getByIDResponder handles the response to the GetByID request. +func (client RoleDefinitionsClient) getByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List get all role definitions that are applicable at scope and above. +// +// scope is the scope of the role definition. filter is the filter to apply on the operation. Use atScopeAndBelow +// filter to search below the given scope as well. +func (client RoleDefinitionsClient) List(ctx context.Context, scope string, filter *string) (*RoleDefinitionListResult, error) { + req, err := client.listPreparer(scope, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinitionListResult), err +} + +// listPreparer prepares the List request. +func (client RoleDefinitionsClient) listPreparer(scope string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client RoleDefinitionsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinitionListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/roleassignments.go b/services/authorization/mgmt/2017-10-01-preview/authorization/roleassignments.go deleted file mode 100644 index a7efe109e30c..000000000000 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/roleassignments.go +++ /dev/null @@ -1,836 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// RoleAssignmentsClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type RoleAssignmentsClient struct { - BaseClient -} - -// NewRoleAssignmentsClient creates an instance of the RoleAssignmentsClient client. -func NewRoleAssignmentsClient(subscriptionID string) RoleAssignmentsClient { - return NewRoleAssignmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoleAssignmentsClientWithBaseURI creates an instance of the RoleAssignmentsClient client. -func NewRoleAssignmentsClientWithBaseURI(baseURI string, subscriptionID string) RoleAssignmentsClient { - return RoleAssignmentsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create creates a role assignment. -// -// scope is the scope of the role assignment to create. The scope can be any REST resource instance. For example, use -// '/subscriptions/{subscription-id}/' for a subscription, -// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and -// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' -// for a resource. roleAssignmentName is the name of the role assignment to create. It can be any valid GUID. -// parameters is parameters for the role assignment. -func (client RoleAssignmentsClient) Create(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (result RoleAssignment, err error) { - req, err := client.CreatePreparer(ctx, scope, roleAssignmentName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Create", resp, "Failure responding to request") - } - - return -} - -// CreatePreparer prepares the Create request. -func (client RoleAssignmentsClient) CreatePreparer(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentName": autorest.Encode("path", roleAssignmentName), - "scope": scope, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsJSON(), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) CreateResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateByID creates a role assignment by ID. -// -// roleAssignmentID is the ID of the role assignment to create. parameters is parameters for the role assignment. -func (client RoleAssignmentsClient) CreateByID(ctx context.Context, roleAssignmentID string, parameters RoleAssignmentCreateParameters) (result RoleAssignment, err error) { - req, err := client.CreateByIDPreparer(ctx, roleAssignmentID, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "CreateByID", nil, "Failure preparing request") - return - } - - resp, err := client.CreateByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "CreateByID", resp, "Failure sending request") - return - } - - result, err = client.CreateByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "CreateByID", resp, "Failure responding to request") - } - - return -} - -// CreateByIDPreparer prepares the CreateByID request. -func (client RoleAssignmentsClient) CreateByIDPreparer(ctx context.Context, roleAssignmentID string, parameters RoleAssignmentCreateParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentId": roleAssignmentID, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsJSON(), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleAssignmentId}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateByIDSender sends the CreateByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) CreateByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateByIDResponder handles the response to the CreateByID request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) CreateByIDResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a role assignment. -// -// scope is the scope of the role assignment to delete. roleAssignmentName is the name of the role assignment to -// delete. -func (client RoleAssignmentsClient) Delete(ctx context.Context, scope string, roleAssignmentName string) (result RoleAssignment, err error) { - req, err := client.DeletePreparer(ctx, scope, roleAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoleAssignmentsClient) DeletePreparer(ctx context.Context, scope string, roleAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentName": autorest.Encode("path", roleAssignmentName), - "scope": scope, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) DeleteResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteByID deletes a role assignment. -// -// roleAssignmentID is the ID of the role assignment to delete. -func (client RoleAssignmentsClient) DeleteByID(ctx context.Context, roleAssignmentID string) (result RoleAssignment, err error) { - req, err := client.DeleteByIDPreparer(ctx, roleAssignmentID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "DeleteByID", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "DeleteByID", resp, "Failure sending request") - return - } - - result, err = client.DeleteByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "DeleteByID", resp, "Failure responding to request") - } - - return -} - -// DeleteByIDPreparer prepares the DeleteByID request. -func (client RoleAssignmentsClient) DeleteByIDPreparer(ctx context.Context, roleAssignmentID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentId": roleAssignmentID, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleAssignmentId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteByIDSender sends the DeleteByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) DeleteByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteByIDResponder handles the response to the DeleteByID request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) DeleteByIDResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get get the specified role assignment. -// -// scope is the scope of the role assignment. roleAssignmentName is the name of the role assignment to get. -func (client RoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (result RoleAssignment, err error) { - req, err := client.GetPreparer(ctx, scope, roleAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoleAssignmentsClient) GetPreparer(ctx context.Context, scope string, roleAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentName": autorest.Encode("path", roleAssignmentName), - "scope": scope, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) GetResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetByID gets a role assignment by ID. -// -// roleAssignmentID is the ID of the role assignment to get. -func (client RoleAssignmentsClient) GetByID(ctx context.Context, roleAssignmentID string) (result RoleAssignment, err error) { - req, err := client.GetByIDPreparer(ctx, roleAssignmentID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "GetByID", nil, "Failure preparing request") - return - } - - resp, err := client.GetByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "GetByID", resp, "Failure sending request") - return - } - - result, err = client.GetByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "GetByID", resp, "Failure responding to request") - } - - return -} - -// GetByIDPreparer prepares the GetByID request. -func (client RoleAssignmentsClient) GetByIDPreparer(ctx context.Context, roleAssignmentID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleAssignmentId": roleAssignmentID, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleAssignmentId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetByIDSender sends the GetByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) GetByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetByIDResponder handles the response to the GetByID request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) GetByIDResponder(resp *http.Response) (result RoleAssignment, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all role assignments for the subscription. -// -// filter is the filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the -// scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified -// principal. -func (client RoleAssignmentsClient) List(ctx context.Context, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "List", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client RoleAssignmentsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListComplete(ctx context.Context, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.List(ctx, filter) - return -} - -// ListForResource gets role assignments for a resource. -// -// resourceGroupName is the name of the resource group. resourceProviderNamespace is the namespace of the resource -// provider. parentResourcePath is the parent resource identity. resourceType is the resource type of the resource. -// resourceName is the name of the resource to get role assignments for. filter is the filter to apply on the -// operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq -// {id} to return all role assignments at, above or below the scope for the specified principal. -func (client RoleAssignmentsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listForResourceNextResults - req, err := client.ListForResourcePreparer(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListForResourceSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResource", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResource", resp, "Failure responding to request") - } - - return -} - -// ListForResourcePreparer prepares the ListForResource request. -func (client RoleAssignmentsClient) ListForResourcePreparer(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "parentResourcePath": parentResourcePath, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "resourceName": autorest.Encode("path", resourceName), - "resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace), - "resourceType": resourceType, - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceSender sends the ListForResource request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListForResourceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceResponder handles the response to the ListForResource request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListForResourceResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listForResourceNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListForResourceComplete(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.ListForResource(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) - return -} - -// ListForResourceGroup gets role assignments for a resource group. -// -// resourceGroupName is the name of the resource group. filter is the filter to apply on the operation. Use -// $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return -// all role assignments at, above or below the scope for the specified principal. -func (client RoleAssignmentsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listForResourceGroupNextResults - req, err := client.ListForResourceGroupPreparer(ctx, resourceGroupName, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListForResourceGroupSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResourceGroup", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForResourceGroup", resp, "Failure responding to request") - } - - return -} - -// ListForResourceGroupPreparer prepares the ListForResourceGroup request. -func (client RoleAssignmentsClient) ListForResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListForResourceGroupResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceGroupNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listForResourceGroupNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListForResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.ListForResourceGroup(ctx, resourceGroupName, filter) - return -} - -// ListForScope gets role assignments for a scope. -// -// scope is the scope of the role assignments. filter is the filter to apply on the operation. Use $filter=atScope() to -// return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments -// at, above or below the scope for the specified principal. -func (client RoleAssignmentsClient) ListForScope(ctx context.Context, scope string, filter string) (result RoleAssignmentListResultPage, err error) { - result.fn = client.listForScopeNextResults - req, err := client.ListForScopePreparer(ctx, scope, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForScope", nil, "Failure preparing request") - return - } - - resp, err := client.ListForScopeSender(req) - if err != nil { - result.ralr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForScope", resp, "Failure sending request") - return - } - - result.ralr, err = client.ListForScopeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "ListForScope", resp, "Failure responding to request") - } - - return -} - -// ListForScopePreparer prepares the ListForScope request. -func (client RoleAssignmentsClient) ListForScopePreparer(ctx context.Context, scope string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "scope": scope, - } - - const APIVersion = "2017-10-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleAssignments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForScopeSender sends the ListForScope request. The method will close the -// http.Response Body if it receives an error. -func (client RoleAssignmentsClient) ListForScopeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListForScopeResponder handles the response to the ListForScope request. The method always -// closes the http.Response Body. -func (client RoleAssignmentsClient) ListForScopeResponder(resp *http.Response) (result RoleAssignmentListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForScopeNextResults retrieves the next set of results, if any. -func (client RoleAssignmentsClient) listForScopeNextResults(lastResults RoleAssignmentListResult) (result RoleAssignmentListResult, err error) { - req, err := lastResults.roleAssignmentListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForScopeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForScopeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForScopeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForScopeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleAssignmentsClient", "listForScopeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForScopeComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleAssignmentsClient) ListForScopeComplete(ctx context.Context, scope string, filter string) (result RoleAssignmentListResultIterator, err error) { - result.page, err = client.ListForScope(ctx, scope, filter) - return -} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/roledefinitions.go b/services/authorization/mgmt/2017-10-01-preview/authorization/roledefinitions.go deleted file mode 100644 index d143d5d7ae5a..000000000000 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/roledefinitions.go +++ /dev/null @@ -1,404 +0,0 @@ -package authorization - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// RoleDefinitionsClient is the role based access control provides you a way to apply granular level policy -// administration down to individual resources or resource groups. These operations enable you to manage role -// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. -// A role assignment grants access to Azure Active Directory users. -type RoleDefinitionsClient struct { - BaseClient -} - -// NewRoleDefinitionsClient creates an instance of the RoleDefinitionsClient client. -func NewRoleDefinitionsClient(subscriptionID string) RoleDefinitionsClient { - return NewRoleDefinitionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoleDefinitionsClientWithBaseURI creates an instance of the RoleDefinitionsClient client. -func NewRoleDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) RoleDefinitionsClient { - return RoleDefinitionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a role definition. -// -// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. roleDefinition is the -// values for the role definition. -func (client RoleDefinitionsClient) CreateOrUpdate(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (result RoleDefinition, err error) { - req, err := client.CreateOrUpdatePreparer(ctx, scope, roleDefinitionID, roleDefinition) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RoleDefinitionsClient) CreateOrUpdatePreparer(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": autorest.Encode("path", roleDefinitionID), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsJSON(), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", pathParameters), - autorest.WithJSON(roleDefinition), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) CreateOrUpdateResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a role definition. -// -// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition to delete. -func (client RoleDefinitionsClient) Delete(ctx context.Context, scope string, roleDefinitionID string) (result RoleDefinition, err error) { - req, err := client.DeletePreparer(ctx, scope, roleDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoleDefinitionsClient) DeletePreparer(ctx context.Context, scope string, roleDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": autorest.Encode("path", roleDefinitionID), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) DeleteResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get get role definition by name (GUID). -// -// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. -func (client RoleDefinitionsClient) Get(ctx context.Context, scope string, roleDefinitionID string) (result RoleDefinition, err error) { - req, err := client.GetPreparer(ctx, scope, roleDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoleDefinitionsClient) GetPreparer(ctx context.Context, scope string, roleDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": autorest.Encode("path", roleDefinitionID), - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) GetResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetByID gets a role definition by ID. -// -// roleDefinitionID is the fully qualified role definition ID. Use the format, -// /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level -// role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role -// definitions. -func (client RoleDefinitionsClient) GetByID(ctx context.Context, roleDefinitionID string) (result RoleDefinition, err error) { - req, err := client.GetByIDPreparer(ctx, roleDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "GetByID", nil, "Failure preparing request") - return - } - - resp, err := client.GetByIDSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "GetByID", resp, "Failure sending request") - return - } - - result, err = client.GetByIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "GetByID", resp, "Failure responding to request") - } - - return -} - -// GetByIDPreparer prepares the GetByID request. -func (client RoleDefinitionsClient) GetByIDPreparer(ctx context.Context, roleDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "roleDefinitionId": roleDefinitionID, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{roleDefinitionId}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetByIDSender sends the GetByID request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) GetByIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetByIDResponder handles the response to the GetByID request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) GetByIDResponder(resp *http.Response) (result RoleDefinition, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get all role definitions that are applicable at scope and above. -// -// scope is the scope of the role definition. filter is the filter to apply on the operation. Use atScopeAndBelow -// filter to search below the given scope as well. -func (client RoleDefinitionsClient) List(ctx context.Context, scope string, filter string) (result RoleDefinitionListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, scope, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "List", resp, "Failure sending request") - return - } - - result.rdlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client RoleDefinitionsClient) ListPreparer(ctx context.Context, scope string, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "scope": scope, - } - - const APIVersion = "2015-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/roleDefinitions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoleDefinitionsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoleDefinitionsClient) ListResponder(resp *http.Response) (result RoleDefinitionListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client RoleDefinitionsClient) listNextResults(lastResults RoleDefinitionListResult) (result RoleDefinitionListResult, err error) { - req, err := lastResults.roleDefinitionListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "authorization.RoleDefinitionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoleDefinitionsClient) ListComplete(ctx context.Context, scope string, filter string) (result RoleDefinitionListResultIterator, err error) { - result.page, err = client.List(ctx, scope, filter) - return -} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/validation.go b/services/authorization/mgmt/2017-10-01-preview/authorization/validation.go new file mode 100644 index 000000000000..e44edeb29921 --- /dev/null +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/validation.go @@ -0,0 +1,381 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "fmt" + "github.com/Azure/azure-pipeline-go/pipeline" + "reflect" + "regexp" + "strings" +) + +// Constraint stores constraint name, target field name +// Rule and chain validations. +type constraint struct { + // Target field name for validation. + target string + + // Constraint name e.g. minLength, MaxLength, Pattern, etc. + name string + + // Rule for constraint e.g. greater than 10, less than 5 etc. + rule interface{} + + // Chain validations for struct type + chain []constraint +} + +// Validation stores parameter-wise validation. +type validation struct { + targetValue interface{} + constraints []constraint +} + +// Constraint list +const ( + empty = "Empty" + null = "Null" + readOnly = "ReadOnly" + pattern = "Pattern" + maxLength = "MaxLength" + minLength = "MinLength" + maxItems = "MaxItems" + minItems = "MinItems" + multipleOf = "MultipleOf" + uniqueItems = "UniqueItems" + inclusiveMaximum = "InclusiveMaximum" + exclusiveMaximum = "ExclusiveMaximum" + exclusiveMinimum = "ExclusiveMinimum" + inclusiveMinimum = "InclusiveMinimum" +) + +// Validate method validates constraints on parameter +// passed in validation array. +func validate(m []validation) error { + for _, item := range m { + v := reflect.ValueOf(item.targetValue) + for _, constraint := range item.constraints { + var err error + switch v.Kind() { + case reflect.Ptr: + err = validatePtr(v, constraint) + case reflect.String: + err = validateString(v, constraint) + case reflect.Struct: + err = validateStruct(v, constraint) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + err = validateInt(v, constraint) + case reflect.Float32, reflect.Float64: + err = validateFloat(v, constraint) + case reflect.Array, reflect.Slice, reflect.Map: + err = validateArrayMap(v, constraint) + default: + err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) + } + if err != nil { + return err + } + } + } + return nil +} + +func validateStruct(x reflect.Value, v constraint, name ...string) error { + //Get field name from target name which is in format a.b.c + s := strings.Split(v.target, ".") + f := x.FieldByName(s[len(s)-1]) + if isZero(f) { + return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.target)) + } + err := validate([]validation{ + { + targetValue: getInterfaceValue(f), + constraints: []constraint{v}, + }, + }) + return err +} + +func validatePtr(x reflect.Value, v constraint) error { + if v.name == readOnly { + if !x.IsNil() { + return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") + } + return nil + } + if x.IsNil() { + return checkNil(x, v) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x.Elem()), + constraints: v.chain, + }, + }) + } + return nil +} + +func validateInt(x reflect.Value, v constraint) error { + i := x.Int() + r, ok := v.rule.(int) + if !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + switch v.name { + case multipleOf: + if i%int64(r) != 0 { + return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) + } + case exclusiveMinimum: + if i <= int64(r) { + return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) + } + case exclusiveMaximum: + if i >= int64(r) { + return createError(x, v, fmt.Sprintf("value must be less than %v", r)) + } + case inclusiveMinimum: + if i < int64(r) { + return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) + } + case inclusiveMaximum: + if i > int64(r) { + return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) + } + default: + return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.name)) + } + return nil +} + +func validateFloat(x reflect.Value, v constraint) error { + f := x.Float() + r, ok := v.rule.(float64) + if !ok { + return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.name, v.rule)) + } + switch v.name { + case exclusiveMinimum: + if f <= r { + return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) + } + case exclusiveMaximum: + if f >= r { + return createError(x, v, fmt.Sprintf("value must be less than %v", r)) + } + case inclusiveMinimum: + if f < r { + return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) + } + case inclusiveMaximum: + if f > r { + return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) + } + default: + return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.name)) + } + return nil +} + +func validateString(x reflect.Value, v constraint) error { + s := x.String() + switch v.name { + case empty: + if len(s) == 0 { + return checkEmpty(x, v) + } + case pattern: + reg, err := regexp.Compile(v.rule.(string)) + if err != nil { + return createError(x, v, err.Error()) + } + if !reg.MatchString(s) { + return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.rule)) + } + case maxLength: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + if len(s) > v.rule.(int) { + return createError(x, v, fmt.Sprintf("value length must be less than %v", v.rule)) + } + case minLength: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + if len(s) < v.rule.(int) { + return createError(x, v, fmt.Sprintf("value length must be greater than %v", v.rule)) + } + case readOnly: + if len(s) > 0 { + return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") + } + default: + return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.name)) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x), + constraints: v.chain, + }, + }) + } + return nil +} + +func validateArrayMap(x reflect.Value, v constraint) error { + switch v.name { + case null: + if x.IsNil() { + return checkNil(x, v) + } + case empty: + if x.IsNil() || x.Len() == 0 { + return checkEmpty(x, v) + } + case maxItems: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.name, v.rule)) + } + if x.Len() > v.rule.(int) { + return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.rule, x.Len())) + } + case minItems: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.name, v.rule)) + } + if x.Len() < v.rule.(int) { + return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.rule, x.Len())) + } + case uniqueItems: + if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { + if !checkForUniqueInArray(x) { + return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.target, x)) + } + } else if x.Kind() == reflect.Map { + if !checkForUniqueInMap(x) { + return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.target, x)) + } + } else { + return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.name, x.Kind())) + } + case readOnly: + if x.Len() != 0 { + return createError(x, v, "readonly parameter; must send as nil or empty in request") + } + case pattern: + reg, err := regexp.Compile(v.rule.(string)) + if err != nil { + return createError(x, v, err.Error()) + } + keys := x.MapKeys() + for _, k := range keys { + if !reg.MatchString(k.String()) { + return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.rule)) + } + } + default: + return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.name)) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x), + constraints: v.chain, + }, + }) + } + return nil +} + +func checkNil(x reflect.Value, v constraint) error { + if _, ok := v.rule.(bool); !ok { + return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.name, v.rule)) + } + if v.rule.(bool) { + return createError(x, v, "value can not be null; required parameter") + } + return nil +} + +func checkEmpty(x reflect.Value, v constraint) error { + if _, ok := v.rule.(bool); !ok { + return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.name, v.rule)) + } + if v.rule.(bool) { + return createError(x, v, "value can not be null or empty; required parameter") + } + return nil +} + +func checkForUniqueInArray(x reflect.Value) bool { + if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { + return false + } + arrOfInterface := make([]interface{}, x.Len()) + for i := 0; i < x.Len(); i++ { + arrOfInterface[i] = x.Index(i).Interface() + } + m := make(map[interface{}]bool) + for _, val := range arrOfInterface { + if m[val] { + return false + } + m[val] = true + } + return true +} + +func checkForUniqueInMap(x reflect.Value) bool { + if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { + return false + } + mapOfInterface := make(map[interface{}]interface{}, x.Len()) + keys := x.MapKeys() + for _, k := range keys { + mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() + } + m := make(map[interface{}]bool) + for _, val := range mapOfInterface { + if m[val] { + return false + } + m[val] = true + } + return true +} + +func getInterfaceValue(x reflect.Value) interface{} { + if x.Kind() == reflect.Invalid { + return nil + } + return x.Interface() +} + +func isZero(x interface{}) bool { + return x == reflect.Zero(reflect.TypeOf(x)).Interface() +} + +func createError(x reflect.Value, v constraint, message string) error { + return pipeline.NewError(nil, fmt.Sprintf("validation failed: parameter=%s constraint=%s value=%#v details: %s", + v.target, v.name, getInterfaceValue(x), message)) +} diff --git a/services/authorization/mgmt/2017-10-01-preview/authorization/version.go b/services/authorization/mgmt/2017-10-01-preview/authorization/version.go index ea3d2316383a..9aef92a819d1 100644 --- a/services/authorization/mgmt/2017-10-01-preview/authorization/version.go +++ b/services/authorization/mgmt/2017-10-01-preview/authorization/version.go @@ -19,10 +19,10 @@ package authorization // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/v12.1.1-beta services" + return "Azure-SDK-For-Go/v12.2.1-beta arm-authorization/" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return "v12.1.1-beta" + return "v12.2.1-beta" } diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/classic_administrators.go b/services/authorization/mgmt/2018-01-01-preview/authorization/classic_administrators.go new file mode 100644 index 000000000000..497576ec30d6 --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/classic_administrators.go @@ -0,0 +1,90 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// ClassicAdministratorsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type ClassicAdministratorsClient struct { + ManagementClient +} + +// NewClassicAdministratorsClient creates an instance of the ClassicAdministratorsClient client. +func NewClassicAdministratorsClient(p pipeline.Pipeline) ClassicAdministratorsClient { + return ClassicAdministratorsClient{NewManagementClient(p)} +} + +// List gets service administrator, account administrator, and co-administrators for the subscription. +func (client ClassicAdministratorsClient) List(ctx context.Context) (*ClassicAdministratorListResult, error) { + req, err := client.listPreparer() + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ClassicAdministratorListResult), err +} + +// listPreparer prepares the List request. +func (client ClassicAdministratorsClient) listPreparer() (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/classicAdministrators" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2015-07-01") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client ClassicAdministratorsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ClassicAdministratorListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/client.go b/services/authorization/mgmt/2018-01-01-preview/authorization/client.go new file mode 100644 index 000000000000..ec71e4b27367 --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/client.go @@ -0,0 +1,63 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/azure-pipeline-go/pipeline" + "net/url" +) + +const ( + // ServiceVersion specifies the version of the operations used in this package. + ServiceVersion = "" + // DefaultBaseURL is the default URL used for the service Authorization + DefaultBaseURL = "https://management.azure.com" +) + +// ManagementClient is the base client for Authorization. +type ManagementClient struct { + url url.URL + p pipeline.Pipeline +} + +// NewManagementClient creates an instance of the ManagementClient client. +func NewManagementClient(p pipeline.Pipeline) ManagementClient { + u, err := url.Parse(DefaultBaseURL) + if err != nil { + panic(err) + } + return NewManagementClientWithURL(*u, p) +} + +// NewManagementClientWithURL creates an instance of the ManagementClient client. +func NewManagementClientWithURL(url url.URL, p pipeline.Pipeline) ManagementClient { + return ManagementClient{ + url: url, + p: p, + } +} + +// URL returns a copy of the URL for this client. +func (mc ManagementClient) URL() url.URL { + return mc.url +} + +// Pipeline returns the pipeline for this client. +func (mc ManagementClient) Pipeline() pipeline.Pipeline { + return mc.p +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/models.go b/services/authorization/mgmt/2018-01-01-preview/authorization/models.go new file mode 100644 index 000000000000..1a0e1692046d --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/models.go @@ -0,0 +1,365 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "net/http" +) + +// Marker represents an opaque value used in paged responses. +type Marker struct { + val *string +} + +// NotDone returns true if the list enumeration should be started or is not yet complete. Specifically, NotDone returns true +// for a just-initialized (zero value) Marker indicating that you should make an initial request to get a result portion from +// the service. NotDone also returns true whenever the service returns an interim result portion. NotDone returns false only +// after the service has returned the final result portion. +func (m Marker) NotDone() bool { + return m.val == nil || *m.val != "" +} + +// UnmarshalXML implements the xml.Unmarshaler interface for Marker. +func (m *Marker) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var out string + err := d.DecodeElement(&out, &start) + m.val = &out + return err +} + +// ClassicAdministrator - Classic Administrators +type ClassicAdministrator struct { + // ID - The ID of the administrator. + ID *string `json:"id,omitempty"` + // Name - The name of the administrator. + Name *string `json:"name,omitempty"` + // Type - The type of the administrator. + Type *string `json:"type,omitempty"` + // Properties - Properties for the classic administrator. + *ClassicAdministratorProperties `json:"properties,omitempty"` +} + +// ClassicAdministratorListResult - ClassicAdministrator list result information. +type ClassicAdministratorListResult struct { + rawResponse *http.Response + // Value - An array of administrators. + Value []ClassicAdministrator `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` +} + +// Response returns the raw HTTP response object. +func (calr ClassicAdministratorListResult) Response() *http.Response { + return calr.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (calr ClassicAdministratorListResult) StatusCode() int { + return calr.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (calr ClassicAdministratorListResult) Status() string { + return calr.rawResponse.Status +} + +// ClassicAdministratorProperties - Classic Administrator properties. +type ClassicAdministratorProperties struct { + // EmailAddress - The email address of the administrator. + EmailAddress *string `json:"emailAddress,omitempty"` + // Role - The role of the administrator. + Role *string `json:"role,omitempty"` +} + +// Permission - Role definition permissions. +type Permission struct { + // Actions - Allowed actions. + Actions []string `json:"actions,omitempty"` + // NotActions - Denied actions. + NotActions []string `json:"notActions,omitempty"` + // DataActions - Allowed Data actions. + DataActions []string `json:"dataActions,omitempty"` + // NotDataActions - Denied Data actions. + NotDataActions []string `json:"notDataActions,omitempty"` +} + +// PermissionGetResult - Permissions information. +type PermissionGetResult struct { + rawResponse *http.Response + // Value - An array of permissions. + Value []Permission `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` +} + +// Response returns the raw HTTP response object. +func (pgr PermissionGetResult) Response() *http.Response { + return pgr.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pgr PermissionGetResult) StatusCode() int { + return pgr.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pgr PermissionGetResult) Status() string { + return pgr.rawResponse.Status +} + +// ProviderOperation - Operation +type ProviderOperation struct { + // Name - The operation name. + Name *string `json:"name,omitempty"` + // DisplayName - The operation display name. + DisplayName *string `json:"displayName,omitempty"` + // Description - The operation description. + Description *string `json:"description,omitempty"` + // Origin - The operation origin. + Origin *string `json:"origin,omitempty"` + // Properties - The operation properties. + Properties map[string]interface{} `json:"properties,omitempty"` + // IsDataAction - The dataAction flag to specify the operation type. + IsDataAction *bool `json:"isDataAction,omitempty"` +} + +// ProviderOperationsMetadata - Provider Operations metadata +type ProviderOperationsMetadata struct { + rawResponse *http.Response + // ID - The provider id. + ID *string `json:"id,omitempty"` + // Name - The provider name. + Name *string `json:"name,omitempty"` + // Type - The provider type. + Type *string `json:"type,omitempty"` + // DisplayName - The provider display name. + DisplayName *string `json:"displayName,omitempty"` + // ResourceTypes - The provider resource types + ResourceTypes []ResourceType `json:"resourceTypes,omitempty"` + // Operations - The provider operations. + Operations []ProviderOperation `json:"operations,omitempty"` +} + +// Response returns the raw HTTP response object. +func (pom ProviderOperationsMetadata) Response() *http.Response { + return pom.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pom ProviderOperationsMetadata) StatusCode() int { + return pom.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pom ProviderOperationsMetadata) Status() string { + return pom.rawResponse.Status +} + +// ProviderOperationsMetadataListResult - Provider operations metadata list +type ProviderOperationsMetadataListResult struct { + rawResponse *http.Response + // Value - The list of providers. + Value []ProviderOperationsMetadata `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` +} + +// Response returns the raw HTTP response object. +func (pomlr ProviderOperationsMetadataListResult) Response() *http.Response { + return pomlr.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (pomlr ProviderOperationsMetadataListResult) StatusCode() int { + return pomlr.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (pomlr ProviderOperationsMetadataListResult) Status() string { + return pomlr.rawResponse.Status +} + +// ResourceType - Resource Type +type ResourceType struct { + // Name - The resource type name. + Name *string `json:"name,omitempty"` + // DisplayName - The resource type display name. + DisplayName *string `json:"displayName,omitempty"` + // Operations - The resource type operations. + Operations []ProviderOperation `json:"operations,omitempty"` +} + +// RoleAssignment - Role Assignments +type RoleAssignment struct { + rawResponse *http.Response + // ID - The role assignment ID. + ID *string `json:"id,omitempty"` + // Name - The role assignment name. + Name *string `json:"name,omitempty"` + // Type - The role assignment type. + Type *string `json:"type,omitempty"` + // Properties - Role assignment properties. + *RoleAssignmentPropertiesWithScope `json:"properties,omitempty"` +} + +// Response returns the raw HTTP response object. +func (ra RoleAssignment) Response() *http.Response { + return ra.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (ra RoleAssignment) StatusCode() int { + return ra.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (ra RoleAssignment) Status() string { + return ra.rawResponse.Status +} + +// RoleAssignmentCreateParameters - Role assignment create parameters. +type RoleAssignmentCreateParameters struct { + // Properties - Role assignment properties. + *RoleAssignmentProperties `json:"properties,omitempty"` +} + +// RoleAssignmentFilter - Role Assignments filter +type RoleAssignmentFilter struct { + // PrincipalID - Returns role assignment of the specific principal. + PrincipalID *string `json:"principalId,omitempty"` + // CanDelegate - The Delegation flag for the roleassignment + CanDelegate *bool `json:"canDelegate,omitempty"` +} + +// RoleAssignmentListResult - Role assignment list operation result. +type RoleAssignmentListResult struct { + rawResponse *http.Response + // Value - Role assignment list. + Value []RoleAssignment `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` +} + +// Response returns the raw HTTP response object. +func (ralr RoleAssignmentListResult) Response() *http.Response { + return ralr.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (ralr RoleAssignmentListResult) StatusCode() int { + return ralr.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (ralr RoleAssignmentListResult) Status() string { + return ralr.rawResponse.Status +} + +// RoleAssignmentProperties - Role assignment properties. +type RoleAssignmentProperties struct { + // RoleDefinitionID - The role definition ID used in the role assignment. + RoleDefinitionID *string `json:"roleDefinitionId,omitempty"` + // PrincipalID - The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. + PrincipalID *string `json:"principalId,omitempty"` + // CanDelegate - The delgation flag used for creating a role assignment + CanDelegate *bool `json:"canDelegate,omitempty"` +} + +// RoleAssignmentPropertiesWithScope - Role assignment properties with scope. +type RoleAssignmentPropertiesWithScope struct { + // Scope - The role assignment scope. + Scope *string `json:"scope,omitempty"` + // RoleDefinitionID - The role definition ID. + RoleDefinitionID *string `json:"roleDefinitionId,omitempty"` + // PrincipalID - The principal ID. + PrincipalID *string `json:"principalId,omitempty"` + // CanDelegate - The Delegation flag for the roleassignment + CanDelegate *bool `json:"canDelegate,omitempty"` +} + +// RoleDefinition - Role definition. +type RoleDefinition struct { + rawResponse *http.Response + // ID - The role definition ID. + ID *string `json:"id,omitempty"` + // Name - The role definition name. + Name *string `json:"name,omitempty"` + // Type - The role definition type. + Type *string `json:"type,omitempty"` + // Properties - Role definition properties. + *RoleDefinitionProperties `json:"properties,omitempty"` +} + +// Response returns the raw HTTP response object. +func (rd RoleDefinition) Response() *http.Response { + return rd.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (rd RoleDefinition) StatusCode() int { + return rd.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (rd RoleDefinition) Status() string { + return rd.rawResponse.Status +} + +// RoleDefinitionFilter - Role Definitions filter +type RoleDefinitionFilter struct { + // RoleName - Returns role definition with the specific name. + RoleName *string `json:"roleName,omitempty"` +} + +// RoleDefinitionListResult - Role definition list operation result. +type RoleDefinitionListResult struct { + rawResponse *http.Response + // Value - Role definition list. + Value []RoleDefinition `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink Marker `json:"NextLink"` +} + +// Response returns the raw HTTP response object. +func (rdlr RoleDefinitionListResult) Response() *http.Response { + return rdlr.rawResponse +} + +// StatusCode returns the HTTP status code of the response, e.g. 200. +func (rdlr RoleDefinitionListResult) StatusCode() int { + return rdlr.rawResponse.StatusCode +} + +// Status returns the HTTP status message of the response, e.g. "200 OK". +func (rdlr RoleDefinitionListResult) Status() string { + return rdlr.rawResponse.Status +} + +// RoleDefinitionProperties - Role definition properties. +type RoleDefinitionProperties struct { + // RoleName - The role name. + RoleName *string `json:"roleName,omitempty"` + // Description - The role definition description. + Description *string `json:"description,omitempty"` + // RoleType - The role type. + RoleType *string `json:"type,omitempty"` + // Permissions - Role definition permissions. + Permissions []Permission `json:"permissions,omitempty"` + // AssignableScopes - Role definition assignable scopes. + AssignableScopes []string `json:"assignableScopes,omitempty"` +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/permissions.go b/services/authorization/mgmt/2018-01-01-preview/authorization/permissions.go new file mode 100644 index 000000000000..d2e6c4ad25fe --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/permissions.go @@ -0,0 +1,144 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// PermissionsClient is the role based access control provides you a way to apply granular level policy administration +// down to individual resources or resource groups. These operations enable you to manage role definitions and role +// assignments. A role definition describes the set of actions that can be performed on resources. A role assignment +// grants access to Azure Active Directory users. +type PermissionsClient struct { + ManagementClient +} + +// NewPermissionsClient creates an instance of the PermissionsClient client. +func NewPermissionsClient(p pipeline.Pipeline) PermissionsClient { + return PermissionsClient{NewManagementClient(p)} +} + +// ListForResource gets all permissions the caller has for a resource. +// +// parentResourcePath is the parent resource identity. resourceType is the resource type of the resource. resourceName +// is the name of the resource to get the permissions for. +func (client PermissionsClient) ListForResource(ctx context.Context, parentResourcePath string, resourceType string, resourceName string) (*PermissionGetResult, error) { + req, err := client.listForResourcePreparer(parentResourcePath, resourceType, resourceName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceResponder}, req) + if err != nil { + return nil, err + } + return resp.(*PermissionGetResult), err +} + +// listForResourcePreparer prepares the ListForResource request. +func (client PermissionsClient) listForResourcePreparer(parentResourcePath string, resourceType string, resourceName string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/permissions" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceResponder handles the response to the ListForResource request. +func (client PermissionsClient) listForResourceResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &PermissionGetResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResourceGroup gets all permissions the caller has for a resource group. +func (client PermissionsClient) ListForResourceGroup(ctx context.Context) (*PermissionGetResult, error) { + req, err := client.listForResourceGroupPreparer() + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceGroupResponder}, req) + if err != nil { + return nil, err + } + return resp.(*PermissionGetResult), err +} + +// listForResourceGroupPreparer prepares the ListForResourceGroup request. +func (client PermissionsClient) listForResourceGroupPreparer() (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceGroupResponder handles the response to the ListForResourceGroup request. +func (client PermissionsClient) listForResourceGroupResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &PermissionGetResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/provider_operations_metadata.go b/services/authorization/mgmt/2018-01-01-preview/authorization/provider_operations_metadata.go new file mode 100644 index 000000000000..8b17e6c9d24e --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/provider_operations_metadata.go @@ -0,0 +1,151 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// ProviderOperationsMetadataClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type ProviderOperationsMetadataClient struct { + ManagementClient +} + +// NewProviderOperationsMetadataClient creates an instance of the ProviderOperationsMetadataClient client. +func NewProviderOperationsMetadataClient(p pipeline.Pipeline) ProviderOperationsMetadataClient { + return ProviderOperationsMetadataClient{NewManagementClient(p)} +} + +// Get gets provider operations metadata for the specified resource provider. +// +// expand is specifies whether to expand the values. +func (client ProviderOperationsMetadataClient) Get(ctx context.Context, expand *string) (*ProviderOperationsMetadata, error) { + req, err := client.getPreparer(expand) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ProviderOperationsMetadata), err +} + +// getPreparer prepares the Get request. +func (client ProviderOperationsMetadataClient) getPreparer(expand *string) (pipeline.Request, error) { + u := client.url + u.Path = "/providers/Microsoft.Authorization/providerOperations/{resourceProviderNamespace}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + if expand != nil { + params.Set("$expand", *expand) + } + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client ProviderOperationsMetadataClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ProviderOperationsMetadata{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List gets provider operations metadata for all resource providers. +// +// expand is specifies whether to expand the values. +func (client ProviderOperationsMetadataClient) List(ctx context.Context, expand *string) (*ProviderOperationsMetadataListResult, error) { + req, err := client.listPreparer(expand) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*ProviderOperationsMetadataListResult), err +} + +// listPreparer prepares the List request. +func (client ProviderOperationsMetadataClient) listPreparer(expand *string) (pipeline.Request, error) { + u := client.url + u.Path = "/providers/Microsoft.Authorization/providerOperations" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + if expand != nil { + params.Set("$expand", *expand) + } + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client ProviderOperationsMetadataClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &ProviderOperationsMetadataListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/responder_policy.go b/services/authorization/mgmt/2018-01-01-preview/authorization/responder_policy.go new file mode 100644 index 000000000000..06f946241b6e --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/responder_policy.go @@ -0,0 +1,81 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/xml" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" +) + +type responder func(resp pipeline.Response) (result pipeline.Response, err error) + +// ResponderPolicyFactory is a Factory capable of creating a responder pipeline. +type responderPolicyFactory struct { + responder responder +} + +// New creates a responder policy factory. +func (arpf responderPolicyFactory) New(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.Policy { + return responderPolicy{next: next, responder: arpf.responder} +} + +type responderPolicy struct { + next pipeline.Policy + responder responder +} + +// Do sends the request to the service and validates/deserializes the HTTP response. +func (arp responderPolicy) Do(ctx context.Context, request pipeline.Request) (pipeline.Response, error) { + resp, err := arp.next.Do(ctx, request) + if err != nil { + return resp, err + } + return arp.responder(resp) +} + +// validateResponse checks an HTTP response's status code against a legal set of codes. +// If the response code is not legal, then validateResponse reads all of the response's body +// (containing error information) and returns a response error. +func validateResponse(resp pipeline.Response, successStatusCodes ...int) error { + if resp == nil { + return NewResponseError(nil, nil, "nil response") + } + responseCode := resp.Response().StatusCode + for _, i := range successStatusCodes { + if i == responseCode { + return nil + } + } + // only close the body in the failure case. in the + // success case responders will close the body as required. + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return NewResponseError(err, resp.Response(), "failed to read response body") + } + // the service code, description and details will be populated during unmarshalling + responseError := NewResponseError(nil, resp.Response(), resp.Response().Status) + if len(b) > 0 { + if err = xml.Unmarshal(b, &responseError); err != nil { + return NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return responseError +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/response_error.go b/services/authorization/mgmt/2018-01-01-preview/authorization/response_error.go new file mode 100644 index 000000000000..3704b446893e --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/response_error.go @@ -0,0 +1,110 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "fmt" + "github.com/Azure/azure-pipeline-go/pipeline" + "net" + "net/http" +) + +// if you want to provide custom error handling set this variable to your constructor function +var responseErrorFactory func(cause error, response *http.Response, description string) error + +// ResponseError identifies a responder-generated network or response parsing error. +type ResponseError interface { + // Error exposes the Error(), Temporary() and Timeout() methods. + net.Error // Includes the Go error interface + + // Response returns the HTTP response. You may examine this but you should not modify it. + Response() *http.Response +} + +// NewResponseError creates an error object that implements the error interface. +func NewResponseError(cause error, response *http.Response, description string) error { + if responseErrorFactory != nil { + return responseErrorFactory(cause, response, description) + } + return &responseError{ + ErrorNode: pipeline.ErrorNode{}.Initialize(cause, 3), + response: response, + description: description, + } +} + +// responseError is the internal struct that implements the public ResponseError interface. +type responseError struct { + pipeline.ErrorNode // This is embedded so that responseError "inherits" Error, Temporary, Timeout, and Cause + response *http.Response + description string +} + +// Error implements the error interface's Error method to return a string representation of the error. +func (e *responseError) Error() string { + b := &bytes.Buffer{} + fmt.Fprintf(b, "===== RESPONSE ERROR (Code=%v) =====\n", e.response.StatusCode) + fmt.Fprintf(b, "Status=%s, Description: %s\n", e.response.Status, e.description) + s := b.String() + return e.ErrorNode.Error(s) +} + +// Response implements the ResponseError interface's method to return the HTTP response. +func (e *responseError) Response() *http.Response { + return e.response +} + +// RFC7807 PROBLEM ------------------------------------------------------------------------------------ +// RFC7807Problem ... This type can be publicly embedded in another type that wants to add additional members. +/*type RFC7807Problem struct { + // Mandatory: A (relative) URI reference identifying the problem type (it MAY refer to human-readable documentation). + typeURI string // Should default to "about:blank" + // Optional: Short, human-readable summary (maybe localized). + title string + // Optional: HTTP status code generated by the origin server + status int + // Optional: Human-readable explanation for this problem occurance. + // Should help client correct the problem. Clients should NOT parse this string. + detail string + // Optional: A (relative) URI identifying this specific problem occurence (it may or may not be dereferenced). + instance string +} +// NewRFC7807Problem ... +func NewRFC7807Problem(typeURI string, status int, titleFormat string, a ...interface{}) error { + return &RFC7807Problem{ + typeURI: typeURI, + status: status, + title: fmt.Sprintf(titleFormat, a...), + } +} +// Error returns the error information as a string. +func (e *RFC7807Problem) Error() string { + return e.title +} +// TypeURI ... +func (e *RFC7807Problem) TypeURI() string { + if e.typeURI == "" { + e.typeURI = "about:blank" + } + return e.typeURI +} +// Members ... +func (e *RFC7807Problem) Members() (status int, title, detail, instance string) { + return e.status, e.title, e.detail, e.instance +}*/ diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/role_assignments.go b/services/authorization/mgmt/2018-01-01-preview/authorization/role_assignments.go new file mode 100644 index 000000000000..b8378be78ad1 --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/role_assignments.go @@ -0,0 +1,615 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// RoleAssignmentsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type RoleAssignmentsClient struct { + ManagementClient +} + +// NewRoleAssignmentsClient creates an instance of the RoleAssignmentsClient client. +func NewRoleAssignmentsClient(p pipeline.Pipeline) RoleAssignmentsClient { + return RoleAssignmentsClient{NewManagementClient(p)} +} + +// Create creates a role assignment. +// +// scope is the scope of the role assignment to create. The scope can be any REST resource instance. For example, use +// '/subscriptions/{subscription-id}/' for a subscription, +// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and +// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' +// for a resource. roleAssignmentName is the name of the role assignment to create. It can be any valid GUID. +// parameters is parameters for the role assignment. +func (client RoleAssignmentsClient) Create(ctx context.Context, scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (*RoleAssignment, error) { + req, err := client.createPreparer(scope, roleAssignmentName, parameters) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// createPreparer prepares the Create request. +func (client RoleAssignmentsClient) createPreparer(scope string, roleAssignmentName string, parameters RoleAssignmentCreateParameters) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(parameters) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createResponder handles the response to the Create request. +func (client RoleAssignmentsClient) createResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// CreateByID creates a role assignment by ID. +// +// roleID is the ID of the role assignment to create. parameters is parameters for the role assignment. +func (client RoleAssignmentsClient) CreateByID(ctx context.Context, roleID string, parameters RoleAssignmentCreateParameters) (*RoleAssignment, error) { + req, err := client.createByIDPreparer(roleID, parameters) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// createByIDPreparer prepares the CreateByID request. +func (client RoleAssignmentsClient) createByIDPreparer(roleID string, parameters RoleAssignmentCreateParameters) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleId}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(parameters) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createByIDResponder handles the response to the CreateByID request. +func (client RoleAssignmentsClient) createByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Delete deletes a role assignment. +// +// scope is the scope of the role assignment to delete. roleAssignmentName is the name of the role assignment to +// delete. +func (client RoleAssignmentsClient) Delete(ctx context.Context, scope string, roleAssignmentName string) (*RoleAssignment, error) { + req, err := client.deletePreparer(scope, roleAssignmentName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// deletePreparer prepares the Delete request. +func (client RoleAssignmentsClient) deletePreparer(scope string, roleAssignmentName string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteResponder handles the response to the Delete request. +func (client RoleAssignmentsClient) deleteResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// DeleteByID deletes a role assignment. +// +// roleID is the ID of the role assignment to delete. +func (client RoleAssignmentsClient) DeleteByID(ctx context.Context, roleID string) (*RoleAssignment, error) { + req, err := client.deleteByIDPreparer(roleID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// deleteByIDPreparer prepares the DeleteByID request. +func (client RoleAssignmentsClient) deleteByIDPreparer(roleID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleId}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteByIDResponder handles the response to the DeleteByID request. +func (client RoleAssignmentsClient) deleteByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Get get the specified role assignment. +// +// scope is the scope of the role assignment. roleAssignmentName is the name of the role assignment to get. +func (client RoleAssignmentsClient) Get(ctx context.Context, scope string, roleAssignmentName string) (*RoleAssignment, error) { + req, err := client.getPreparer(scope, roleAssignmentName) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// getPreparer prepares the Get request. +func (client RoleAssignmentsClient) getPreparer(scope string, roleAssignmentName string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client RoleAssignmentsClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// GetByID gets a role assignment by ID. +// +// roleID is the ID of the role assignment to get. +func (client RoleAssignmentsClient) GetByID(ctx context.Context, roleID string) (*RoleAssignment, error) { + req, err := client.getByIDPreparer(roleID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignment), err +} + +// getByIDPreparer prepares the GetByID request. +func (client RoleAssignmentsClient) getByIDPreparer(roleID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getByIDResponder handles the response to the GetByID request. +func (client RoleAssignmentsClient) getByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignment{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List gets all role assignments for the subscription. +// +// filter is the filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the +// scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified +// principal. +func (client RoleAssignmentsClient) List(ctx context.Context, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listPreparer(filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listPreparer prepares the List request. +func (client RoleAssignmentsClient) listPreparer(filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client RoleAssignmentsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResource gets role assignments for a resource. +// +// parentResourcePath is the parent resource identity. resourceType is the resource type of the resource. resourceName +// is the name of the resource to get role assignments for. filter is the filter to apply on the operation. Use +// $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return +// all role assignments at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForResource(ctx context.Context, parentResourcePath string, resourceType string, resourceName string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForResourcePreparer(parentResourcePath, resourceType, resourceName, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForResourcePreparer prepares the ListForResource request. +func (client RoleAssignmentsClient) listForResourcePreparer(parentResourcePath string, resourceType string, resourceName string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceResponder handles the response to the ListForResource request. +func (client RoleAssignmentsClient) listForResourceResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForResourceGroup gets role assignments for a resource group. +// +// filter is the filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the +// scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified +// principal. +func (client RoleAssignmentsClient) ListForResourceGroup(ctx context.Context, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForResourceGroupPreparer(filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForResourceGroupResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForResourceGroupPreparer prepares the ListForResourceGroup request. +func (client RoleAssignmentsClient) listForResourceGroupPreparer(filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForResourceGroupResponder handles the response to the ListForResourceGroup request. +func (client RoleAssignmentsClient) listForResourceGroupResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// ListForScope gets role assignments for a scope. +// +// scope is the scope of the role assignments. filter is the filter to apply on the operation. Use $filter=atScope() to +// return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments +// at, above or below the scope for the specified principal. +func (client RoleAssignmentsClient) ListForScope(ctx context.Context, scope string, filter *string) (*RoleAssignmentListResult, error) { + req, err := client.listForScopePreparer(scope, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listForScopeResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleAssignmentListResult), err +} + +// listForScopePreparer prepares the ListForScope request. +func (client RoleAssignmentsClient) listForScopePreparer(scope string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleAssignments" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listForScopeResponder handles the response to the ListForScope request. +func (client RoleAssignmentsClient) listForScopeResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleAssignmentListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/role_definitions.go b/services/authorization/mgmt/2018-01-01-preview/authorization/role_definitions.go new file mode 100644 index 000000000000..6037fe4be6df --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/role_definitions.go @@ -0,0 +1,322 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "bytes" + "context" + "encoding/json" + "github.com/Azure/azure-pipeline-go/pipeline" + "io/ioutil" + "net/http" +) + +// RoleDefinitionsClient is the role based access control provides you a way to apply granular level policy +// administration down to individual resources or resource groups. These operations enable you to manage role +// definitions and role assignments. A role definition describes the set of actions that can be performed on resources. +// A role assignment grants access to Azure Active Directory users. +type RoleDefinitionsClient struct { + ManagementClient +} + +// NewRoleDefinitionsClient creates an instance of the RoleDefinitionsClient client. +func NewRoleDefinitionsClient(p pipeline.Pipeline) RoleDefinitionsClient { + return RoleDefinitionsClient{NewManagementClient(p)} +} + +// CreateOrUpdate creates or updates a role definition. +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. roleDefinition is the +// values for the role definition. +func (client RoleDefinitionsClient) CreateOrUpdate(ctx context.Context, scope string, roleDefinitionID string, roleDefinition RoleDefinition) (*RoleDefinition, error) { + req, err := client.createOrUpdatePreparer(scope, roleDefinitionID, roleDefinition) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.createOrUpdateResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// createOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RoleDefinitionsClient) createOrUpdatePreparer(scope string, roleDefinitionID string, roleDefinition RoleDefinition) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("PUT", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + b, err := json.Marshal(roleDefinition) + if err != nil { + return req, pipeline.NewError(err, "failed to marshal request body") + } + req.Header.Set("Content-Type", "application/json") + err = req.SetBody(bytes.NewReader(b)) + if err != nil { + return req, pipeline.NewError(err, "failed to set request body") + } + return req, nil +} + +// createOrUpdateResponder handles the response to the CreateOrUpdate request. +func (client RoleDefinitionsClient) createOrUpdateResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK, http.StatusCreated) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Delete deletes a role definition. +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition to delete. +func (client RoleDefinitionsClient) Delete(ctx context.Context, scope string, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.deletePreparer(scope, roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.deleteResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// deletePreparer prepares the Delete request. +func (client RoleDefinitionsClient) deletePreparer(scope string, roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("DELETE", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// deleteResponder handles the response to the Delete request. +func (client RoleDefinitionsClient) deleteResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// Get get role definition by name (GUID). +// +// scope is the scope of the role definition. roleDefinitionID is the ID of the role definition. +func (client RoleDefinitionsClient) Get(ctx context.Context, scope string, roleDefinitionID string) (*RoleDefinition, error) { + req, err := client.getPreparer(scope, roleDefinitionID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// getPreparer prepares the Get request. +func (client RoleDefinitionsClient) getPreparer(scope string, roleDefinitionID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getResponder handles the response to the Get request. +func (client RoleDefinitionsClient) getResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// GetByID gets a role definition by ID. +// +// roleID is the fully qualified role definition ID. Use the format, +// /subscriptions/{guid}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for subscription level +// role definitions, or /providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId} for tenant level role +// definitions. +func (client RoleDefinitionsClient) GetByID(ctx context.Context, roleID string) (*RoleDefinition, error) { + req, err := client.getByIDPreparer(roleID) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.getByIDResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinition), err +} + +// getByIDPreparer prepares the GetByID request. +func (client RoleDefinitionsClient) getByIDPreparer(roleID string) (pipeline.Request, error) { + u := client.url + u.Path = "/{roleId}" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// getByIDResponder handles the response to the GetByID request. +func (client RoleDefinitionsClient) getByIDResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinition{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} + +// List get all role definitions that are applicable at scope and above. +// +// scope is the scope of the role definition. filter is the filter to apply on the operation. Use atScopeAndBelow +// filter to search below the given scope as well. +func (client RoleDefinitionsClient) List(ctx context.Context, scope string, filter *string) (*RoleDefinitionListResult, error) { + req, err := client.listPreparer(scope, filter) + if err != nil { + return nil, err + } + resp, err := client.Pipeline().Do(ctx, responderPolicyFactory{responder: client.listResponder}, req) + if err != nil { + return nil, err + } + return resp.(*RoleDefinitionListResult), err +} + +// listPreparer prepares the List request. +func (client RoleDefinitionsClient) listPreparer(scope string, filter *string) (pipeline.Request, error) { + u := client.url + u.Path = "/{scope}/providers/Microsoft.Authorization/roleDefinitions" + req, err := pipeline.NewRequest("GET", u, nil) + if err != nil { + return req, pipeline.NewError(err, "failed to create request") + } + params := req.URL.Query() + if filter != nil { + params.Set("$filter", *filter) + } + params.Set("api-version", "2018-01-01-preview") + req.URL.RawQuery = params.Encode() + return req, nil +} + +// listResponder handles the response to the List request. +func (client RoleDefinitionsClient) listResponder(resp pipeline.Response) (pipeline.Response, error) { + err := validateResponse(resp, http.StatusOK) + if resp == nil { + return nil, err + } + result := &RoleDefinitionListResult{rawResponse: resp.Response()} + if err != nil { + return result, err + } + defer resp.Response().Body.Close() + b, err := ioutil.ReadAll(resp.Response().Body) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to read response body") + } + if len(b) > 0 { + err = json.Unmarshal(b, result) + if err != nil { + return result, NewResponseError(err, resp.Response(), "failed to unmarshal response body") + } + } + return result, nil +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/validation.go b/services/authorization/mgmt/2018-01-01-preview/authorization/validation.go new file mode 100644 index 000000000000..e44edeb29921 --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/validation.go @@ -0,0 +1,381 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "fmt" + "github.com/Azure/azure-pipeline-go/pipeline" + "reflect" + "regexp" + "strings" +) + +// Constraint stores constraint name, target field name +// Rule and chain validations. +type constraint struct { + // Target field name for validation. + target string + + // Constraint name e.g. minLength, MaxLength, Pattern, etc. + name string + + // Rule for constraint e.g. greater than 10, less than 5 etc. + rule interface{} + + // Chain validations for struct type + chain []constraint +} + +// Validation stores parameter-wise validation. +type validation struct { + targetValue interface{} + constraints []constraint +} + +// Constraint list +const ( + empty = "Empty" + null = "Null" + readOnly = "ReadOnly" + pattern = "Pattern" + maxLength = "MaxLength" + minLength = "MinLength" + maxItems = "MaxItems" + minItems = "MinItems" + multipleOf = "MultipleOf" + uniqueItems = "UniqueItems" + inclusiveMaximum = "InclusiveMaximum" + exclusiveMaximum = "ExclusiveMaximum" + exclusiveMinimum = "ExclusiveMinimum" + inclusiveMinimum = "InclusiveMinimum" +) + +// Validate method validates constraints on parameter +// passed in validation array. +func validate(m []validation) error { + for _, item := range m { + v := reflect.ValueOf(item.targetValue) + for _, constraint := range item.constraints { + var err error + switch v.Kind() { + case reflect.Ptr: + err = validatePtr(v, constraint) + case reflect.String: + err = validateString(v, constraint) + case reflect.Struct: + err = validateStruct(v, constraint) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + err = validateInt(v, constraint) + case reflect.Float32, reflect.Float64: + err = validateFloat(v, constraint) + case reflect.Array, reflect.Slice, reflect.Map: + err = validateArrayMap(v, constraint) + default: + err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) + } + if err != nil { + return err + } + } + } + return nil +} + +func validateStruct(x reflect.Value, v constraint, name ...string) error { + //Get field name from target name which is in format a.b.c + s := strings.Split(v.target, ".") + f := x.FieldByName(s[len(s)-1]) + if isZero(f) { + return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.target)) + } + err := validate([]validation{ + { + targetValue: getInterfaceValue(f), + constraints: []constraint{v}, + }, + }) + return err +} + +func validatePtr(x reflect.Value, v constraint) error { + if v.name == readOnly { + if !x.IsNil() { + return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") + } + return nil + } + if x.IsNil() { + return checkNil(x, v) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x.Elem()), + constraints: v.chain, + }, + }) + } + return nil +} + +func validateInt(x reflect.Value, v constraint) error { + i := x.Int() + r, ok := v.rule.(int) + if !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + switch v.name { + case multipleOf: + if i%int64(r) != 0 { + return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) + } + case exclusiveMinimum: + if i <= int64(r) { + return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) + } + case exclusiveMaximum: + if i >= int64(r) { + return createError(x, v, fmt.Sprintf("value must be less than %v", r)) + } + case inclusiveMinimum: + if i < int64(r) { + return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) + } + case inclusiveMaximum: + if i > int64(r) { + return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) + } + default: + return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.name)) + } + return nil +} + +func validateFloat(x reflect.Value, v constraint) error { + f := x.Float() + r, ok := v.rule.(float64) + if !ok { + return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.name, v.rule)) + } + switch v.name { + case exclusiveMinimum: + if f <= r { + return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) + } + case exclusiveMaximum: + if f >= r { + return createError(x, v, fmt.Sprintf("value must be less than %v", r)) + } + case inclusiveMinimum: + if f < r { + return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) + } + case inclusiveMaximum: + if f > r { + return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) + } + default: + return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.name)) + } + return nil +} + +func validateString(x reflect.Value, v constraint) error { + s := x.String() + switch v.name { + case empty: + if len(s) == 0 { + return checkEmpty(x, v) + } + case pattern: + reg, err := regexp.Compile(v.rule.(string)) + if err != nil { + return createError(x, v, err.Error()) + } + if !reg.MatchString(s) { + return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.rule)) + } + case maxLength: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + if len(s) > v.rule.(int) { + return createError(x, v, fmt.Sprintf("value length must be less than %v", v.rule)) + } + case minLength: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.name, v.rule)) + } + if len(s) < v.rule.(int) { + return createError(x, v, fmt.Sprintf("value length must be greater than %v", v.rule)) + } + case readOnly: + if len(s) > 0 { + return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") + } + default: + return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.name)) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x), + constraints: v.chain, + }, + }) + } + return nil +} + +func validateArrayMap(x reflect.Value, v constraint) error { + switch v.name { + case null: + if x.IsNil() { + return checkNil(x, v) + } + case empty: + if x.IsNil() || x.Len() == 0 { + return checkEmpty(x, v) + } + case maxItems: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.name, v.rule)) + } + if x.Len() > v.rule.(int) { + return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.rule, x.Len())) + } + case minItems: + if _, ok := v.rule.(int); !ok { + return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.name, v.rule)) + } + if x.Len() < v.rule.(int) { + return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.rule, x.Len())) + } + case uniqueItems: + if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { + if !checkForUniqueInArray(x) { + return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.target, x)) + } + } else if x.Kind() == reflect.Map { + if !checkForUniqueInMap(x) { + return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.target, x)) + } + } else { + return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.name, x.Kind())) + } + case readOnly: + if x.Len() != 0 { + return createError(x, v, "readonly parameter; must send as nil or empty in request") + } + case pattern: + reg, err := regexp.Compile(v.rule.(string)) + if err != nil { + return createError(x, v, err.Error()) + } + keys := x.MapKeys() + for _, k := range keys { + if !reg.MatchString(k.String()) { + return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.rule)) + } + } + default: + return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.name)) + } + if v.chain != nil { + return validate([]validation{ + { + targetValue: getInterfaceValue(x), + constraints: v.chain, + }, + }) + } + return nil +} + +func checkNil(x reflect.Value, v constraint) error { + if _, ok := v.rule.(bool); !ok { + return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.name, v.rule)) + } + if v.rule.(bool) { + return createError(x, v, "value can not be null; required parameter") + } + return nil +} + +func checkEmpty(x reflect.Value, v constraint) error { + if _, ok := v.rule.(bool); !ok { + return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.name, v.rule)) + } + if v.rule.(bool) { + return createError(x, v, "value can not be null or empty; required parameter") + } + return nil +} + +func checkForUniqueInArray(x reflect.Value) bool { + if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { + return false + } + arrOfInterface := make([]interface{}, x.Len()) + for i := 0; i < x.Len(); i++ { + arrOfInterface[i] = x.Index(i).Interface() + } + m := make(map[interface{}]bool) + for _, val := range arrOfInterface { + if m[val] { + return false + } + m[val] = true + } + return true +} + +func checkForUniqueInMap(x reflect.Value) bool { + if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { + return false + } + mapOfInterface := make(map[interface{}]interface{}, x.Len()) + keys := x.MapKeys() + for _, k := range keys { + mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() + } + m := make(map[interface{}]bool) + for _, val := range mapOfInterface { + if m[val] { + return false + } + m[val] = true + } + return true +} + +func getInterfaceValue(x reflect.Value) interface{} { + if x.Kind() == reflect.Invalid { + return nil + } + return x.Interface() +} + +func isZero(x interface{}) bool { + return x == reflect.Zero(reflect.TypeOf(x)).Interface() +} + +func createError(x reflect.Value, v constraint, message string) error { + return pipeline.NewError(nil, fmt.Sprintf("validation failed: parameter=%s constraint=%s value=%#v details: %s", + v.target, v.name, getInterfaceValue(x), message)) +} diff --git a/services/authorization/mgmt/2018-01-01-preview/authorization/version.go b/services/authorization/mgmt/2018-01-01-preview/authorization/version.go new file mode 100644 index 000000000000..9aef92a819d1 --- /dev/null +++ b/services/authorization/mgmt/2018-01-01-preview/authorization/version.go @@ -0,0 +1,28 @@ +package authorization + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/v12.2.1-beta arm-authorization/" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return "v12.2.1-beta" +}