From daf4d4b94b412b8c8b8a07d51caa72e01641e8b0 Mon Sep 17 00:00:00 2001 From: Jay Brown Date: Fri, 13 Jun 2025 19:42:24 +0000 Subject: [PATCH] Merged in feature/permit-io-demo (pull request #144) draft pr for the test demo harness for permit.io * harness working for permit.io demo * user is const * aws profile * permit import code for research * cleanup * create user tool poc * Merge branch 'main' of bitbucket.org:aarete/query-orchestration into feature/permit-io-demo * tests for user creation * add audit logs and dry-run * add tests sanity check the requested roles * update docs for delete * disable/enable users and test * more tests and make user name required only for create operations * clean up * add docs * aws tag tests * audit -> slog * attempt build fix devbox * edit * just devbox * remove lock change for merge * Merge branch 'main' of bitbucket.org:aarete/query-orchestration into feature/permit-io-demo --- cmd/cognito_test/permit.harness/demo.sh | 5 + cmd/cognito_test/permit.harness/jwt.json | 19 + cmd/cognito_test/permit.harness/main.go | 212 + cmd/cognito_test/permit.harness/readme.md | 18 + cmd/cognito_test/permit.harness/run.main.sh | 2 + cmd/cognito_test/user.creation.tool/audit.go | 141 + .../user.creation.tool/cognito-permit-sync.go | 1220 + .../user.creation.tool/cognito.go | 248 + .../user.creation.tool/disable_users_test.go | 453 + .../minimal_csv_operations_test.go | 394 + .../name_validation_test.go | 419 + cmd/cognito_test/user.creation.tool/permit.go | 626 + cmd/cognito_test/user.creation.tool/readme.md | 496 + .../user.creation.tool/run.delete.users.sh | 15 + .../user.creation.tool/run.tool.sh | 16 + .../user.creation.tool/userlifecycle_test.go | 356 + .../user.creation.tool/users.to.import.csv | 3 + .../user.creation.tool/validate_roles_test.go | 402 + devbox.json | 2 +- go.mod | 6 +- go.sum | 8 + .../cognitoidentityprovider/CHANGELOG.md | 699 + .../cognitoidentityprovider/LICENSE.txt | 202 + .../cognitoidentityprovider/api_client.go | 944 + .../api_op_AddCustomAttributes.go | 205 + .../api_op_AdminAddUserToGroup.go | 186 + .../api_op_AdminConfirmSignUp.go | 219 + .../api_op_AdminCreateUser.go | 350 + .../api_op_AdminDeleteUser.go | 179 + .../api_op_AdminDeleteUserAttributes.go | 191 + .../api_op_AdminDisableProviderForUser.go | 200 + .../api_op_AdminDisableUser.go | 183 + .../api_op_AdminEnableUser.go | 182 + .../api_op_AdminForgetDevice.go | 188 + .../api_op_AdminGetDevice.go | 195 + .../api_op_AdminGetUser.go | 243 + .../api_op_AdminInitiateAuth.go | 458 + .../api_op_AdminLinkProviderForUser.go | 235 + .../api_op_AdminListDevices.go | 209 + .../api_op_AdminListGroupsForUser.go | 299 + .../api_op_AdminListUserAuthEvents.go | 300 + .../api_op_AdminRemoveUserFromGroup.go | 189 + .../api_op_AdminResetUserPassword.go | 233 + .../api_op_AdminRespondToAuthChallenge.go | 552 + .../api_op_AdminSetUserMFAPreference.go | 201 + .../api_op_AdminSetUserPassword.go | 218 + .../api_op_AdminSetUserSettings.go | 192 + .../api_op_AdminUpdateAuthEventFeedback.go | 205 + .../api_op_AdminUpdateDeviceStatus.go | 197 + .../api_op_AdminUpdateUserAttributes.go | 262 + .../api_op_AdminUserGlobalSignOut.go | 207 + .../api_op_AssociateSoftwareToken.go | 180 + .../api_op_ChangePassword.go | 176 + .../api_op_CompleteWebAuthnRegistration.go | 165 + .../api_op_ConfirmDevice.go | 196 + .../api_op_ConfirmForgotPassword.go | 242 + .../api_op_ConfirmSignUp.go | 269 + .../api_op_CreateGroup.go | 209 + .../api_op_CreateIdentityProvider.go | 306 + .../api_op_CreateManagedLoginBranding.go | 213 + .../api_op_CreateResourceServer.go | 201 + .../api_op_CreateUserImportJob.go | 191 + .../api_op_CreateUserPool.go | 374 + .../api_op_CreateUserPoolClient.go | 484 + .../api_op_CreateUserPoolDomain.go | 229 + .../api_op_DeleteGroup.go | 178 + .../api_op_DeleteIdentityProvider.go | 177 + .../api_op_DeleteManagedLoginBranding.go | 178 + .../api_op_DeleteResourceServer.go | 180 + .../api_op_DeleteUser.go | 166 + .../api_op_DeleteUserAttributes.go | 176 + .../api_op_DeleteUserPool.go | 167 + .../api_op_DeleteUserPoolClient.go | 162 + .../api_op_DeleteUserPoolDomain.go | 164 + .../api_op_DeleteWebAuthnCredential.go | 170 + .../api_op_DescribeIdentityProvider.go | 168 + .../api_op_DescribeManagedLoginBranding.go | 173 + ...op_DescribeManagedLoginBrandingByClient.go | 173 + .../api_op_DescribeResourceServer.go | 175 + .../api_op_DescribeRiskConfiguration.go | 178 + .../api_op_DescribeUserImportJob.go | 171 + .../api_op_DescribeUserPool.go | 178 + .../api_op_DescribeUserPoolClient.go | 186 + .../api_op_DescribeUserPoolDomain.go | 177 + .../api_op_ForgetDevice.go | 171 + .../api_op_ForgotPassword.go | 256 + .../api_op_GetCSVHeader.go | 188 + .../api_op_GetDevice.go | 179 + .../api_op_GetGroup.go | 183 + .../api_op_GetIdentityProviderByIdentifier.go | 176 + .../api_op_GetLogDeliveryConfiguration.go | 179 + .../api_op_GetSigningCertificate.go | 184 + .../api_op_GetTokensFromRefreshToken.go | 214 + .../api_op_GetUICustomization.go | 172 + .../cognitoidentityprovider/api_op_GetUser.go | 196 + ...api_op_GetUserAttributeVerificationCode.go | 228 + .../api_op_GetUserAuthFactors.go | 189 + .../api_op_GetUserPoolMfaConfig.go | 216 + .../api_op_GlobalSignOut.go | 193 + .../api_op_InitiateAuth.go | 439 + .../api_op_ListDevices.go | 192 + .../api_op_ListGroups.go | 286 + .../api_op_ListIdentityProviders.go | 293 + .../api_op_ListResourceServers.go | 292 + .../api_op_ListTagsForResource.go | 162 + .../api_op_ListUserImportJobs.go | 202 + .../api_op_ListUserPoolClients.go | 292 + .../api_op_ListUserPools.go | 284 + .../api_op_ListUsers.go | 357 + .../api_op_ListUsersInGroup.go | 294 + .../api_op_ListWebAuthnCredentials.go | 189 + .../api_op_ResendConfirmationCode.go | 253 + .../api_op_RespondToAuthChallenge.go | 522 + .../api_op_RevokeToken.go | 171 + .../api_op_SetLogDeliveryConfiguration.go | 169 + .../api_op_SetRiskConfiguration.go | 208 + .../api_op_SetUICustomization.go | 197 + .../api_op_SetUserMFAPreference.go | 191 + .../api_op_SetUserPoolMfaConfig.go | 247 + .../api_op_SetUserSettings.go | 176 + .../cognitoidentityprovider/api_op_SignUp.go | 304 + .../api_op_StartUserImportJob.go | 173 + .../api_op_StartWebAuthnRegistration.go | 167 + .../api_op_StopUserImportJob.go | 173 + .../api_op_TagResource.go | 177 + .../api_op_UntagResource.go | 160 + .../api_op_UpdateAuthEventFeedback.go | 205 + .../api_op_UpdateDeviceStatus.go | 184 + .../api_op_UpdateGroup.go | 208 + .../api_op_UpdateIdentityProvider.go | 298 + .../api_op_UpdateManagedLoginBranding.go | 205 + .../api_op_UpdateResourceServer.go | 201 + .../api_op_UpdateUserAttributes.go | 245 + .../api_op_UpdateUserPool.go | 336 + .../api_op_UpdateUserPoolClient.go | 478 + .../api_op_UpdateUserPoolDomain.go | 237 + .../api_op_VerifySoftwareToken.go | 186 + .../api_op_VerifyUserAttribute.go | 185 + .../service/cognitoidentityprovider/auth.go | 499 + .../cognitoidentityprovider/deserializers.go | 29520 ++++++++++++++++ .../service/cognitoidentityprovider/doc.go | 45 + .../cognitoidentityprovider/document/doc.go | 66 + .../document/document.go | 34 + .../cognitoidentityprovider/endpoints.go | 608 + .../cognitoidentityprovider/generated.json | 151 + .../go_module_metadata.go | 6 + .../internal/document/document.go | 99 + .../internal/endpoints/endpoints.go | 716 + .../cognitoidentityprovider/options.go | 232 + .../cognitoidentityprovider/serializers.go | 11903 +++++++ .../cognitoidentityprovider/types/enums.go | 1089 + .../cognitoidentityprovider/types/errors.go | 1478 + .../cognitoidentityprovider/types/types.go | 2873 ++ .../cognitoidentityprovider/validators.go | 5409 +++ .../document/internal/serde/field.go | 293 + .../document/internal/serde/field_cache.go | 48 + .../document/internal/serde/reflect.go | 24 + .../document/internal/serde/serde.go | 100 + .../smithy-go/document/internal/serde/tags.go | 38 + .../aws/smithy-go/document/json/decoder.go | 349 + .../aws/smithy-go/document/json/doc.go | 8 + .../aws/smithy-go/document/json/encoder.go | 329 + .../aws/smithy-go/document/json/json.go | 27 + .../github.com/permitio/permit-golang/LICENSE | 21 + .../permitio/permit-golang/pkg/api/api.go | 214 + .../permit-golang/pkg/api/condition_sets.go | 257 + .../permit-golang/pkg/api/elements.go | 45 + .../permit-golang/pkg/api/environments.go | 152 + .../permit-golang/pkg/api/implicitGrants.go | 114 + .../permit-golang/pkg/api/projects.go | 143 + .../permit-golang/pkg/api/proxyConfig.go | 143 + .../pkg/api/relationshipTuples.go | 226 + .../pkg/api/resourceActionGroups.go | 169 + .../permit-golang/pkg/api/resourceActions.go | 171 + .../pkg/api/resourceInstances.go | 232 + .../pkg/api/resourceRelations.go | 158 + .../permit-golang/pkg/api/resourceRoles.go | 372 + .../permit-golang/pkg/api/resources.go | 187 + .../pkg/api/resoureAttributes.go | 141 + .../permit-golang/pkg/api/roleAssignments.go | 99 + .../permitio/permit-golang/pkg/api/roles.go | 300 + .../permitio/permit-golang/pkg/api/tenants.go | 188 + .../permitio/permit-golang/pkg/api/users.go | 349 + .../permitio/permit-golang/pkg/api/utils.go | 27 + .../permit-golang/pkg/config/builder.go | 94 + .../permit-golang/pkg/config/config.go | 101 + .../permit-golang/pkg/config/consts.go | 14 + .../permit-golang/pkg/config/context.go | 81 + .../permit-golang/pkg/config/utils.go | 24 + .../pkg/enforcement/all_tenants.go | 108 + .../pkg/enforcement/bulk_check.go | 204 + .../permit-golang/pkg/enforcement/check.go | 129 + .../permit-golang/pkg/enforcement/consts.go | 57 + .../pkg/enforcement/enforcement.go | 40 + .../permit-golang/pkg/enforcement/resource.go | 76 + .../permit-golang/pkg/enforcement/user.go | 50 + .../pkg/enforcement/user_permissions.go | 216 + .../permit-golang/pkg/enforcement/utils.go | 16 + .../permit-golang/pkg/errors/consts.go | 51 + .../permit-golang/pkg/errors/errors.go | 97 + .../permit-golang/pkg/errors/handlers.go | 36 + .../permit-golang/pkg/errors/utils.go | 16 + .../permit-golang/pkg/models/client.go | 13 + .../pkg/models/model_action_block_editable.go | 198 + .../pkg/models/model_action_block_read.go | 263 + .../permit-golang/pkg/models/model_actor.go | 175 + .../pkg/models/model_add_role_permissions.go | 107 + .../pkg/models/model_api_key_create.go | 298 + .../pkg/models/model_api_key_owner_type.go | 112 + .../pkg/models/model_api_key_read.go | 447 + .../pkg/models/model_api_key_scope_read.go | 181 + .../models/model_attribute_block_editable.go | 144 + .../pkg/models/model_attribute_block_read.go | 211 + .../pkg/models/model_attribute_type.go | 118 + .../pkg/models/model_attributes.go | 121 + .../pkg/models/model_auth_mechanism.go | 112 + .../pkg/models/model_authn_me_api_key_read.go | 305 + .../pkg/models/model_authn_me_member_read.go | 382 + .../pkg/models/model_authn_me_read.go | 106 + .../pkg/models/model_authn_me_user_read.go | 578 + .../model_bulk_role_assignment_report.go | 128 + .../model_bulk_role_un_assignment_report.go | 128 + .../pkg/models/model_condition_set_create.go | 371 + .../pkg/models/model_condition_set_data.go | 142 + .../pkg/models/model_condition_set_read.go | 576 + .../models/model_condition_set_rule_create.go | 254 + .../models/model_condition_set_rule_read.go | 369 + .../models/model_condition_set_rule_remove.go | 254 + .../pkg/models/model_condition_set_type.go | 110 + .../pkg/models/model_condition_set_update.go | 235 + .../model_copy_environment_scope_roles.go | 162 + .../pkg/models/model_data_source_config.go | 107 + .../pkg/models/model_data_source_entry.go | 263 + .../pkg/models/model_derived_role.go | 178 + .../models/model_derived_role_block_edit.go | 163 + .../models/model_derived_role_block_read.go | 191 + .../pkg/models/model_derived_role_rule.go | 196 + .../models/model_derived_role_rule_create.go | 210 + .../models/model_derived_role_rule_delete.go | 210 + .../models/model_derived_role_rule_read.go | 294 + .../pkg/models/model_dev_login.go | 107 + .../models/model_elements_config_create.go | 263 + .../pkg/models/model_elements_config_read.go | 473 + .../models/model_elements_config_update.go | 254 + .../pkg/models/model_elements_env_read.go | 107 + .../pkg/models/model_elements_env_update.go | 114 + .../models/model_elements_permission_level.go | 118 + .../pkg/models/model_elements_role_read.go | 458 + .../pkg/models/model_elements_type.go | 112 + .../pkg/models/model_elements_user_create.go | 291 + .../models/model_elements_user_role_create.go | 107 + .../models/model_elements_user_role_remove.go | 107 + .../model_embedded_login_request_output.go | 255 + .../pkg/models/model_environment_copy.go | 192 + .../models/model_environment_copy_scope.go | 232 + .../model_environment_copy_scope_filters.go | 162 + .../models/model_environment_copy_target.go | 161 + .../pkg/models/model_environment_create.go | 211 + .../pkg/models/model_environment_read.go | 362 + .../pkg/models/model_environment_stats.go | 420 + .../pkg/models/model_environment_update.go | 188 + .../pkg/models/model_failed_invite.go | 135 + .../pkg/models/model_full_data.go | 164 + .../pkg/models/model_http_validation_error.go | 113 + .../pkg/models/model_identity_read.go | 257 + .../pkg/models/model_invite_attempt_result.go | 155 + .../pkg/models/model_invite_create.go | 137 + .../pkg/models/model_invite_read.go | 325 + .../pkg/models/model_invite_status.go | 114 + .../permit-golang/pkg/models/model_jwks.go | 116 + .../permit-golang/pkg/models/model_labels.go | 135 + .../pkg/models/model_language_instructions.go | 164 + .../pkg/models/model_location_inner.go | 103 + .../pkg/models/model_login_result.go | 210 + .../pkg/models/model_mapping_rule.go | 349 + .../pkg/models/model_member_access_level.go | 112 + .../pkg/models/model_member_access_obj.go | 112 + .../permit-golang/pkg/models/model_methods.go | 120 + .../pkg/models/model_multi_invite_result.go | 143 + .../permit-golang/pkg/models/model_new.go | 254 + .../pkg/models/model_onboarding_step.go | 122 + .../pkg/models/model_opa_decision_log.go | 309 + .../pkg/models/model_opal_client.go | 287 + .../pkg/models/model_org_member_read.go | 614 + .../pkg/models/model_org_member_update.go | 151 + .../pkg/models/model_organization_create.go | 174 + .../pkg/models/model_organization_read.go | 265 + .../model_organization_read_with_api_key.go | 337 + .../pkg/models/model_organization_update.go | 151 + .../model_paginated_result_api_key_read_.go | 175 + ...el_paginated_result_condition_set_read_.go | 183 + ..._paginated_result_elements_config_read_.go | 175 + ...odel_paginated_result_opa_decision_log_.go | 175 + .../model_paginated_result_relation_read_.go | 183 + ...el_paginated_result_resource_role_read_.go | 183 + .../model_paginated_result_user_read_.go | 175 + .../pkg/models/model_parent_id.go | 85 + .../permit-golang/pkg/models/model_pdp.go | 164 + .../pkg/models/model_pdp_config_read.go | 261 + .../pkg/models/model_pdp_context.go | 204 + .../pkg/models/model_pdp_state.go | 106 + .../pkg/models/model_pdp_state_update.go | 135 + .../pkg/models/model_pdp_values.go | 164 + .../model_permission_level_role_read.go | 166 + ..._derived_role_rule__derivation_settings.go | 129 + ...__schema_opal_data__derivation_settings.go | 128 + .../pkg/models/model_policy_repo_create.go | 246 + .../pkg/models/model_policy_repo_read.go | 305 + .../pkg/models/model_policy_repo_status.go | 112 + .../pkg/models/model_programming_language.go | 116 + .../pkg/models/model_project_create.go | 285 + .../pkg/models/model_project_read.go | 406 + .../pkg/models/model_project_update.go | 225 + .../pkg/models/model_proxy_config_create.go | 248 + .../pkg/models/model_proxy_config_read.go | 417 + .../pkg/models/model_proxy_config_update.go | 237 + .../pkg/models/model_relation_block_read.go | 181 + .../pkg/models/model_relation_create.go | 209 + .../pkg/models/model_relation_read.go | 462 + .../model_relationship_tuple_block_read.go | 172 + .../models/model_relationship_tuple_create.go | 209 + ...elationship_tuple_create_bulk_operation.go | 115 + .../models/model_relationship_tuple_delete.go | 172 + ...elationship_tuple_delete_bulk_operation.go | 115 + .../models/model_relationship_tuple_obj.go | 169 + .../models/model_relationship_tuple_read.go | 625 + .../pkg/models/model_remote_config.go | 211 + .../models/model_remove_role_permissions.go | 107 + .../models/model_resource_action_create.go | 218 + .../model_resource_action_group_create.go | 254 + .../model_resource_action_group_read.go | 451 + .../pkg/models/model_resource_action_read.go | 443 + .../models/model_resource_action_update.go | 199 + .../models/model_resource_attribute_create.go | 174 + .../models/model_resource_attribute_read.go | 415 + .../models/model_resource_attribute_update.go | 151 + .../pkg/models/model_resource_create.go | 278 + .../pkg/models/model_resource_id.go | 85 + .../model_resource_instance_block_read.go | 209 + .../models/model_resource_instance_create.go | 211 + .../models/model_resource_instance_read.go | 459 + .../models/model_resource_instance_update.go | 114 + .../pkg/models/model_resource_read.go | 466 + .../pkg/models/model_resource_replace.go | 248 + .../pkg/models/model_resource_role_create.go | 248 + .../pkg/models/model_resource_role_list.go | 115 + .../pkg/models/model_resource_role_read.go | 495 + .../pkg/models/model_resource_role_update.go | 225 + .../pkg/models/model_resource_sets.go | 162 + .../pkg/models/model_resource_update.go | 262 + .../pkg/models/model_resources.go | 162 + ...a__proj_id___env_id__condition_sets_get.go | 103 + ..._proj_id___env_id__role_assignments_get.go | 103 + .../models/model_role_assignment_create.go | 253 + .../model_role_assignment_detailed_read.go | 397 + .../pkg/models/model_role_assignment_read.go | 522 + .../models/model_role_assignment_remove.go | 252 + ...model_role_assignment_resource_instance.go | 248 + .../pkg/models/model_role_assignment_role.go | 142 + .../models/model_role_assignment_tenant.go | 205 + .../pkg/models/model_role_assignment_user.go | 286 + .../pkg/models/model_role_block.go | 188 + .../pkg/models/model_role_create.go | 267 + .../pkg/models/model_role_data.go | 113 + .../pkg/models/model_role_read.go | 438 + .../pkg/models/model_role_update.go | 244 + .../permit-golang/pkg/models/model_roles.go | 103 + .../permit-golang/pkg/models/model_scope.go | 232 + .../pkg/models/model_settings.go | 121 + .../pkg/models/model_ssh_auth_data.go | 214 + .../pkg/models/model_statistics.go | 251 + .../model_stripped_relation_block_read.go | 181 + .../pkg/models/model_target_env.go | 161 + .../pkg/models/model_tenant_block_read.go | 218 + .../pkg/models/model_tenant_create.go | 211 + .../pkg/models/model_tenant_read.go | 422 + .../pkg/models/model_tenant_update.go | 188 + .../pkg/models/model_user_create.go | 255 + .../pkg/models/model_user_data.go | 149 + .../models/model_user_login_request_input.go | 137 + .../pkg/models/model_user_read.go | 411 + .../pkg/models/model_user_role.go | 137 + .../pkg/models/model_user_role_create.go | 223 + .../pkg/models/model_user_role_remove.go | 174 + .../pkg/models/model_user_sets.go | 162 + .../pkg/models/model_user_update.go | 225 + .../pkg/models/model_validation_error.go | 164 + .../pkg/models/model_webhook_create.go | 144 + .../pkg/models/model_webhook_read.go | 288 + .../pkg/models/model_webhook_update.go | 151 + .../permit-golang/pkg/models/utils.go | 347 + .../permit-golang/pkg/openapi/api_api_keys.go | 715 + .../pkg/openapi/api_authentication.go | 916 + .../pkg/openapi/api_condition_set_rules.go | 445 + .../pkg/openapi/api_condition_sets.go | 1104 + .../pkg/openapi/api_decision_logs.go | 231 + .../pkg/openapi/api_decision_logs_ingress.go | 132 + .../permit-golang/pkg/openapi/api_default.go | 533 + .../pkg/openapi/api_elements_configs.go | 899 + .../pkg/openapi/api_elements_data.go | 955 + .../pkg/openapi/api_environments.go | 895 + .../pkg/openapi/api_implicit_grants.go | 441 + .../pkg/openapi/api_instructions.go | 142 + .../permit-golang/pkg/openapi/api_members.go | 612 + .../pkg/openapi/api_opal_data.go | 531 + .../pkg/openapi/api_organizations.go | 1113 + .../permit-golang/pkg/openapi/api_policy.go | 257 + .../pkg/openapi/api_policy_decision_points.go | 654 + .../openapi/api_policy_git_repositories.go | 858 + .../permit-golang/pkg/openapi/api_projects.go | 616 + .../pkg/openapi/api_proxy_config.go | 666 + .../pkg/openapi/api_relationship_tuples.go | 751 + .../pkg/openapi/api_resource_action_groups.go | 547 + .../pkg/openapi/api_resource_actions.go | 692 + .../pkg/openapi/api_resource_attributes.go | 700 + .../pkg/openapi/api_resource_instances.go | 739 + .../pkg/openapi/api_resource_relations.go | 569 + .../pkg/openapi/api_resource_roles.go | 1555 + .../pkg/openapi/api_resources.go | 816 + .../pkg/openapi/api_role_assignments.go | 771 + .../permit-golang/pkg/openapi/api_roles.go | 1208 + .../permit-golang/pkg/openapi/api_tenants.go | 946 + .../pkg/openapi/api_user_attributes.go | 725 + .../permit-golang/pkg/openapi/api_users.go | 1074 + .../permit-golang/pkg/openapi/client.go | 742 + .../pkg/openapi/configuration.go | 229 + .../permit-golang/pkg/openapi/response.go | 47 + .../permit-golang/pkg/permit/permit.go | 67 + vendor/go.uber.org/zap/.codecov.yml | 17 + vendor/go.uber.org/zap/.gitignore | 32 + vendor/go.uber.org/zap/.golangci.yml | 77 + vendor/go.uber.org/zap/.readme.tmpl | 109 + vendor/go.uber.org/zap/CHANGELOG.md | 671 + vendor/go.uber.org/zap/CODE_OF_CONDUCT.md | 75 + vendor/go.uber.org/zap/CONTRIBUTING.md | 70 + vendor/go.uber.org/zap/FAQ.md | 164 + vendor/go.uber.org/zap/LICENSE.txt | 19 + vendor/go.uber.org/zap/Makefile | 76 + vendor/go.uber.org/zap/README.md | 137 + vendor/go.uber.org/zap/array.go | 447 + vendor/go.uber.org/zap/buffer/buffer.go | 146 + vendor/go.uber.org/zap/buffer/pool.go | 53 + vendor/go.uber.org/zap/checklicense.sh | 17 + vendor/go.uber.org/zap/config.go | 330 + vendor/go.uber.org/zap/doc.go | 117 + vendor/go.uber.org/zap/encoder.go | 79 + vendor/go.uber.org/zap/error.go | 82 + vendor/go.uber.org/zap/field.go | 613 + vendor/go.uber.org/zap/flag.go | 39 + vendor/go.uber.org/zap/glide.yaml | 34 + vendor/go.uber.org/zap/global.go | 169 + vendor/go.uber.org/zap/http_handler.go | 140 + .../zap/internal/bufferpool/bufferpool.go | 31 + .../go.uber.org/zap/internal/color/color.go | 44 + vendor/go.uber.org/zap/internal/exit/exit.go | 66 + .../go.uber.org/zap/internal/level_enabler.go | 37 + vendor/go.uber.org/zap/internal/pool/pool.go | 58 + .../zap/internal/stacktrace/stack.go | 181 + vendor/go.uber.org/zap/level.go | 153 + vendor/go.uber.org/zap/logger.go | 432 + vendor/go.uber.org/zap/options.go | 167 + vendor/go.uber.org/zap/sink.go | 180 + vendor/go.uber.org/zap/sugar.go | 437 + vendor/go.uber.org/zap/time.go | 27 + vendor/go.uber.org/zap/writer.go | 98 + .../zap/zapcore/buffered_write_syncer.go | 219 + vendor/go.uber.org/zap/zapcore/clock.go | 48 + .../zap/zapcore/console_encoder.go | 157 + vendor/go.uber.org/zap/zapcore/core.go | 122 + vendor/go.uber.org/zap/zapcore/doc.go | 24 + vendor/go.uber.org/zap/zapcore/encoder.go | 451 + vendor/go.uber.org/zap/zapcore/entry.go | 298 + vendor/go.uber.org/zap/zapcore/error.go | 136 + vendor/go.uber.org/zap/zapcore/field.go | 233 + vendor/go.uber.org/zap/zapcore/hook.go | 77 + .../go.uber.org/zap/zapcore/increase_level.go | 75 + .../go.uber.org/zap/zapcore/json_encoder.go | 583 + vendor/go.uber.org/zap/zapcore/lazy_with.go | 54 + vendor/go.uber.org/zap/zapcore/level.go | 229 + .../go.uber.org/zap/zapcore/level_strings.go | 46 + vendor/go.uber.org/zap/zapcore/marshaler.go | 61 + .../go.uber.org/zap/zapcore/memory_encoder.go | 179 + .../zap/zapcore/reflected_encoder.go | 41 + vendor/go.uber.org/zap/zapcore/sampler.go | 229 + vendor/go.uber.org/zap/zapcore/tee.go | 96 + .../go.uber.org/zap/zapcore/write_syncer.go | 122 + vendor/golang.org/x/net/context/context.go | 144 + vendor/golang.org/x/oauth2/.travis.yml | 13 + vendor/golang.org/x/oauth2/CONTRIBUTING.md | 26 + vendor/golang.org/x/oauth2/LICENSE | 27 + vendor/golang.org/x/oauth2/README.md | 35 + vendor/golang.org/x/oauth2/deviceauth.go | 198 + vendor/golang.org/x/oauth2/internal/doc.go | 6 + vendor/golang.org/x/oauth2/internal/oauth2.go | 37 + vendor/golang.org/x/oauth2/internal/token.go | 352 + .../golang.org/x/oauth2/internal/transport.go | 28 + vendor/golang.org/x/oauth2/oauth2.go | 421 + vendor/golang.org/x/oauth2/pkce.go | 68 + vendor/golang.org/x/oauth2/token.go | 212 + vendor/golang.org/x/oauth2/transport.go | 89 + vendor/modules.txt | 34 + 501 files changed, 171268 insertions(+), 2 deletions(-) create mode 100755 cmd/cognito_test/permit.harness/demo.sh create mode 100644 cmd/cognito_test/permit.harness/jwt.json create mode 100644 cmd/cognito_test/permit.harness/main.go create mode 100644 cmd/cognito_test/permit.harness/readme.md create mode 100755 cmd/cognito_test/permit.harness/run.main.sh create mode 100644 cmd/cognito_test/user.creation.tool/audit.go create mode 100644 cmd/cognito_test/user.creation.tool/cognito-permit-sync.go create mode 100644 cmd/cognito_test/user.creation.tool/cognito.go create mode 100644 cmd/cognito_test/user.creation.tool/disable_users_test.go create mode 100644 cmd/cognito_test/user.creation.tool/minimal_csv_operations_test.go create mode 100644 cmd/cognito_test/user.creation.tool/name_validation_test.go create mode 100644 cmd/cognito_test/user.creation.tool/permit.go create mode 100644 cmd/cognito_test/user.creation.tool/readme.md create mode 100755 cmd/cognito_test/user.creation.tool/run.delete.users.sh create mode 100755 cmd/cognito_test/user.creation.tool/run.tool.sh create mode 100644 cmd/cognito_test/user.creation.tool/userlifecycle_test.go create mode 100644 cmd/cognito_test/user.creation.tool/users.to.import.csv create mode 100644 cmd/cognito_test/user.creation.tool/validate_roles_test.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/CHANGELOG.md create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/LICENSE.txt create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_client.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AddCustomAttributes.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminAddUserToGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminConfirmSignUp.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminCreateUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUserAttributes.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableProviderForUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminEnableUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminForgetDevice.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetDevice.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminInitiateAuth.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminLinkProviderForUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListDevices.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListGroupsForUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListUserAuthEvents.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRemoveUserFromGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminResetUserPassword.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRespondToAuthChallenge.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserMFAPreference.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserPassword.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserSettings.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateAuthEventFeedback.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateDeviceStatus.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateUserAttributes.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUserGlobalSignOut.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AssociateSoftwareToken.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ChangePassword.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CompleteWebAuthnRegistration.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmDevice.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmForgotPassword.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmSignUp.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateIdentityProvider.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateManagedLoginBranding.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateResourceServer.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserImportJob.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPool.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolClient.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolDomain.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteIdentityProvider.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteManagedLoginBranding.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteResourceServer.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserAttributes.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPool.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolClient.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolDomain.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteWebAuthnCredential.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeIdentityProvider.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBranding.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBrandingByClient.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeResourceServer.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeRiskConfiguration.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserImportJob.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPool.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolClient.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolDomain.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgetDevice.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgotPassword.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetCSVHeader.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetDevice.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetIdentityProviderByIdentifier.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetLogDeliveryConfiguration.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetSigningCertificate.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetTokensFromRefreshToken.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUICustomization.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUser.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAttributeVerificationCode.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAuthFactors.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserPoolMfaConfig.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GlobalSignOut.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_InitiateAuth.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListDevices.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListGroups.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListIdentityProviders.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListResourceServers.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListTagsForResource.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserImportJobs.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPoolClients.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPools.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsers.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsersInGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListWebAuthnCredentials.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ResendConfirmationCode.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RespondToAuthChallenge.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RevokeToken.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetLogDeliveryConfiguration.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetRiskConfiguration.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUICustomization.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserMFAPreference.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserPoolMfaConfig.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserSettings.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SignUp.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartUserImportJob.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartWebAuthnRegistration.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StopUserImportJob.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_TagResource.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UntagResource.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateAuthEventFeedback.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateDeviceStatus.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateGroup.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateIdentityProvider.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateManagedLoginBranding.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateResourceServer.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserAttributes.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPool.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolClient.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolDomain.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifySoftwareToken.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifyUserAttribute.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/auth.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/deserializers.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/doc.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/doc.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/document.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/endpoints.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/generated.json create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/go_module_metadata.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document/document.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/endpoints/endpoints.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/options.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/serializers.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/enums.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/errors.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/types.go create mode 100644 vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/validators.go create mode 100644 vendor/github.com/aws/smithy-go/document/internal/serde/field.go create mode 100644 vendor/github.com/aws/smithy-go/document/internal/serde/field_cache.go create mode 100644 vendor/github.com/aws/smithy-go/document/internal/serde/reflect.go create mode 100644 vendor/github.com/aws/smithy-go/document/internal/serde/serde.go create mode 100644 vendor/github.com/aws/smithy-go/document/internal/serde/tags.go create mode 100644 vendor/github.com/aws/smithy-go/document/json/decoder.go create mode 100644 vendor/github.com/aws/smithy-go/document/json/doc.go create mode 100644 vendor/github.com/aws/smithy-go/document/json/encoder.go create mode 100644 vendor/github.com/aws/smithy-go/document/json/json.go create mode 100644 vendor/github.com/permitio/permit-golang/LICENSE create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/api.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/condition_sets.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/elements.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/environments.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/implicitGrants.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/projects.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/proxyConfig.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/relationshipTuples.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resourceActionGroups.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resourceActions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resourceInstances.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resourceRelations.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resourceRoles.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resources.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/resoureAttributes.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/roleAssignments.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/roles.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/tenants.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/users.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/api/utils.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/config/builder.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/config/config.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/config/consts.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/config/context.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/config/utils.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/all_tenants.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/bulk_check.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/check.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/consts.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/enforcement.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/resource.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/user.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/user_permissions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/enforcement/utils.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/errors/consts.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/errors/errors.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/errors/handlers.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/errors/utils.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/client.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_editable.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_actor.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_add_role_permissions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_owner_type.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_scope_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_editable.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_type.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_attributes.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_auth_mechanism.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_api_key_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_member_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_user_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_assignment_report.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_un_assignment_report.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_remove.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_type.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_copy_environment_scope_roles.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_config.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_entry.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_edit.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_delete.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_dev_login.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_permission_level.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_role_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_type.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_remove.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_embedded_login_request_output.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope_filters.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_target.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_stats.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_environment_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_failed_invite.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_full_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_http_validation_error.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_identity_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_invite_attempt_result.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_invite_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_invite_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_invite_status.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_jwks.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_labels.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_language_instructions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_location_inner.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_login_result.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_mapping_rule.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_level.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_obj.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_methods.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_multi_invite_result.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_new.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_onboarding_step.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_opa_decision_log.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_opal_client.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_organization_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read_with_api_key.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_organization_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_api_key_read_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_condition_set_read_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_elements_config_read_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_opa_decision_log_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_relation_read_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_resource_role_read_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_user_read_.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_parent_id.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_pdp.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_config_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_context.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_values.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_permission_level_role_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_derived_role_rule__derivation_settings.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_opal_data__derivation_settings.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_status.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_programming_language.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_project_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_project_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_project_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relation_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relation_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relation_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create_bulk_operation.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete_bulk_operation.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_obj.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_remote_config.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_remove_role_permissions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_id.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_replace.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_list.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_sets.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resource_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_resources.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_condition_sets_v2_schema__proj_id___env_id__condition_sets_get.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_role_assignments_v2_facts__proj_id___env_id__role_assignments_get.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_detailed_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_remove.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_resource_instance.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_role.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_tenant.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_user.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_block.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_role_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_roles.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_scope.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_settings.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_ssh_auth_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_statistics.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_stripped_relation_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_target_env.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_block_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_login_request_input.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_role.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_remove.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_sets.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_user_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_validation_error.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_create.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_read.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_update.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/models/utils.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_api_keys.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_authentication.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_set_rules.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_sets.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs_ingress.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_default.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_configs.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_environments.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_implicit_grants.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_instructions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_members.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_opal_data.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_organizations.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_decision_points.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_git_repositories.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_projects.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_proxy_config.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_relationship_tuples.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_action_groups.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_actions.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_attributes.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_instances.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_relations.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_roles.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_resources.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_role_assignments.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_roles.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_tenants.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_user_attributes.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/api_users.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/client.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/configuration.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/openapi/response.go create mode 100644 vendor/github.com/permitio/permit-golang/pkg/permit/permit.go create mode 100644 vendor/go.uber.org/zap/.codecov.yml create mode 100644 vendor/go.uber.org/zap/.gitignore create mode 100644 vendor/go.uber.org/zap/.golangci.yml create mode 100644 vendor/go.uber.org/zap/.readme.tmpl create mode 100644 vendor/go.uber.org/zap/CHANGELOG.md create mode 100644 vendor/go.uber.org/zap/CODE_OF_CONDUCT.md create mode 100644 vendor/go.uber.org/zap/CONTRIBUTING.md create mode 100644 vendor/go.uber.org/zap/FAQ.md create mode 100644 vendor/go.uber.org/zap/LICENSE.txt create mode 100644 vendor/go.uber.org/zap/Makefile create mode 100644 vendor/go.uber.org/zap/README.md create mode 100644 vendor/go.uber.org/zap/array.go create mode 100644 vendor/go.uber.org/zap/buffer/buffer.go create mode 100644 vendor/go.uber.org/zap/buffer/pool.go create mode 100644 vendor/go.uber.org/zap/checklicense.sh create mode 100644 vendor/go.uber.org/zap/config.go create mode 100644 vendor/go.uber.org/zap/doc.go create mode 100644 vendor/go.uber.org/zap/encoder.go create mode 100644 vendor/go.uber.org/zap/error.go create mode 100644 vendor/go.uber.org/zap/field.go create mode 100644 vendor/go.uber.org/zap/flag.go create mode 100644 vendor/go.uber.org/zap/glide.yaml create mode 100644 vendor/go.uber.org/zap/global.go create mode 100644 vendor/go.uber.org/zap/http_handler.go create mode 100644 vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go create mode 100644 vendor/go.uber.org/zap/internal/color/color.go create mode 100644 vendor/go.uber.org/zap/internal/exit/exit.go create mode 100644 vendor/go.uber.org/zap/internal/level_enabler.go create mode 100644 vendor/go.uber.org/zap/internal/pool/pool.go create mode 100644 vendor/go.uber.org/zap/internal/stacktrace/stack.go create mode 100644 vendor/go.uber.org/zap/level.go create mode 100644 vendor/go.uber.org/zap/logger.go create mode 100644 vendor/go.uber.org/zap/options.go create mode 100644 vendor/go.uber.org/zap/sink.go create mode 100644 vendor/go.uber.org/zap/sugar.go create mode 100644 vendor/go.uber.org/zap/time.go create mode 100644 vendor/go.uber.org/zap/writer.go create mode 100644 vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go create mode 100644 vendor/go.uber.org/zap/zapcore/clock.go create mode 100644 vendor/go.uber.org/zap/zapcore/console_encoder.go create mode 100644 vendor/go.uber.org/zap/zapcore/core.go create mode 100644 vendor/go.uber.org/zap/zapcore/doc.go create mode 100644 vendor/go.uber.org/zap/zapcore/encoder.go create mode 100644 vendor/go.uber.org/zap/zapcore/entry.go create mode 100644 vendor/go.uber.org/zap/zapcore/error.go create mode 100644 vendor/go.uber.org/zap/zapcore/field.go create mode 100644 vendor/go.uber.org/zap/zapcore/hook.go create mode 100644 vendor/go.uber.org/zap/zapcore/increase_level.go create mode 100644 vendor/go.uber.org/zap/zapcore/json_encoder.go create mode 100644 vendor/go.uber.org/zap/zapcore/lazy_with.go create mode 100644 vendor/go.uber.org/zap/zapcore/level.go create mode 100644 vendor/go.uber.org/zap/zapcore/level_strings.go create mode 100644 vendor/go.uber.org/zap/zapcore/marshaler.go create mode 100644 vendor/go.uber.org/zap/zapcore/memory_encoder.go create mode 100644 vendor/go.uber.org/zap/zapcore/reflected_encoder.go create mode 100644 vendor/go.uber.org/zap/zapcore/sampler.go create mode 100644 vendor/go.uber.org/zap/zapcore/tee.go create mode 100644 vendor/go.uber.org/zap/zapcore/write_syncer.go create mode 100644 vendor/golang.org/x/net/context/context.go create mode 100644 vendor/golang.org/x/oauth2/.travis.yml create mode 100644 vendor/golang.org/x/oauth2/CONTRIBUTING.md create mode 100644 vendor/golang.org/x/oauth2/LICENSE create mode 100644 vendor/golang.org/x/oauth2/README.md create mode 100644 vendor/golang.org/x/oauth2/deviceauth.go create mode 100644 vendor/golang.org/x/oauth2/internal/doc.go create mode 100644 vendor/golang.org/x/oauth2/internal/oauth2.go create mode 100644 vendor/golang.org/x/oauth2/internal/token.go create mode 100644 vendor/golang.org/x/oauth2/internal/transport.go create mode 100644 vendor/golang.org/x/oauth2/oauth2.go create mode 100644 vendor/golang.org/x/oauth2/pkce.go create mode 100644 vendor/golang.org/x/oauth2/token.go create mode 100644 vendor/golang.org/x/oauth2/transport.go diff --git a/cmd/cognito_test/permit.harness/demo.sh b/cmd/cognito_test/permit.harness/demo.sh new file mode 100755 index 00000000..67b5ccdd --- /dev/null +++ b/cmd/cognito_test/permit.harness/demo.sh @@ -0,0 +1,5 @@ +docker run -it \ + -p 7766:7000 \ + --env PDP_API_KEY=permit_key_get-this-value-from-jay \ + --env PDP_DEBUG=True \ + permitio/pdp-v2:latest diff --git a/cmd/cognito_test/permit.harness/jwt.json b/cmd/cognito_test/permit.harness/jwt.json new file mode 100644 index 00000000..977c5959 --- /dev/null +++ b/cmd/cognito_test/permit.harness/jwt.json @@ -0,0 +1,19 @@ +{ + "sub": "e12bb510-30e1-7062-a69a-ca7f3f38d80e", + "cognito:groups": [ + "uploaders", + "querybuilders" + ], + "iss": "https://cognito-idp.us-east-2.amazonaws.com/us-east-2_1y6po8rR8", + "version": 2, + "client_id": "552cqkf3640t39ncehkmgpce31", + "origin_jti": "0750d18e-8588-4d12-acbd-754d7279f317", + "event_id": "89841577-8dd9-4cd4-a698-a890393305ff", + "token_use": "access", + "scope": "openid profile email", + "auth_time": 1747326253, + "exp": 1747329853, + "iat": 1747326253, + "jti": "739302f1-7334-4718-b124-b51fb958af9a", + "username": "testuser" +} \ No newline at end of file diff --git a/cmd/cognito_test/permit.harness/main.go b/cmd/cognito_test/permit.harness/main.go new file mode 100644 index 00000000..223e28e9 --- /dev/null +++ b/cmd/cognito_test/permit.harness/main.go @@ -0,0 +1,212 @@ +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "time" + + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/enforcement" + "github.com/permitio/permit-golang/pkg/permit" +) + +const ( + port = 4000 + readTimeout = 10 * time.Second + writeTimeout = 30 * time.Second + idleTimeout = 120 * time.Second + + // This is the subject value from our JWT once we have authenticated. + // Also found in the cognito user pool for the testuser. + testUserSubject = "e12bb510-30e1-7062-a69a-ca7f3f38d80e" +) + +func main() { + // Get Permit.io key from environment variable + permitKey := os.Getenv("PERMIT_IO_KEY") + if permitKey == "" { + log.Fatal("PERMIT_IO_KEY environment variable is not set") + } + + // Initialize the Permit.io SDK + permitClient := initPermitClient(permitKey) + + // Set up routes + mux := setupRoutes(permitClient) + + // Start server with timeout settings + startServer(port, mux) +} + +// initPermitClient initializes and returns the Permit.io client +func initPermitClient(permitKey string) *permit.Client { + return permit.NewPermit( + config.NewConfigBuilder(permitKey). + WithPdpUrl("https://cloudpdp.api.permit.io"). + Build(), + ) +} + +// setupRoutes configures and returns the HTTP routes +func setupRoutes(permitClient *permit.Client) *http.ServeMux { + mux := http.NewServeMux() + + // Register the endpoints + mux.HandleFunc("/query-endpoint", createPermissionHandler(permitClient, "query-endpoint")) + mux.HandleFunc("/admin-stuff", createPermissionHandler(permitClient, "admin-stuff")) + mux.HandleFunc("/", createHomeHandler()) + + return mux +} + +// createHomeHandler returns the handler function for the root path +func createHomeHandler() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/html") + _, err := w.Write([]byte(` + + + + Permit.io Test Harness + + + +

Permit.io Test Harness

+

Available endpoints:

+ Query Endpoint - Read Action + Query Endpoint - Write Action + Admin Stuff - Read Action + Admin Stuff - Write Action + + + `)) + if err != nil { + log.Printf("Error writing response: %v", err) + } + } +} + +// createPermissionHandler creates a handler function for permission checks +func createPermissionHandler(permitClient *permit.Client, resourceType string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // Get and validate the action parameter + action, err := validateActionParam(r) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + _, writeErr := w.Write([]byte(err.Error())) + if writeErr != nil { + log.Printf("Error writing response: %v", writeErr) + } + return + } + + // Check permission + permitted, err := checkPermission(permitClient, testUserSubject, action, resourceType) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + _, writeErr := w.Write([]byte(fmt.Sprintf("Error checking permissions: %v", err))) + if writeErr != nil { + log.Printf("Error writing response: %v", writeErr) + } + return + } + + // Determine response status and color + status, httpStatus, backgroundColor := getResponseStatus(permitted) + + // Render the HTML response + renderHTMLResponse(w, resourceType, action, status, httpStatus, backgroundColor) + } +} + +// validateActionParam extracts and validates the action parameter from the request +func validateActionParam(r *http.Request) (string, error) { + action := r.URL.Query().Get("action") + if action == "" { + return "", fmt.Errorf("Missing 'action' parameter") + } + return action, nil +} + +// checkPermission performs the permission check using the Permit.io client +func checkPermission(permitClient *permit.Client, userID string, action string, resourceType string) (bool, error) { + // Create user for permission check + user := enforcement.UserBuilder(userID).Build() + + // Create resource based on the endpoint + resource := enforcement.ResourceBuilder(resourceType).Build() + + // Check permission + return permitClient.Check(user, enforcement.Action(action), resource) +} + +// getResponseStatus determines the response status based on permission result +func getResponseStatus(permitted bool) (string, int, string) { + if permitted { + return "PERMITTED *********** OK ", http.StatusOK, "#d4ffcc" // Light green + } + return "NOT PERMITTED", http.StatusForbidden, "#ffcccc" // Light red +} + +// renderHTMLResponse generates and sends the HTML response +func renderHTMLResponse(w http.ResponseWriter, resourceType, action, status string, httpStatus int, backgroundColor string) { + w.WriteHeader(httpStatus) + w.Header().Set("Content-Type", "text/html") + html := fmt.Sprintf(` + + + + Permit.io Test Result + + + +

Permission Check Result

+

Action '%s' on endpoint '%s' was %s

+

Back to home

+ + + `, backgroundColor, action, resourceType, status) + _, err := w.Write([]byte(html)) + if err != nil { + log.Printf("Error writing response: %v", err) + } +} + +// startServer starts the HTTP server with proper timeout settings +func startServer(port int, handler http.Handler) { + // Create a server with timeout settings + server := &http.Server{ + Addr: fmt.Sprintf(":%d", port), + Handler: handler, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + IdleTimeout: idleTimeout, + } + + // Start the server + fmt.Printf("Listening on http://localhost:%d\n", port) + if err := server.ListenAndServe(); err != nil { + log.Fatalf("Server error: %v", err) + } +} diff --git a/cmd/cognito_test/permit.harness/readme.md b/cmd/cognito_test/permit.harness/readme.md new file mode 100644 index 00000000..eda3e21b --- /dev/null +++ b/cmd/cognito_test/permit.harness/readme.md @@ -0,0 +1,18 @@ +# running the demo +start the permit.io serice +`./demo.sh` + +# run the go harness +`./run.main.sh` + +# load the main page +load this page and select your actions to test permissions +http://localhost:4000/ + +# edit the permissions +go to the permissions editor and change rights then re-try on the harness +https://app.permit.io/policy-editor + +# example jwt token +See the `jwt.json` file to see the contents of a typical bearer jwt token (decrypted) +to see how the subject (sub) id is identified. \ No newline at end of file diff --git a/cmd/cognito_test/permit.harness/run.main.sh b/cmd/cognito_test/permit.harness/run.main.sh new file mode 100755 index 00000000..30e30bc7 --- /dev/null +++ b/cmd/cognito_test/permit.harness/run.main.sh @@ -0,0 +1,2 @@ +export PERMIT_IO_KEY="permit_key_get_this_value_from_jay_for_demo" +go run ./... diff --git a/cmd/cognito_test/user.creation.tool/audit.go b/cmd/cognito_test/user.creation.tool/audit.go new file mode 100644 index 00000000..3ce751dc --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/audit.go @@ -0,0 +1,141 @@ +// audit.go provides comprehensive audit trail logging functionality for compliance and monitoring. +// This file now uses the `log/slog` structured logging package introduced in Go 1.21. +// A single environment variable LOG_FORMAT controls the output format: +// +// LOG_FORMAT=text -> human‑readable text (default) +// LOG_FORMAT=json -> JSON +// +// The public API (type AuditLogger and all its methods) is unchanged, so no call‑sites +// (e.g. cognito-permit-sync.go) need to be modified. +package main + +import ( + "context" + "log/slog" + "os" +) + +const envLogFormat = "LOG_FORMAT" + +// AuditLogger handles audit‑trail logging for compliance. +type AuditLogger struct { + logger *slog.Logger + file *os.File +} + +// NewAuditLogger initializes the audit logger. +// The signature is unchanged: pass isDryRun=true to write to dry-run-audit.log; +// otherwise logs are appended to audit.log in the working directory. +func NewAuditLogger(isDryRun bool) (*AuditLogger, error) { + filename := "audit.log" + if isDryRun { + filename = "dry-run-audit.log" + } + + file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + return nil, err + } + + // Choose handler based on LOG_FORMAT + var handler slog.Handler + switch os.Getenv(envLogFormat) { + case "json": + handler = slog.NewJSONHandler(file, &slog.HandlerOptions{AddSource: false}) + default: // "text" or unset + handler = slog.NewTextHandler(file, &slog.HandlerOptions{AddSource: false}) + } + + logger := slog.New(handler) + + return &AuditLogger{ + logger: logger, + file: file, + }, nil +} + +// Close closes the underlying audit file. +func (a *AuditLogger) Close() error { + if a.file != nil { + return a.file.Close() + } + return nil +} + +// ----- Public logging helpers ------------------------------------------------ + +// ActionType represents the type of action being logged. +type ActionType string + +const ( + ActionCreate ActionType = "CREATE" + ActionDelete ActionType = "DELETE" + ActionDisable ActionType = "DISABLE" + ActionEnable ActionType = "ENABLE" + ActionAssignRole ActionType = "ASSIGN_ROLE" + ActionUnassignRole ActionType = "UNASSIGN_ROLE" + ActionUpdate ActionType = "UPDATE" + ActionSkip ActionType = "SKIP" +) + +// SystemType represents the system where the action occurred. +type SystemType string + +const ( + SystemCognito SystemType = "COGNITO" + SystemPermit SystemType = "PERMIT" +) + +// ResultType represents the outcome of the action. +type ResultType string + +const ( + ResultSuccess ResultType = "SUCCESS" + ResultFailure ResultType = "FAILURE" + ResultSkipped ResultType = "SKIPPED" +) + +// LogAction logs a generic action (without subjectID or role). +func (a *AuditLogger) LogAction(action ActionType, system SystemType, userEmail string, result ResultType, details string) { + a.logger.InfoContext(context.TODO(), "audit_event", + "action", action, + "system", system, + "userEmail", userEmail, + "result", result, + "details", details, + ) +} + +// LogActionWithSubjectID logs an action involving a specific subject identifier. +func (a *AuditLogger) LogActionWithSubjectID(action ActionType, system SystemType, userEmail, subjectID string, result ResultType, details string) { + a.logger.InfoContext(context.TODO(), "audit_event", + "action", action, + "system", system, + "userEmail", userEmail, + "subjectID", subjectID, + "result", result, + "details", details, + ) +} + +// LogRoleAction logs role assignment/unassignment activities. +func (a *AuditLogger) LogRoleAction(action ActionType, userEmail, role string, result ResultType, details string) { + a.logger.InfoContext(context.TODO(), "audit_event", + "action", action, + "system", SystemPermit, + "userEmail", userEmail, + "role", role, + "result", result, + "details", details, + ) +} + +// LogDryRunStart marks the beginning of a dry‑run execution. +func (a *AuditLogger) LogDryRunStart() { + a.logger.InfoContext(context.TODO(), "dry_run_start") +} + +// LogDryRunEnd marks the completion of a dry‑run execution. +func (a *AuditLogger) LogDryRunEnd() { + a.logger.InfoContext(context.TODO(), "dry_run_end") +} diff --git a/cmd/cognito_test/user.creation.tool/cognito-permit-sync.go b/cmd/cognito_test/user.creation.tool/cognito-permit-sync.go new file mode 100644 index 00000000..ed465afc --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/cognito-permit-sync.go @@ -0,0 +1,1220 @@ +// cognito-permit-sync.go is the main entry point and orchestration logic for the user creation tool. +// This file coordinates the synchronization of users between AWS Cognito and Permit.io systems, +// handling CSV parsing, user creation/deletion/disable/enable operations, role validation, +// configuration management, and command-line interface. It serves as the primary workflow controller. +package main + +import ( + "context" + "encoding/csv" + "flag" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" + "github.com/joho/godotenv" +) + +type ErrorResponse struct { + Error struct { + Message string `json:"message"` + Details interface{} `json:"details,omitempty"` + } `json:"error"` +} + +// Import tracking types +type ImportResult struct { + TotalUsers int + SuccessfulUsers int + FailedUsers []FailedUser + StartTime time.Time + EndTime time.Time +} + +// Delete tracking types +type DeleteResult struct { + TotalUsers int + SuccessfulUsers int + FailedUsers []FailedUser + StartTime time.Time + EndTime time.Time +} + +// Disable/Enable tracking types +type DisableEnableResult struct { + TotalUsers int + SuccessfulUsers int + FailedUsers []FailedUser + StartTime time.Time + EndTime time.Time + OperationType string // "disable" or "enable" +} + +type FailedUser struct { + Email string + FirstName string + LastName string + Error string + FailureStep string // "cognito" or "permit" +} + +// Combined config +type AppConfig struct { + // Permit.io config + PermitAPIKey string + PermitProjectID string + PermitEnvID string + PermitBaseURL string + + // Cognito config + CognitoUserPoolID string + CognitoRegion string + + // Other + CSVPath string + DeleteUsers bool + DisableUsers bool + EnableUsers bool + DryRun bool +} + +// UserProcessingContext holds the context for processing a single user +type UserProcessingContext struct { + Config AppConfig + CognitoClient *cognitoidentityprovider.Client + CognitoConfig *CognitoConfig + HTTPClient *http.Client + AuditLogger *AuditLogger + User map[string]string + Index int + Total int +} + +func main() { + // Load .env file if it exists + if err := godotenv.Load(); err != nil { + // Don't exit on error - .env file might not exist and that's OK + // Environment variables can still be set other ways + fmt.Println("Error loading .env file - ignoring.") + } + + if err := run(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } +} + +func run() error { + config := parseFlags() + + // Initialize audit logger + auditLogger, err := NewAuditLogger(config.DryRun) + if err != nil { + return fmt.Errorf("failed to initialize audit logger: %v", err) + } + defer auditLogger.Close() + + // Log dry run start if applicable + if config.DryRun { + auditLogger.LogDryRunStart() + fmt.Println("🔍 DRY RUN MODE - No actual changes will be made") + fmt.Println(strings.Repeat("=", 60)) + } + + sanityCheckCredentials() + + // Check if we should list projects/environments + if config.PermitProjectID == "list" { + if config.PermitAPIKey == "" { + return fmt.Errorf("PERMIT_KEY environment variable is not set") + } + listProjectsAndEnvironments(config) + return nil + } + + // Validate configuration + if err := validateConfig(config); err != nil { + return fmt.Errorf("configuration error: %v", err) + } + + // Initialize AWS Cognito client + ctx := context.Background() + cognitoClient, err := initializeCognitoClient() + if err != nil { + return fmt.Errorf("error initializing Cognito client: %v", err) + } + + // Read and parse CSV file + users, err := readCSV(config.CSVPath, config) + if err != nil { + return fmt.Errorf("error reading CSV file: %v", err) + } + + if len(users) == 0 { + fmt.Println("No users found in CSV file") + return nil + } + + // Add this code AFTER this existing line: + // if len(users) == 0 { + // fmt.Println("No users found in CSV file") + // return nil + // } + + // AND BEFORE this existing line: + // if config.DeleteUsers { + + // Validate that all roles specified in CSV exist in Permit.io + fmt.Println("Validating roles specified in CSV...") + httpClient := &http.Client{Timeout: 30 * time.Second} + + requestedRoles, err := ValidateCSVRoles(httpClient, config, users) + if err != nil { + fmt.Printf("\n❌ Role Validation Failed!\n") + fmt.Println(strings.Repeat("=", 60)) + fmt.Printf("Error: %v\n\n", err) + fmt.Printf("The following roles are missing in Permit.io:\n") + for _, role := range requestedRoles { + fmt.Printf(" - %s\n", role) + } + fmt.Printf("\nPlease create these roles in Permit.io before running this tool.\n") + fmt.Printf("You can create roles in the Permit.io dashboard under:\n") + fmt.Printf("Project: %s → Environment: %s → Roles\n", config.PermitProjectID, config.PermitEnvID) + fmt.Println(strings.Repeat("=", 60)) + return fmt.Errorf("role validation failed") + } + + if len(requestedRoles) > 0 { + fmt.Printf("✅ All %d roles validated successfully: %s\n", + len(requestedRoles), strings.Join(requestedRoles, ", ")) + } else { + fmt.Println("ℹ️ No roles specified in CSV - skipping role validation") + } + fmt.Println() + + if config.DeleteUsers { + // Delete mode + fmt.Printf("Found %d users to DELETE\n", len(users)) + fmt.Printf("Will delete users from Permit.io project: %s\n", config.PermitProjectID) + fmt.Printf("Then delete from Cognito User Pool: %s\n", config.CognitoUserPoolID) + fmt.Println(strings.Repeat("=", 60)) + if !config.DryRun { + fmt.Println("⚠️ WARNING: This will permanently delete users!") + } + fmt.Println(strings.Repeat("=", 60)) + + // Process user deletions + result := deleteUsers(ctx, config, cognitoClient, users, auditLogger) + + // Print delete summary + printDeleteSummary(result) + } else if config.DisableUsers { + // Disable mode + fmt.Printf("Found %d users to DISABLE\n", len(users)) + fmt.Printf("Will disable users in Cognito User Pool: %s\n", config.CognitoUserPoolID) + fmt.Println(strings.Repeat("=", 60)) + + // Process user disabling + result := disableEnableUsers(ctx, config, cognitoClient, users, auditLogger, "disable") + + // Print disable/enable summary + printDisableEnableSummary(result) + } else if config.EnableUsers { + // Enable mode + fmt.Printf("Found %d users to ENABLE\n", len(users)) + fmt.Printf("Will enable users in Cognito User Pool: %s\n", config.CognitoUserPoolID) + fmt.Println(strings.Repeat("=", 60)) + + // Process user enabling + result := disableEnableUsers(ctx, config, cognitoClient, users, auditLogger, "enable") + + // Print disable/enable summary + printDisableEnableSummary(result) + } else { + // Create mode (existing functionality) + fmt.Printf("Found %d users to import\n", len(users)) + fmt.Printf("Will create users in Cognito User Pool: %s\n", config.CognitoUserPoolID) + fmt.Printf("Then sync to Permit.io project: %s\n", config.PermitProjectID) + fmt.Println(strings.Repeat("=", 60)) + + // Process users + result := processUsers(ctx, config, cognitoClient, users, auditLogger) + + // Print summary + printSummary(result) + } + + // Log dry run end if applicable + if config.DryRun { + auditLogger.LogDryRunEnd() + fmt.Println("\n🔍 DRY RUN COMPLETED - Check dry-run-audit.log for details") + } else { + fmt.Println("\n📋 Check audit.log for detailed audit trail") + } + + return nil +} + +func parseFlags() AppConfig { + var config AppConfig + + // Permit.io flags + flag.StringVar(&config.PermitProjectID, "project", "", "Permit.io project ID or key (required)") + flag.StringVar(&config.PermitEnvID, "env", "", "Permit.io environment ID or key (required)") + flag.StringVar(&config.PermitBaseURL, "api-url", "https://api.permit.io", "Permit.io API base URL") + + // File flag + flag.StringVar(&config.CSVPath, "csv", "", "Path to CSV file containing users (required)") + + // Delete flag + flag.BoolVar(&config.DeleteUsers, "delete-users", false, "Delete users instead of creating them") + + // Disable/Enable flags + flag.BoolVar(&config.DisableUsers, "disable-users", false, "Disable users in Cognito instead of creating them") + flag.BoolVar(&config.EnableUsers, "enable-users", false, "Enable users in Cognito instead of creating them") + + // Dry run flag + flag.BoolVar(&config.DryRun, "dry-run", false, "Perform a dry run without making actual changes") + + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "Usage: %s [options]\n\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "This tool creates users in AWS Cognito and syncs them to Permit.io\n\n") + fmt.Fprintf(os.Stderr, "Options:\n") + flag.PrintDefaults() + fmt.Fprintf(os.Stderr, "\nEnvironment Variables:\n") + fmt.Fprintf(os.Stderr, " PERMIT_KEY Permit.io API key (required)\n") + fmt.Fprintf(os.Stderr, " COGNITO_USER_POOL_ID AWS Cognito User Pool ID (required)\n") + fmt.Fprintf(os.Stderr, " COGNITO_CLIENT_ID AWS Cognito Client ID (required)\n") + fmt.Fprintf(os.Stderr, " COGNITO_CLIENT_SECRET AWS Cognito Client Secret (optional)\n") + fmt.Fprintf(os.Stderr, " AWS_REGION AWS Region (defaults to us-east-1)\n") + fmt.Fprintf(os.Stderr, "\nCSV Format:\n") + fmt.Fprintf(os.Stderr, " email,first_name,last_name,role1,role2,...,roleN\n") + fmt.Fprintf(os.Stderr, " - No user_id needed (generated by Cognito)\n") + fmt.Fprintf(os.Stderr, " - Up to 99 roles can be specified per user\n") + fmt.Fprintf(os.Stderr, " - Empty role columns are ignored\n") + fmt.Fprintf(os.Stderr, "\nExample:\n") + fmt.Fprintf(os.Stderr, " %s -project myproject -env production -csv users.csv\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "\nTo delete users:\n") + fmt.Fprintf(os.Stderr, " %s -project myproject -env production -csv users.csv --delete-users\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "\nTo disable users:\n") + fmt.Fprintf(os.Stderr, " %s -project myproject -env production -csv users.csv --disable-users\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "\nTo enable users:\n") + fmt.Fprintf(os.Stderr, " %s -project myproject -env production -csv users.csv --enable-users\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "\nTo perform a dry run:\n") + fmt.Fprintf(os.Stderr, " %s -project myproject -env production -csv users.csv --dry-run\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "\nTo list available projects and environments:\n") + fmt.Fprintf(os.Stderr, " %s -project list\n", os.Args[0]) + } + + flag.Parse() + + // Get environment variables + config.PermitAPIKey = os.Getenv("PERMIT_KEY") + config.CognitoUserPoolID = os.Getenv("COGNITO_USER_POOL_ID") + config.CognitoRegion = os.Getenv("AWS_REGION") + + if config.CognitoRegion == "" { + config.CognitoRegion = "us-east-1" + } + + return config +} + +func validateConfig(config AppConfig) error { + // Validate Permit.io config + if config.PermitAPIKey == "" { + return fmt.Errorf("PERMIT_KEY environment variable is not set") + } + + if config.PermitProjectID == "" { + return fmt.Errorf("project ID is required") + } + + if config.PermitEnvID == "" { + return fmt.Errorf("environment ID is required") + } + + // Validate Cognito config + if config.CognitoUserPoolID == "" { + return fmt.Errorf("COGNITO_USER_POOL_ID environment variable is not set") + } + + // Validate CSV + if config.CSVPath == "" { + return fmt.Errorf("CSV file path is required") + } + + if _, err := os.Stat(config.CSVPath); os.IsNotExist(err) { + return fmt.Errorf("CSV file does not exist: %s", config.CSVPath) + } + + // Validate that only one operation type is specified + operationCount := 0 + if config.DeleteUsers { + operationCount++ + } + if config.DisableUsers { + operationCount++ + } + if config.EnableUsers { + operationCount++ + } + + if operationCount > 1 { + return fmt.Errorf("only one operation can be specified: --delete-users, --disable-users, or --enable-users") + } + + return nil +} + +func readCSV(path string, config AppConfig) ([]map[string]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + reader := csv.NewReader(file) + reader.TrimLeadingSpace = true + reader.FieldsPerRecord = -1 // Allow variable number of fields per record + + // Read and validate header + header, err := reader.Read() + if err != nil { + return nil, fmt.Errorf("error reading CSV header: %v", err) + } + + if err := validateCSVHeader(header, config); err != nil { + return nil, err + } + + // Read all user records + return readUserRecords(reader, config) +} + +func validateCSVHeader(header []string, config AppConfig) error { + // For create operations, we need at least 3 columns (email, first_name, last_name) + // For other operations, we only need email (first column) + isCreateOperation := !config.DeleteUsers && !config.DisableUsers && !config.EnableUsers + + if isCreateOperation { + expectedHeaders := []string{"email", "first_name", "last_name"} + + if len(header) < len(expectedHeaders) { + return fmt.Errorf("CSV must have at least %d columns for user creation: %v", len(expectedHeaders), expectedHeaders) + } + + for i, expected := range expectedHeaders { + if strings.ToLower(strings.TrimSpace(header[i])) != expected { + return fmt.Errorf("column %d should be '%s' but got '%s'", i+1, expected, header[i]) + } + } + + // Check maximum number of roles (99 max = 102 total columns max now without user_id) + if len(header) > 102 { + return fmt.Errorf("CSV can have at most 99 role columns (found %d)", len(header)-3) + } + } else { + // For delete/disable/enable operations, we only need email + if len(header) < 1 { + return fmt.Errorf("CSV must have at least email column") + } + + if strings.ToLower(strings.TrimSpace(header[0])) != "email" { + return fmt.Errorf("first column should be 'email' but got '%s'", header[0]) + } + + // Check maximum number of columns (still enforce reasonable limits) + if len(header) > 102 { + return fmt.Errorf("CSV can have at most 102 columns") + } + } + + return nil +} + +func readUserRecords(reader *csv.Reader, config AppConfig) ([]map[string]string, error) { + var users []map[string]string + lineNum := 1 + + for { + record, err := reader.Read() + if err == io.EOF { + break + } + if err != nil { + return nil, fmt.Errorf("error reading line %d: %v", lineNum+1, err) + } + lineNum++ + + // Skip empty lines + if isEmptyRecord(record) { + continue + } + + if isCommentRecord(record) { + continue + } + + // Ensure we have at least the required fields + // For create operations, we need at least 3 fields (email, first_name, last_name) + // For other operations, we only need email (first field) + isCreateOperation := !config.DeleteUsers && !config.DisableUsers && !config.EnableUsers + if isCreateOperation && len(record) < 3 { + return nil, fmt.Errorf("line %d: must have at least 3 fields (email, first_name, last_name) for user creation", lineNum) + } + if !isCreateOperation && len(record) < 1 { + return nil, fmt.Errorf("line %d: must have at least email field", lineNum) + } + + user, err := parseUserRecord(record, lineNum, config) + if err != nil { + return nil, err + } + + users = append(users, user) + } + + return users, nil +} + +func isEmptyRecord(record []string) bool { + return len(record) == 0 || (len(record) == 1 && record[0] == "") +} + +func isCommentRecord(record []string) bool { + return len(record) > 0 && strings.HasPrefix(strings.TrimSpace(record[0]), "#") +} + +func parseUserRecord(record []string, lineNum int, config AppConfig) (map[string]string, error) { + user := make(map[string]string) + user["email"] = strings.TrimSpace(record[0]) + + // Handle optional fields for non-create operations + if len(record) > 1 { + user["first_name"] = strings.TrimSpace(record[1]) + } else { + user["first_name"] = "" + } + + if len(record) > 2 { + user["last_name"] = strings.TrimSpace(record[2]) + } else { + user["last_name"] = "" + } + + // Collect roles + user["roles"] = collectRoles(record) + + // Validate required fields + if user["email"] == "" { + return nil, fmt.Errorf("line %d: email cannot be empty", lineNum) + } + + // Validate first_name and last_name are required for create operations only + isCreateOperation := !config.DeleteUsers && !config.DisableUsers && !config.EnableUsers + if isCreateOperation { + if user["first_name"] == "" { + return nil, fmt.Errorf("line %d: first_name cannot be empty for user creation", lineNum) + } + if user["last_name"] == "" { + return nil, fmt.Errorf("line %d: last_name cannot be empty for user creation", lineNum) + } + } + + return user, nil +} + +func collectRoles(record []string) string { + var roles []string + for i := 3; i < len(record) && i < 102; i++ { // Max 99 roles, starting from index 3 + role := strings.TrimSpace(record[i]) + if role != "" { + roles = append(roles, role) + } + } + return strings.Join(roles, ",") +} + +/* + processUsers handles the processing of many users. + Because of its complexity and for maintainability, it breaks the work down into the following hierarchy: + +processUsers() + + └── processSingleUser() + ├── ensureCognitoUser() + ├── ensurePermitUser() + └── manageUserRoles() + ├── parseDesiredRoles() + ├── getCurrentRoles() + ├── removeUnwantedRoles() + └── addMissingRoles() + └── containsRole() +*/ +func processUsers(ctx context.Context, config AppConfig, cognitoClient *cognitoidentityprovider.Client, users []map[string]string, auditLogger *AuditLogger) ImportResult { + result := ImportResult{ + TotalUsers: len(users), + StartTime: time.Now(), + } + + httpClient := &http.Client{ + Timeout: 30 * time.Second, + } + + cognitoConfig := &CognitoConfig{ + UserPoolID: config.CognitoUserPoolID, + Region: config.CognitoRegion, + } + + for i, user := range users { + fmt.Printf("\nProcessing user %d/%d: %s\n", i+1, len(users), user["email"]) + + // Create processing context + procCtx := &UserProcessingContext{ + Config: config, + CognitoClient: cognitoClient, + CognitoConfig: cognitoConfig, + HTTPClient: httpClient, + AuditLogger: auditLogger, + User: user, + Index: i, + Total: len(users), + } + + // Process this user + success := processSingleUser(ctx, procCtx, &result) + + if success { + result.SuccessfulUsers++ + if config.DryRun { + fmt.Printf(" ✅ [DRY RUN] User would be successfully processed\n") + } else { + fmt.Printf(" ✅ User successfully processed in both systems\n") + } + } + + // Add a small delay to avoid rate limiting + if !config.DryRun { + time.Sleep(100 * time.Millisecond) + } + } + + result.EndTime = time.Now() + return result +} + +// processSingleUser handles the complete processing of a single user +func processSingleUser(ctx context.Context, procCtx *UserProcessingContext, result *ImportResult) bool { + // Step 1: Ensure user exists in Cognito + cognitoUser, err := ensureCognitoUser(ctx, procCtx) + if err != nil { + addFailedUser(result, procCtx.User, err.Error(), "cognito") + return false + } + + // Step 2: Ensure user exists in Permit.io + err = ensurePermitUser(procCtx, cognitoUser) + if err != nil { + addFailedUser(result, procCtx.User, err.Error(), "permit") + return false + } + + // Step 3: Manage user roles + err = manageUserRoles(procCtx, cognitoUser) + if err != nil { + addFailedUser(result, procCtx.User, err.Error(), "permit") + // Don't return false here - user was created, just role assignment may have failed partially + } + + return true +} + +// ensureCognitoUser ensures the user exists in Cognito (creates if needed) +func ensureCognitoUser(ctx context.Context, procCtx *UserProcessingContext) (*CognitoUserResponse, error) { + user := procCtx.User + config := procCtx.Config + cognitoClient := procCtx.CognitoClient + cognitoConfig := procCtx.CognitoConfig + auditLogger := procCtx.AuditLogger + + // Check if user exists in Cognito + if userExistsInCognito(ctx, cognitoClient, cognitoConfig.UserPoolID, user["email"]) { + fmt.Printf(" ℹ️ User already exists in Cognito\n") + auditLogger.LogAction(ActionSkip, SystemCognito, user["email"], ResultSkipped, "User already exists") + + // Get existing user details + existingUser, err := getCognitoUser(ctx, cognitoClient, cognitoConfig.UserPoolID, user["email"]) + if err != nil { + auditLogger.LogAction(ActionCreate, SystemCognito, user["email"], ResultFailure, fmt.Sprintf("Failed to retrieve existing user: %v", err)) + fmt.Printf(" ❌ Failed to retrieve existing Cognito user: %v\n", err) + return nil, fmt.Errorf("failed to retrieve existing Cognito user: %v", err) + } + return existingUser, nil + } + + // Create new user in Cognito + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would create user in Cognito\n") + auditLogger.LogAction(ActionCreate, SystemCognito, user["email"], ResultSuccess, "DRY RUN - Would create user") + // Create a mock user for dry run + return &CognitoUserResponse{ + SubjectID: "mock-subject-id-" + user["email"], + Username: user["email"], + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Status: "CONFIRMED", + }, nil + } + + cognitoUser, err := createCognitoUser(ctx, cognitoClient, cognitoConfig, user) + if err != nil { + auditLogger.LogAction(ActionCreate, SystemCognito, user["email"], ResultFailure, fmt.Sprintf("Failed to create: %v", err)) + fmt.Printf(" ❌ Cognito creation failed: %v\n", err) + return nil, fmt.Errorf("failed to create in Cognito: %v", err) + } + + auditLogger.LogActionWithSubjectID(ActionCreate, SystemCognito, user["email"], cognitoUser.SubjectID, ResultSuccess, "User created successfully") + fmt.Printf(" ✓ Created in Cognito with Subject ID: %s\n", cognitoUser.SubjectID) + return cognitoUser, nil +} + +// ensurePermitUser ensures the user exists in Permit.io (creates if needed) +func ensurePermitUser(procCtx *UserProcessingContext, cognitoUser *CognitoUserResponse) error { + user := procCtx.User + config := procCtx.Config + httpClient := procCtx.HTTPClient + auditLogger := procCtx.AuditLogger + + // Check if user exists in Permit.io + permitExists, permitUserKey, err := userExistsInPermit(httpClient, config, user["email"]) + if err != nil { + auditLogger.LogAction(ActionCreate, SystemPermit, user["email"], ResultFailure, fmt.Sprintf("Failed to check user existence: %v", err)) + fmt.Printf(" ❌ Failed to check Permit.io user existence: %v\n", err) + return fmt.Errorf("failed to check Permit.io user existence: %v", err) + } + + if permitExists { + fmt.Printf(" ℹ️ User already exists in Permit.io with key: %s\n", permitUserKey) + auditLogger.LogActionWithSubjectID(ActionSkip, SystemPermit, user["email"], permitUserKey, ResultSkipped, "User already exists") + return nil + } + + // Create user in Permit.io + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would create user in Permit.io\n") + auditLogger.LogActionWithSubjectID(ActionCreate, SystemPermit, user["email"], cognitoUser.SubjectID, ResultSuccess, "DRY RUN - Would create user") + return nil + } + + err = createPermitUser(httpClient, config, cognitoUser) + if err != nil { + auditLogger.LogActionWithSubjectID(ActionCreate, SystemPermit, user["email"], cognitoUser.SubjectID, ResultFailure, fmt.Sprintf("Failed to create: %v", err)) + fmt.Printf(" ❌ Permit.io creation failed: %v\n", err) + return fmt.Errorf("failed to create in Permit.io: %v", err) + } + + auditLogger.LogActionWithSubjectID(ActionCreate, SystemPermit, user["email"], cognitoUser.SubjectID, ResultSuccess, "User created successfully") + fmt.Printf(" ✓ Created in Permit.io\n") + return nil +} + +// manageUserRoles ensures user has exactly the roles specified in CSV +func manageUserRoles(procCtx *UserProcessingContext, cognitoUser *CognitoUserResponse) error { + user := procCtx.User + config := procCtx.Config + httpClient := procCtx.HTTPClient + auditLogger := procCtx.AuditLogger + + if user["roles"] == "" { + return nil // No roles to manage + } + + // Parse desired roles from CSV + desiredRoles := parseDesiredRoles(user["roles"]) + if len(desiredRoles) == 0 { + return nil + } + + // Get current roles + currentRoles, err := getCurrentRoles(httpClient, config, cognitoUser.SubjectID, auditLogger, user["email"]) + if err != nil { + return err + } + + // Remove roles that are no longer needed + err = removeUnwantedRoles(procCtx, cognitoUser, currentRoles, desiredRoles) + if err != nil { + return err + } + + // Add roles that are missing + return addMissingRoles(procCtx, cognitoUser, currentRoles, desiredRoles) +} + +// parseDesiredRoles parses the roles string from CSV into a slice +func parseDesiredRoles(rolesStr string) []string { + var desiredRoles []string + for _, role := range strings.Split(rolesStr, ",") { + role = strings.TrimSpace(role) + if role != "" { + desiredRoles = append(desiredRoles, role) + } + } + return desiredRoles +} + +// getCurrentRoles retrieves the current roles for a user +func getCurrentRoles(httpClient *http.Client, config AppConfig, subjectID string, auditLogger *AuditLogger, email string) ([]string, error) { + if config.DryRun { + return []string{}, nil // Assume no roles for dry run + } + + currentRoles, err := getPermitUserRoles(httpClient, config, subjectID) + if err != nil { + fmt.Printf(" ⚠️ Failed to get current roles: %v\n", err) + auditLogger.LogAction(ActionUpdate, SystemPermit, email, ResultFailure, fmt.Sprintf("Failed to get current roles: %v", err)) + return []string{}, nil // Continue with empty current roles + } + return currentRoles, nil +} + +// removeUnwantedRoles removes roles that are in current but not in desired +func removeUnwantedRoles(procCtx *UserProcessingContext, cognitoUser *CognitoUserResponse, currentRoles, desiredRoles []string) error { + config := procCtx.Config + httpClient := procCtx.HTTPClient + auditLogger := procCtx.AuditLogger + user := procCtx.User + + for _, currentRole := range currentRoles { + if !containsRole(desiredRoles, currentRole) { + // Remove this role + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would remove role: %s\n", currentRole) + auditLogger.LogRoleAction(ActionUnassignRole, user["email"], currentRole, ResultSuccess, "DRY RUN - Would remove role") + } else { + err := unassignRole(httpClient, config, cognitoUser.SubjectID, currentRole) + if err != nil { + fmt.Printf(" ⚠️ Failed to remove role '%s': %v\n", currentRole, err) + auditLogger.LogRoleAction(ActionUnassignRole, user["email"], currentRole, ResultFailure, fmt.Sprintf("Failed to remove: %v", err)) + } else { + fmt.Printf(" ✓ Removed role: %s\n", currentRole) + auditLogger.LogRoleAction(ActionUnassignRole, user["email"], currentRole, ResultSuccess, "Role removed successfully") + } + } + } + } + return nil +} + +// addMissingRoles adds roles that are in desired but not in current +func addMissingRoles(procCtx *UserProcessingContext, cognitoUser *CognitoUserResponse, currentRoles, desiredRoles []string) error { + config := procCtx.Config + httpClient := procCtx.HTTPClient + auditLogger := procCtx.AuditLogger + user := procCtx.User + + var roleErrors []string + + for _, desiredRole := range desiredRoles { + if !containsRole(currentRoles, desiredRole) { + // Add this role + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would assign role: %s\n", desiredRole) + auditLogger.LogRoleAction(ActionAssignRole, user["email"], desiredRole, ResultSuccess, "DRY RUN - Would assign role") + } else { + err := assignRole(httpClient, config, cognitoUser.SubjectID, desiredRole) + if err != nil { + roleErrors = append(roleErrors, fmt.Sprintf("role '%s': %v", desiredRole, err)) + auditLogger.LogRoleAction(ActionAssignRole, user["email"], desiredRole, ResultFailure, fmt.Sprintf("Failed to assign: %v", err)) + } else { + fmt.Printf(" ✓ Assigned role: %s\n", desiredRole) + auditLogger.LogRoleAction(ActionAssignRole, user["email"], desiredRole, ResultSuccess, "Role assigned successfully") + } + } + } else { + // Role already assigned + fmt.Printf(" ℹ️ Role already assigned: %s\n", desiredRole) + auditLogger.LogRoleAction(ActionSkip, user["email"], desiredRole, ResultSkipped, "Role already assigned") + } + } + + if len(roleErrors) > 0 { + return fmt.Errorf("failed to assign roles: %s", strings.Join(roleErrors, "; ")) + } + return nil +} + +// containsRole checks if a role exists in a slice of roles +func containsRole(roles []string, role string) bool { + for _, r := range roles { + if r == role { + return true + } + } + return false +} + +// addFailedUser adds a user to the failed users list +func addFailedUser(result *ImportResult, user map[string]string, errorMsg, failureStep string) { + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: errorMsg, + FailureStep: failureStep, + }) +} + +func deleteUsers(ctx context.Context, config AppConfig, cognitoClient *cognitoidentityprovider.Client, users []map[string]string, auditLogger *AuditLogger) DeleteResult { + result := DeleteResult{ + TotalUsers: len(users), + StartTime: time.Now(), + } + + httpClient := &http.Client{ + Timeout: 30 * time.Second, + } + + for i, user := range users { + fmt.Printf("\nDeleting user %d/%d: %s\n", i+1, len(users), user["email"]) + + // Step 1: Find user in Permit.io by email to get their key (Cognito Subject ID) + permitUserKey, err := findPermitUserByEmail(httpClient, config, user["email"]) + if err != nil { + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: fmt.Sprintf("Failed to find user in Permit.io: %v", err), + FailureStep: "permit", + }) + auditLogger.LogAction(ActionDelete, SystemPermit, user["email"], ResultFailure, fmt.Sprintf("Failed to find user: %v", err)) + fmt.Printf(" ❌ Failed to find user in Permit.io: %v\n", err) + continue + } + + if permitUserKey == "" { + fmt.Printf(" ℹ️ User not found in Permit.io, skipping Permit.io deletion\n") + auditLogger.LogAction(ActionSkip, SystemPermit, user["email"], ResultSkipped, "User not found in Permit.io") + } else { + fmt.Printf(" ✓ Found user in Permit.io with key: %s\n", permitUserKey) + + // Step 2: Delete user from Permit.io + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would delete from Permit.io\n") + auditLogger.LogActionWithSubjectID(ActionDelete, SystemPermit, user["email"], permitUserKey, ResultSuccess, "DRY RUN - Would delete user") + } else { + err = deletePermitUser(httpClient, config, permitUserKey) + if err != nil { + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: fmt.Sprintf("Failed to delete from Permit.io: %v", err), + FailureStep: "permit", + }) + auditLogger.LogActionWithSubjectID(ActionDelete, SystemPermit, user["email"], permitUserKey, ResultFailure, fmt.Sprintf("Failed to delete: %v", err)) + fmt.Printf(" ❌ Permit.io deletion failed: %v\n", err) + continue + } + auditLogger.LogActionWithSubjectID(ActionDelete, SystemPermit, user["email"], permitUserKey, ResultSuccess, "User deleted successfully") + fmt.Printf(" ✓ Deleted from Permit.io\n") + } + } + + // Step 3: Check if user exists in Cognito and delete if needed + if !userExistsInCognito(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) { + fmt.Printf(" ℹ️ User not found in Cognito, skipping Cognito deletion\n") + auditLogger.LogAction(ActionSkip, SystemCognito, user["email"], ResultSkipped, "User not found in Cognito") + } else { + // Delete user from Cognito (only if they exist) + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would delete from Cognito\n") + auditLogger.LogAction(ActionDelete, SystemCognito, user["email"], ResultSuccess, "DRY RUN - Would delete user") + } else { + err = deleteCognitoUser(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + if err != nil { + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: fmt.Sprintf("Failed to delete from Cognito: %v", err), + FailureStep: "cognito", + }) + auditLogger.LogAction(ActionDelete, SystemCognito, user["email"], ResultFailure, fmt.Sprintf("Failed to delete: %v", err)) + fmt.Printf(" ❌ Cognito deletion failed: %v\n", err) + if permitUserKey != "" { + fmt.Printf(" ⚠️ WARNING: User deleted from Permit.io but remains in Cognito!\n") + } + continue + } + auditLogger.LogAction(ActionDelete, SystemCognito, user["email"], ResultSuccess, "User deleted successfully") + fmt.Printf(" ✓ Deleted from Cognito\n") + } + } + + // Mark as successful - user was processed (deleted where they existed) + result.SuccessfulUsers++ + if config.DryRun { + fmt.Printf(" ✅ [DRY RUN] User would be successfully deleted\n") + } else { + fmt.Printf(" ✅ User successfully deleted from both systems\n") + } + + // Add a small delay to avoid rate limiting + if !config.DryRun { + time.Sleep(100 * time.Millisecond) + } + } + + result.EndTime = time.Now() + return result +} + +func printSummary(result ImportResult) { + duration := result.EndTime.Sub(result.StartTime) + + fmt.Println("\n" + strings.Repeat("=", 60)) + fmt.Println("IMPORT SUMMARY") + fmt.Println(strings.Repeat("=", 60)) + fmt.Printf("Total users processed: %d\n", result.TotalUsers) + fmt.Printf("Successfully created: %d\n", result.SuccessfulUsers) + fmt.Printf("Failed: %d\n", len(result.FailedUsers)) + fmt.Printf("Time taken: %s\n", duration.Round(time.Millisecond)) + fmt.Printf("Average time per user: %s\n", (duration / time.Duration(result.TotalUsers)).Round(time.Millisecond)) + + // Group failures by type + cognitoFailures := []FailedUser{} + permitFailures := []FailedUser{} + + for _, failed := range result.FailedUsers { + if failed.FailureStep == "cognito" { + cognitoFailures = append(cognitoFailures, failed) + } else { + permitFailures = append(permitFailures, failed) + } + } + + if len(cognitoFailures) > 0 { + fmt.Printf("\nCognito Failures (%d):\n", len(cognitoFailures)) + fmt.Println(strings.Repeat("-", 60)) + for _, failed := range cognitoFailures { + fmt.Printf(" Email: %s\n", failed.Email) + fmt.Printf(" Name: %s %s\n", failed.FirstName, failed.LastName) + fmt.Printf(" Error: %s\n", failed.Error) + fmt.Println() + } + } + + if len(permitFailures) > 0 { + fmt.Printf("\nPermit.io Failures (%d):\n", len(permitFailures)) + fmt.Println(strings.Repeat("-", 60)) + for _, failed := range permitFailures { + fmt.Printf(" Email: %s\n", failed.Email) + fmt.Printf(" Name: %s %s\n", failed.FirstName, failed.LastName) + fmt.Printf(" Error: %s\n", failed.Error) + fmt.Println() + } + } + + if result.SuccessfulUsers > 0 { + fmt.Printf("\n✅ Successfully created %d users in both Cognito and Permit.io\n", result.SuccessfulUsers) + } + + fmt.Println(strings.Repeat("=", 60)) +} + +func printDeleteSummary(result DeleteResult) { + duration := result.EndTime.Sub(result.StartTime) + + fmt.Println("\n" + strings.Repeat("=", 60)) + fmt.Println("DELETE SUMMARY") + fmt.Println(strings.Repeat("=", 60)) + fmt.Printf("Total users processed: %d\n", result.TotalUsers) + fmt.Printf("Successfully deleted: %d\n", result.SuccessfulUsers) + fmt.Printf("Failed: %d\n", len(result.FailedUsers)) + fmt.Printf("Time taken: %s\n", duration.Round(time.Millisecond)) + fmt.Printf("Average time per user: %s\n", (duration / time.Duration(result.TotalUsers)).Round(time.Millisecond)) + + // Group failures by type + permitFailures := []FailedUser{} + cognitoFailures := []FailedUser{} + + for _, failed := range result.FailedUsers { + if failed.FailureStep == "permit" { + permitFailures = append(permitFailures, failed) + } else if failed.FailureStep == "cognito" { + cognitoFailures = append(cognitoFailures, failed) + } + } + + if len(permitFailures) > 0 { + fmt.Printf("\nPermit.io Failures (%d):\n", len(permitFailures)) + fmt.Println(strings.Repeat("-", 60)) + for _, failed := range permitFailures { + fmt.Printf(" Email: %s\n", failed.Email) + fmt.Printf(" Name: %s %s\n", failed.FirstName, failed.LastName) + fmt.Printf(" Error: %s\n", failed.Error) + fmt.Println() + } + } + + if len(cognitoFailures) > 0 { + fmt.Printf("\nCognito Failures (%d):\n", len(cognitoFailures)) + fmt.Println(strings.Repeat("-", 60)) + fmt.Printf("⚠️ WARNING: These users were deleted from Permit.io but remain in Cognito!\n\n") + for _, failed := range cognitoFailures { + fmt.Printf(" Email: %s\n", failed.Email) + fmt.Printf(" Name: %s %s\n", failed.FirstName, failed.LastName) + fmt.Printf(" Error: %s\n", failed.Error) + fmt.Println() + } + } + + if result.SuccessfulUsers > 0 { + fmt.Printf("\n✅ Successfully deleted %d users from both Permit.io and Cognito\n", result.SuccessfulUsers) + } + + fmt.Println(strings.Repeat("=", 60)) +} + +func disableEnableUsers(ctx context.Context, config AppConfig, cognitoClient *cognitoidentityprovider.Client, users []map[string]string, auditLogger *AuditLogger, operation string) DisableEnableResult { + result := DisableEnableResult{ + TotalUsers: len(users), + StartTime: time.Now(), + OperationType: operation, + } + + for i, user := range users { + fmt.Printf("\n%s user %d/%d: %s\n", strings.ToUpper(operation[:1])+operation[1:], i+1, len(users), user["email"]) + + // Check if user exists in Cognito + if !userExistsInCognito(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) { + fmt.Printf(" ❌ User not found in Cognito\n") + auditLogger.LogAction(getActionType(operation), SystemCognito, user["email"], ResultFailure, "User not found") + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: "User not found in Cognito", + FailureStep: "cognito", + }) + continue + } + + // Check if user is already in desired state + isEnabled, err := isCognitoUserEnabled(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + if err != nil { + fmt.Printf(" ❌ Failed to check if user is enabled: %v\n", err) + auditLogger.LogAction(getActionType(operation), SystemCognito, user["email"], ResultFailure, fmt.Sprintf("Failed to check enabled state: %v", err)) + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: fmt.Sprintf("Failed to check enabled state: %v", err), + FailureStep: "cognito", + }) + continue + } + + if isUserInDesiredEnabledState(isEnabled, operation) { + fmt.Printf(" ℹ️ User is already %sd\n", operation) + auditLogger.LogAction(ActionSkip, SystemCognito, user["email"], ResultSkipped, fmt.Sprintf("User already %sd", operation)) + result.SuccessfulUsers++ + continue + } + + // Perform the operation + if config.DryRun { + fmt.Printf(" 🔍 [DRY RUN] Would %s user\n", operation) + auditLogger.LogAction(getActionType(operation), SystemCognito, user["email"], ResultSuccess, fmt.Sprintf("DRY RUN - Would %s user", operation)) + result.SuccessfulUsers++ + } else { + err := performUserOperation(ctx, cognitoClient, config.CognitoUserPoolID, user["email"], operation) + if err != nil { + fmt.Printf(" ❌ Failed to %s user: %v\n", operation, err) + auditLogger.LogAction(getActionType(operation), SystemCognito, user["email"], ResultFailure, fmt.Sprintf("Failed to %s: %v", operation, err)) + result.FailedUsers = append(result.FailedUsers, FailedUser{ + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Error: fmt.Sprintf("Failed to %s user: %v", operation, err), + FailureStep: "cognito", + }) + continue + } + + fmt.Printf(" ✅ Successfully %sd user\n", operation) + auditLogger.LogAction(getActionType(operation), SystemCognito, user["email"], ResultSuccess, fmt.Sprintf("User %sd successfully", operation)) + result.SuccessfulUsers++ + } + + // Add a small delay to avoid rate limiting + if !config.DryRun { + time.Sleep(100 * time.Millisecond) + } + } + + result.EndTime = time.Now() + return result +} + +func getActionType(operation string) ActionType { + if operation == "disable" { + return ActionDisable + } + return ActionEnable +} + +func isUserInDesiredEnabledState(isEnabled bool, operation string) bool { + if operation == "disable" { + // User should be disabled (not enabled) + return !isEnabled + } else { // enable + // User should be enabled + return isEnabled + } +} + +func performUserOperation(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username, operation string) error { + if operation == "disable" { + return disableCognitoUser(ctx, client, userPoolID, username) + } + return enableCognitoUser(ctx, client, userPoolID, username) +} + +func printDisableEnableSummary(result DisableEnableResult) { + duration := result.EndTime.Sub(result.StartTime) + + fmt.Println("\n" + strings.Repeat("=", 60)) + fmt.Printf("%s SUMMARY\n", strings.ToUpper(result.OperationType)) + fmt.Println(strings.Repeat("=", 60)) + fmt.Printf("Total users processed: %d\n", result.TotalUsers) + fmt.Printf("Successfully %sd: %d\n", result.OperationType, result.SuccessfulUsers) + fmt.Printf("Failed: %d\n", len(result.FailedUsers)) + fmt.Printf("Time taken: %s\n", duration.Round(time.Millisecond)) + fmt.Printf("Average time per user: %s\n", (duration / time.Duration(result.TotalUsers)).Round(time.Millisecond)) + + if len(result.FailedUsers) > 0 { + fmt.Printf("\nCognito Failures (%d):\n", len(result.FailedUsers)) + fmt.Println(strings.Repeat("-", 60)) + for _, failed := range result.FailedUsers { + fmt.Printf(" Email: %s\n", failed.Email) + fmt.Printf(" Name: %s %s\n", failed.FirstName, failed.LastName) + fmt.Printf(" Error: %s\n", failed.Error) + fmt.Println() + } + } + + if result.SuccessfulUsers > 0 { + fmt.Printf("\n✅ Successfully %sd %d users in Cognito\n", result.OperationType, result.SuccessfulUsers) + } + + fmt.Println(strings.Repeat("=", 60)) +} diff --git a/cmd/cognito_test/user.creation.tool/cognito.go b/cmd/cognito_test/user.creation.tool/cognito.go new file mode 100644 index 00000000..06af524e --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/cognito.go @@ -0,0 +1,248 @@ +// cognito.go handles AWS Cognito User Pool operations for user identity management. +// This file provides functions to create, delete, enable, disable, and retrieve users from +// AWS Cognito User Pools, including credential validation, user attribute management, +// and integration with AWS SDK v2 for identity provider operations. +package main + +import ( + "context" + "fmt" + "net/http" + "os" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/aws-sdk-go-v2/service/sts" +) + +// Cognito types +type CognitoConfig struct { + UserPoolID string + Region string +} + +type UserInput struct { + Email string + FirstName string + LastName string +} + +type CognitoUserResponse struct { + SubjectID string + Username string + Email string + FirstName string + LastName string + Status string + Enabled bool +} + +func sanityCheckCredentials() { + awsProfile := os.Getenv("AWS_PROFILE") + + var cfgOpts []func(*config.LoadOptions) error + if awsProfile != "" { + cfgOpts = append(cfgOpts, config.WithSharedConfigProfile(awsProfile)) + } + + // Pass options with ... to expand the slice + cfg, err := config.LoadDefaultConfig(context.Background(), cfgOpts...) + if err != nil { + fmt.Fprintf(os.Stderr, "AWS: Failed to load config: %v\n", err) + os.Exit(1) + } + + stsSvc := sts.NewFromConfig(cfg) + _, err = stsSvc.GetCallerIdentity(context.Background(), &sts.GetCallerIdentityInput{}) + if err != nil { + fmt.Fprintf(os.Stderr, "AWS: Credential check failed: %v\n", err) + os.Exit(1) + } + + permitKey := os.Getenv("PERMIT_KEY") + if permitKey == "" { + fmt.Fprintf(os.Stderr, "Permit.io: PERMIT_KEY environment variable is not set\n") + os.Exit(1) + } + + req, _ := http.NewRequest("GET", "https://api.permit.io/v2/projects", nil) + req.Header.Add("Authorization", "Bearer "+permitKey) + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Do(req) + if err != nil || resp.StatusCode < 200 || resp.StatusCode >= 300 { + fmt.Fprintf(os.Stderr, "Permit.io: Credential check failed: %v, status=%v\n", err, resp.StatusCode) + os.Exit(1) + } + resp.Body.Close() +} + +// Initialize a Cognito client with the correct profile +func initializeCognitoClient() (*cognitoidentityprovider.Client, error) { + awsProfile := os.Getenv("AWS_PROFILE") + + var cfgOpts []func(*config.LoadOptions) error + if awsProfile != "" { + cfgOpts = append(cfgOpts, config.WithSharedConfigProfile(awsProfile)) + } + + cfg, err := config.LoadDefaultConfig(context.Background(), cfgOpts...) + if err != nil { + return nil, err + } + + client := cognitoidentityprovider.NewFromConfig(cfg) + return client, nil +} + +func createCognitoUser(ctx context.Context, client *cognitoidentityprovider.Client, config *CognitoConfig, user map[string]string) (*CognitoUserResponse, error) { + // Use email as username + username := user["email"] + + // Prepare user attributes + userAttributes := []types.AttributeType{ + { + Name: aws.String("email"), + Value: aws.String(user["email"]), + }, + { + Name: aws.String("given_name"), + Value: aws.String(user["first_name"]), + }, + { + Name: aws.String("family_name"), + Value: aws.String(user["last_name"]), + }, + { + Name: aws.String("email_verified"), + Value: aws.String("true"), + }, + } + + // Prepare the AdminCreateUser input + createUserInput := &cognitoidentityprovider.AdminCreateUserInput{ + UserPoolId: aws.String(config.UserPoolID), + Username: aws.String(username), + UserAttributes: userAttributes, + DesiredDeliveryMediums: []types.DeliveryMediumType{types.DeliveryMediumTypeEmail}, + } + + // Create the user + result, err := client.AdminCreateUser(ctx, createUserInput) + if err != nil { + return nil, err + } + + // Extract the subject ID from attributes + var subjectID string + for _, attr := range result.User.Attributes { + if aws.ToString(attr.Name) == "sub" { + subjectID = aws.ToString(attr.Value) + break + } + } + + // Build response + response := &CognitoUserResponse{ + SubjectID: subjectID, + Username: aws.ToString(result.User.Username), + Email: user["email"], + FirstName: user["first_name"], + LastName: user["last_name"], + Status: string(result.User.UserStatus), + Enabled: result.User.Enabled, + } + + return response, nil +} + +func deleteCognitoUser(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) error { + deleteInput := &cognitoidentityprovider.AdminDeleteUserInput{ + UserPoolId: aws.String(userPoolID), + Username: aws.String(username), + } + + _, err := client.AdminDeleteUser(ctx, deleteInput) + if err != nil { + return err + } + + return nil +} + +// getCognitoUser retrieves an existing user from Cognito +func getCognitoUser(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) (*CognitoUserResponse, error) { + input := &cognitoidentityprovider.AdminGetUserInput{ + UserPoolId: aws.String(userPoolID), + Username: aws.String(username), + } + + result, err := client.AdminGetUser(ctx, input) + if err != nil { + return nil, err + } + + // Extract attributes + var subjectID, email, firstName, lastName string + for _, attr := range result.UserAttributes { + switch aws.ToString(attr.Name) { + case "sub": + subjectID = aws.ToString(attr.Value) + case "email": + email = aws.ToString(attr.Value) + case "given_name": + firstName = aws.ToString(attr.Value) + case "family_name": + lastName = aws.ToString(attr.Value) + } + } + + return &CognitoUserResponse{ + SubjectID: subjectID, + Username: aws.ToString(result.Username), + Email: email, + FirstName: firstName, + LastName: lastName, + Status: string(result.UserStatus), + Enabled: result.Enabled, + }, nil +} + +// userExistsInCognito checks if a user exists in Cognito +func userExistsInCognito(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) bool { + _, err := getCognitoUser(ctx, client, userPoolID, username) + return err == nil +} + +// disableCognitoUser disables a user in Cognito +func disableCognitoUser(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) error { + input := &cognitoidentityprovider.AdminDisableUserInput{ + UserPoolId: aws.String(userPoolID), + Username: aws.String(username), + } + + _, err := client.AdminDisableUser(ctx, input) + return err +} + +// enableCognitoUser enables a user in Cognito +func enableCognitoUser(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) error { + input := &cognitoidentityprovider.AdminEnableUserInput{ + UserPoolId: aws.String(userPoolID), + Username: aws.String(username), + } + + _, err := client.AdminEnableUser(ctx, input) + return err +} + +// isCognitoUserEnabled checks if a user is enabled in Cognito +func isCognitoUserEnabled(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) (bool, error) { + user, err := getCognitoUser(ctx, client, userPoolID, username) + if err != nil { + return false, err + } + return user.Enabled, nil +} diff --git a/cmd/cognito_test/user.creation.tool/disable_users_test.go b/cmd/cognito_test/user.creation.tool/disable_users_test.go new file mode 100644 index 00000000..3be1de0a --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/disable_users_test.go @@ -0,0 +1,453 @@ +//go:build aws + +package main + +import ( + "fmt" + "os" + "strings" + "testing" + "time" +) + +// Test data for disable/enable operations +var disableTestUsers = []map[string]string{ + { + "email": "disable-test1@gmail.com", + "first_name": "DisableTest", + "last_name": "User1", + "roles": "editor", + }, + { + "email": "disable-test2@gmail.com", + "first_name": "DisableTest", + "last_name": "User2", + "roles": "viewer", + }, +} + +const disableTestCSVPath = "./temp-disable-users.csv" + +func TestDisableEnableUserLifecycle(t *testing.T) { + // Skip test if required environment variables are not set + if !checkRequiredEnvVars(t) { + return + } + + // Create test CSV file for disable/enable tests + if err := createDisableTestCSV(); err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + + // Cleanup test CSV file after test + defer func() { + if err := os.Remove(disableTestCSVPath); err != nil && !os.IsNotExist(err) { + t.Logf("Warning: failed to cleanup test CSV file: %v", err) + } + }() + + // Test the complete lifecycle: create -> disable -> enable -> delete + t.Run("CreateTestUsers", func(t *testing.T) { + testCreateDisableTestUsers(t) + }) + + t.Run("VerifyUsersCreated", func(t *testing.T) { + testVerifyDisableTestUsersExist(t) + }) + + t.Run("DisableUsers", func(t *testing.T) { + testDisableUsers(t) + }) + + t.Run("VerifyUsersDisabled", func(t *testing.T) { + testVerifyUsersDisabled(t) + }) + + t.Run("EnableUsers", func(t *testing.T) { + testEnableUsers(t) + }) + + t.Run("VerifyUsersEnabled", func(t *testing.T) { + testVerifyUsersEnabled(t) + }) + + t.Run("CleanupTestUsers", func(t *testing.T) { + testDeleteDisableTestUsers(t) + }) +} + +func createDisableTestCSV() error { + csvContent := "email,first_name,last_name,role1\n" + csvContent += "disable-test1@gmail.com,DisableTest,User1,editor\n" + csvContent += "disable-test2@gmail.com,DisableTest,User2,viewer\n" + + return os.WriteFile(disableTestCSVPath, []byte(csvContent), 0600) +} + +func testCreateDisableTestUsers(t *testing.T) { + // Save original os.Args + originalArgs := os.Args + + // Set up args for user creation + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", disableTestCSVPath, + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application + err := run() + if err != nil { + t.Fatalf("Failed to create disable test users: %v", err) + } + + t.Logf("Successfully created disable test users") +} + +func testVerifyDisableTestUsersExist(t *testing.T) { + ctx := t.Context() + + // Initialize clients + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + config := AppConfig{ + CognitoUserPoolID: os.Getenv("COGNITO_USER_POOL_ID"), + CognitoRegion: os.Getenv("AWS_REGION"), + } + + for _, user := range disableTestUsers { + t.Run(fmt.Sprintf("VerifyUser_%s", user["email"]), func(t *testing.T) { + // Verify user exists in Cognito and is enabled + cognitoUser, err := getCognitoUser(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + if err != nil { + t.Fatalf("Failed to find user %s in Cognito: %v", user["email"], err) + } + + if cognitoUser.Status != "CONFIRMED" && cognitoUser.Status != "FORCE_CHANGE_PASSWORD" { + t.Fatalf("User %s is not in expected enabled state. Status: %s", user["email"], cognitoUser.Status) + } + + t.Logf("User %s found in Cognito with enabled status: %s", user["email"], cognitoUser.Status) + }) + } +} + +func testDisableUsers(t *testing.T) { + // Save original os.Args + originalArgs := os.Args + + // Set up args for user disabling + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", disableTestCSVPath, + "--disable-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in disable mode + err := run() + if err != nil { + t.Fatalf("Failed to disable users: %v", err) + } + + t.Logf("Successfully disabled users") +} + +func testVerifyUsersDisabled(t *testing.T) { + ctx := t.Context() + + // Initialize clients + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + config := AppConfig{ + CognitoUserPoolID: os.Getenv("COGNITO_USER_POOL_ID"), + CognitoRegion: os.Getenv("AWS_REGION"), + } + + for _, user := range disableTestUsers { + t.Run(fmt.Sprintf("VerifyUserDisabled_%s", user["email"]), func(t *testing.T) { + // Give Cognito a moment to process the disable request + time.Sleep(2 * time.Second) + + // Check if the user is disabled using the Enabled field + isEnabled, err := isCognitoUserEnabled(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + if err != nil { + t.Fatalf("Failed to check enabled state for %s: %v", user["email"], err) + } + + if isEnabled { + t.Fatalf("User %s is still enabled. Expected disabled state", user["email"]) + } + + t.Logf("User %s successfully verified as disabled (enabled=%v)", user["email"], isEnabled) + }) + } +} + +func testEnableUsers(t *testing.T) { + // Save original os.Args + originalArgs := os.Args + + // Set up args for user enabling + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", disableTestCSVPath, + "--enable-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in enable mode + err := run() + if err != nil { + t.Fatalf("Failed to enable users: %v", err) + } + + t.Logf("Successfully enabled users") +} + +func testVerifyUsersEnabled(t *testing.T) { + ctx := t.Context() + + // Initialize clients + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + config := AppConfig{ + CognitoUserPoolID: os.Getenv("COGNITO_USER_POOL_ID"), + CognitoRegion: os.Getenv("AWS_REGION"), + } + + for _, user := range disableTestUsers { + t.Run(fmt.Sprintf("VerifyUserEnabled_%s", user["email"]), func(t *testing.T) { + // Give Cognito a moment to process the enable request + time.Sleep(2 * time.Second) + + // Check if the user is enabled using the Enabled field + isEnabled, err := isCognitoUserEnabled(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + if err != nil { + t.Fatalf("Failed to check enabled state for %s: %v", user["email"], err) + } + + if !isEnabled { + t.Fatalf("User %s is not enabled. Expected enabled state", user["email"]) + } + + t.Logf("User %s successfully verified as enabled (enabled=%v)", user["email"], isEnabled) + }) + } +} + +func testDeleteDisableTestUsers(t *testing.T) { + // Save original os.Args + originalArgs := os.Args + + // Set up args for user deletion + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", disableTestCSVPath, + "--delete-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in delete mode + err := run() + if err != nil { + t.Fatalf("Failed to delete disable test users: %v", err) + } + + t.Logf("Successfully deleted disable test users") +} + +// Test individual disable/enable functions +func TestDisableEnableOperations(t *testing.T) { + if !checkRequiredEnvVars(t) { + return + } + + ctx := t.Context() + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + userPoolID := os.Getenv("COGNITO_USER_POOL_ID") + testEmail := "individual-test@example.com" + + // Create a test user first + testUser := map[string]string{ + "email": testEmail, + "first_name": "Individual", + "last_name": "Test", + } + + cognitoConfig := &CognitoConfig{ + UserPoolID: userPoolID, + Region: os.Getenv("AWS_REGION"), + } + + // Create user + _, err = createCognitoUser(ctx, cognitoClient, cognitoConfig, testUser) + if err != nil { + // If user already exists, that's fine + if !strings.Contains(err.Error(), "already exists") && !strings.Contains(err.Error(), "UsernameExistsException") { + t.Fatalf("Failed to create test user: %v", err) + } + } + + defer func() { + // Cleanup: delete the test user + _ = deleteCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + }() + + t.Run("TestDisableFunction", func(t *testing.T) { + // Test disable function + err := disableCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("Failed to disable user: %v", err) + } + + // Verify user is disabled using the Enabled field + isEnabled, err := isCognitoUserEnabled(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("Failed to check enabled state: %v", err) + } + + if isEnabled { + t.Fatalf("User should be disabled but is still enabled") + } + + t.Logf("User successfully disabled (enabled=%v)", isEnabled) + }) + + t.Run("TestEnableFunction", func(t *testing.T) { + // Test enable function + err := enableCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("Failed to enable user: %v", err) + } + + // Verify user is enabled using the Enabled field + isEnabled, err := isCognitoUserEnabled(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("Failed to check enabled state: %v", err) + } + + if !isEnabled { + t.Fatalf("User should be enabled but is still disabled") + } + + t.Logf("User successfully enabled (enabled=%v)", isEnabled) + }) +} + +// Test idempotent behavior +func TestIdempotentDisableEnable(t *testing.T) { + if !checkRequiredEnvVars(t) { + return + } + + ctx := t.Context() + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + userPoolID := os.Getenv("COGNITO_USER_POOL_ID") + testEmail := "idempotent-test@example.com" + + // Create a test user + testUser := map[string]string{ + "email": testEmail, + "first_name": "Idempotent", + "last_name": "Test", + } + + cognitoConfig := &CognitoConfig{ + UserPoolID: userPoolID, + Region: os.Getenv("AWS_REGION"), + } + + _, err = createCognitoUser(ctx, cognitoClient, cognitoConfig, testUser) + if err != nil && !strings.Contains(err.Error(), "already exists") && !strings.Contains(err.Error(), "UsernameExistsException") { + t.Fatalf("Failed to create test user: %v", err) + } + + defer func() { + // Cleanup: delete the test user + _ = deleteCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + }() + + t.Run("TestDisableIdempotent", func(t *testing.T) { + // Disable user twice - second should be idempotent + err := disableCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("First disable failed: %v", err) + } + + err = disableCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("Second disable (idempotent) failed: %v", err) + } + + t.Logf("Disable operation is idempotent") + }) + + t.Run("TestEnableIdempotent", func(t *testing.T) { + // Enable user twice - second should be idempotent + err := enableCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("First enable failed: %v", err) + } + + err = enableCognitoUser(ctx, cognitoClient, userPoolID, testEmail) + if err != nil { + t.Fatalf("Second enable (idempotent) failed: %v", err) + } + + t.Logf("Enable operation is idempotent") + }) +} diff --git a/cmd/cognito_test/user.creation.tool/minimal_csv_operations_test.go b/cmd/cognito_test/user.creation.tool/minimal_csv_operations_test.go new file mode 100644 index 00000000..7c24d4e7 --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/minimal_csv_operations_test.go @@ -0,0 +1,394 @@ +//go:build aws + +package main + +import ( + "os" + "testing" +) + +const minimalCSVPath = "./temp-minimal-operations.csv" + +// Test that the actual CLI operations work with minimal CSV files +func TestMinimalCSVOperations(t *testing.T) { + // Skip test if required environment variables are not set + if !checkRequiredEnvVars(t) { + return + } + + // First create some test users that we can later disable/delete + t.Run("CreateUserForMinimalTesting", func(t *testing.T) { + // Create a test user with full data + csvContent := "email,first_name,last_name\n" + csvContent += "minimal-test@gmail.com,Minimal,Test\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + // Save original os.Args + originalArgs := os.Args + + // Set up args for user creation + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application to create the user + err = run() + if err != nil { + t.Fatalf("Failed to create test user for minimal CSV testing: %v", err) + } + + t.Logf("Successfully created test user for minimal CSV operations") + }) + + // Test disable operation with minimal CSV (only email) + t.Run("DisableUserWithMinimalCSV", func(t *testing.T) { + // Create minimal CSV with only email + csvContent := "email\n" + csvContent += "minimal-test@gmail.com\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create minimal CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + // Save original os.Args + originalArgs := os.Args + + // Set up args for user disabling + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + "--disable-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in disable mode + err = run() + if err != nil { + t.Fatalf("Failed to disable user with minimal CSV: %v", err) + } + + t.Logf("Successfully disabled user with minimal CSV (email only)") + }) + + // Test enable operation with minimal CSV (only email) + t.Run("EnableUserWithMinimalCSV", func(t *testing.T) { + // Create minimal CSV with only email + csvContent := "email\n" + csvContent += "minimal-test@gmail.com\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create minimal CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + // Save original os.Args + originalArgs := os.Args + + // Set up args for user enabling + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + "--enable-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in enable mode + err = run() + if err != nil { + t.Fatalf("Failed to enable user with minimal CSV: %v", err) + } + + t.Logf("Successfully enabled user with minimal CSV (email only)") + }) + + // Test delete operation with minimal CSV (only email) + t.Run("DeleteUserWithMinimalCSV", func(t *testing.T) { + // Create minimal CSV with only email + csvContent := "email\n" + csvContent += "minimal-test@gmail.com\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create minimal CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + // Save original os.Args + originalArgs := os.Args + + // Set up args for user deletion + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + "--delete-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in delete mode + err = run() + if err != nil { + t.Fatalf("Failed to delete user with minimal CSV: %v", err) + } + + t.Logf("Successfully deleted user with minimal CSV (email only)") + }) +} + +// Test that create operations fail with empty names +func TestCreateOperationValidation(t *testing.T) { + // Skip test if required environment variables are not set + if !checkRequiredEnvVars(t) { + return + } + + t.Run("CreateFailsWithEmptyFirstName", func(t *testing.T) { + // Create CSV with empty first name + csvContent := "email,first_name,last_name\n" + csvContent += "validation-test@gmail.com,,Test\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + // Save original os.Args + originalArgs := os.Args + + // Set up args for user creation (default mode) + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application - should fail + err = run() + if err == nil { + t.Fatal("Expected error for empty first_name in create mode, but got none") + } + + t.Logf("Create operation correctly failed with empty first_name: %v", err) + }) + + t.Run("CreateFailsWithEmptyLastName", func(t *testing.T) { + // Create CSV with empty last name + csvContent := "email,first_name,last_name\n" + csvContent += "validation-test@gmail.com,Test,\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + // Save original os.Args + originalArgs := os.Args + + // Set up args for user creation (default mode) + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application - should fail + err = run() + if err == nil { + t.Fatal("Expected error for empty last_name in create mode, but got none") + } + + t.Logf("Create operation correctly failed with empty last_name: %v", err) + }) +} + +// Test with CSV files that have empty name fields but valid for delete/disable +func TestEmptyNamesForNonCreateOperations(t *testing.T) { + // Skip test if required environment variables are not set + if !checkRequiredEnvVars(t) { + return + } + + // First create a test user + t.Run("CreateUserForEmptyNameTesting", func(t *testing.T) { + csvContent := "email,first_name,last_name\n" + csvContent += "empty-names-test@gmail.com,EmptyNames,Test\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + originalArgs := os.Args + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + } + defer func() { os.Args = originalArgs }() + + resetFlags() + err = run() + if err != nil { + t.Fatalf("Failed to create test user: %v", err) + } + + t.Logf("Successfully created test user for empty names testing") + }) + + t.Run("DisableWithEmptyNames", func(t *testing.T) { + // CSV with empty names + csvContent := "email,first_name,last_name\n" + csvContent += "empty-names-test@gmail.com,,\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + originalArgs := os.Args + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + "--disable-users", + } + defer func() { os.Args = originalArgs }() + + resetFlags() + err = run() + if err != nil { + t.Fatalf("Failed to disable user with empty names: %v", err) + } + + t.Logf("Successfully disabled user with empty names") + }) + + t.Run("EnableWithEmptyNames", func(t *testing.T) { + // CSV with empty names + csvContent := "email,first_name,last_name\n" + csvContent += "empty-names-test@gmail.com,,\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + originalArgs := os.Args + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + "--enable-users", + } + defer func() { os.Args = originalArgs }() + + resetFlags() + err = run() + if err != nil { + t.Fatalf("Failed to enable user with empty names: %v", err) + } + + t.Logf("Successfully enabled user with empty names") + }) + + t.Run("DeleteWithEmptyNames", func(t *testing.T) { + // CSV with empty names + csvContent := "email,first_name,last_name\n" + csvContent += "empty-names-test@gmail.com,,\n" + + err := os.WriteFile(minimalCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(minimalCSVPath) + + originalArgs := os.Args + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", minimalCSVPath, + "--delete-users", + } + defer func() { os.Args = originalArgs }() + + resetFlags() + err = run() + if err != nil { + t.Fatalf("Failed to delete user with empty names: %v", err) + } + + t.Logf("Successfully deleted user with empty names") + }) +} diff --git a/cmd/cognito_test/user.creation.tool/name_validation_test.go b/cmd/cognito_test/user.creation.tool/name_validation_test.go new file mode 100644 index 00000000..f688b49a --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/name_validation_test.go @@ -0,0 +1,419 @@ +//go:build aws + +package main + +import ( + "os" + "strings" + "testing" +) + +const nameValidationTestCSVPath = "./temp-name-validation.csv" + +func TestNameValidationForCreateMode(t *testing.T) { + t.Run("CreateMode_MissingFirstName", func(t *testing.T) { + // CSV with missing first name + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,,Smith\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: false, + } + + _, err = readCSV(nameValidationTestCSVPath, config) + if err == nil { + t.Fatal("Expected error for missing first_name in create mode, but got none") + } + + if !strings.Contains(err.Error(), "first_name cannot be empty for user creation") { + t.Fatalf("Expected error about missing first_name, got: %v", err) + } + + t.Logf("Correctly detected missing first_name: %v", err) + }) + + t.Run("CreateMode_MissingLastName", func(t *testing.T) { + // CSV with missing last name + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,John,\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: false, + } + + _, err = readCSV(nameValidationTestCSVPath, config) + if err == nil { + t.Fatal("Expected error for missing last_name in create mode, but got none") + } + + if !strings.Contains(err.Error(), "last_name cannot be empty for user creation") { + t.Fatalf("Expected error about missing last_name, got: %v", err) + } + + t.Logf("Correctly detected missing last_name: %v", err) + }) + + t.Run("CreateMode_MissingBothNames", func(t *testing.T) { + // CSV with missing both names + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,,\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: false, + } + + _, err = readCSV(nameValidationTestCSVPath, config) + if err == nil { + t.Fatal("Expected error for missing names in create mode, but got none") + } + + if !strings.Contains(err.Error(), "first_name cannot be empty for user creation") { + t.Fatalf("Expected error about missing first_name, got: %v", err) + } + + t.Logf("Correctly detected missing first_name: %v", err) + }) + + t.Run("CreateMode_ValidNames", func(t *testing.T) { + // CSV with valid names + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,John,Smith\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: false, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for valid names in create mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + user := users[0] + if user["email"] != "test@example.com" { + t.Fatalf("Expected email 'test@example.com', got '%s'", user["email"]) + } + if user["first_name"] != "John" { + t.Fatalf("Expected first_name 'John', got '%s'", user["first_name"]) + } + if user["last_name"] != "Smith" { + t.Fatalf("Expected last_name 'Smith', got '%s'", user["last_name"]) + } + + t.Logf("Valid names accepted correctly for create mode") + }) +} + +func TestNameValidationForDeleteMode(t *testing.T) { + t.Run("DeleteMode_OnlyEmail", func(t *testing.T) { + // CSV with only email (minimal CSV for delete) + csvContent := "email\n" + csvContent += "test@example.com\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: true, + DisableUsers: false, + EnableUsers: false, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for email-only CSV in delete mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + user := users[0] + if user["email"] != "test@example.com" { + t.Fatalf("Expected email 'test@example.com', got '%s'", user["email"]) + } + if user["first_name"] != "" { + t.Fatalf("Expected empty first_name, got '%s'", user["first_name"]) + } + if user["last_name"] != "" { + t.Fatalf("Expected empty last_name, got '%s'", user["last_name"]) + } + + t.Logf("Email-only CSV accepted correctly for delete mode") + }) + + t.Run("DeleteMode_EmptyNames", func(t *testing.T) { + // CSV with empty names (should be allowed for delete) + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,,\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: true, + DisableUsers: false, + EnableUsers: false, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for empty names in delete mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + user := users[0] + if user["email"] != "test@example.com" { + t.Fatalf("Expected email 'test@example.com', got '%s'", user["email"]) + } + + t.Logf("Empty names accepted correctly for delete mode") + }) +} + +func TestNameValidationForDisableMode(t *testing.T) { + t.Run("DisableMode_OnlyEmail", func(t *testing.T) { + // CSV with only email + csvContent := "email\n" + csvContent += "test@example.com\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: true, + EnableUsers: false, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for email-only CSV in disable mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + user := users[0] + if user["email"] != "test@example.com" { + t.Fatalf("Expected email 'test@example.com', got '%s'", user["email"]) + } + + t.Logf("Email-only CSV accepted correctly for disable mode") + }) + + t.Run("DisableMode_EmptyNames", func(t *testing.T) { + // CSV with empty names + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,,\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: true, + EnableUsers: false, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for empty names in disable mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + t.Logf("Empty names accepted correctly for disable mode") + }) +} + +func TestNameValidationForEnableMode(t *testing.T) { + t.Run("EnableMode_OnlyEmail", func(t *testing.T) { + // CSV with only email + csvContent := "email\n" + csvContent += "test@example.com\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: true, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for email-only CSV in enable mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + user := users[0] + if user["email"] != "test@example.com" { + t.Fatalf("Expected email 'test@example.com', got '%s'", user["email"]) + } + + t.Logf("Email-only CSV accepted correctly for enable mode") + }) + + t.Run("EnableMode_EmptyNames", func(t *testing.T) { + // CSV with empty names + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,,\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: true, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for empty names in enable mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + t.Logf("Empty names accepted correctly for enable mode") + }) +} + +// Test edge case where CSV has inconsistent field counts +func TestNameValidationEdgeCases(t *testing.T) { + t.Run("CreateMode_InsufficientFields", func(t *testing.T) { + // CSV with insufficient fields for create mode + csvContent := "email,first_name,last_name\n" + csvContent += "test@example.com,John\n" // Missing last_name field + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: false, + DisableUsers: false, + EnableUsers: false, + } + + _, err = readCSV(nameValidationTestCSVPath, config) + if err == nil { + t.Fatal("Expected error for insufficient fields in create mode, but got none") + } + + if !strings.Contains(err.Error(), "must have at least 3 fields") { + t.Fatalf("Expected error about insufficient fields, got: %v", err) + } + + t.Logf("Correctly detected insufficient fields: %v", err) + }) + + t.Run("DeleteMode_OnlyEmailField", func(t *testing.T) { + // CSV with just email field for delete mode + csvContent := "email\n" + csvContent += "test@example.com\n" + + err := os.WriteFile(nameValidationTestCSVPath, []byte(csvContent), 0600) + if err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + defer os.Remove(nameValidationTestCSVPath) + + config := AppConfig{ + CSVPath: nameValidationTestCSVPath, + DeleteUsers: true, + DisableUsers: false, + EnableUsers: false, + } + + users, err := readCSV(nameValidationTestCSVPath, config) + if err != nil { + t.Fatalf("Expected no error for email-only CSV in delete mode, got: %v", err) + } + + if len(users) != 1 { + t.Fatalf("Expected 1 user, got %d", len(users)) + } + + t.Logf("Single email field correctly handled for delete mode") + }) +} diff --git a/cmd/cognito_test/user.creation.tool/permit.go b/cmd/cognito_test/user.creation.tool/permit.go new file mode 100644 index 00000000..cf309b15 --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/permit.go @@ -0,0 +1,626 @@ +// permit.go handles Permit.io API operations for user management and role-based access control (RBAC). +// This file provides functions to create, delete, search, and manage users in Permit.io, as well as +// assign/unassign roles and validate role definitions. It integrates with Cognito user data to sync +// user information between the two systems. +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" +) + +// Permit.io types +type PermitUser struct { + Key string `json:"key"` + Email string `json:"email,omitempty"` + FirstName string `json:"first_name,omitempty"` + LastName string `json:"last_name,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +type RoleAssignment struct { + User string `json:"user"` + Role string `json:"role"` + Tenant string `json:"tenant"` +} + +func createPermitUser(client *http.Client, config AppConfig, cognitoUser *CognitoUserResponse) error { + url := fmt.Sprintf("%s/v2/facts/%s/%s/users", config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID) + + userObj := PermitUser{ + Key: cognitoUser.SubjectID, // Use Cognito Subject ID as the key + Email: cognitoUser.Email, + FirstName: cognitoUser.FirstName, + LastName: cognitoUser.LastName, + Attributes: map[string]interface{}{ + "cognito_username": cognitoUser.Username, + "cognito_status": cognitoUser.Status, + }, + } + + jsonData, err := json.Marshal(userObj) + if err != nil { + return fmt.Errorf("error marshaling user data: %v", err) + } + + req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) + if err != nil { + return fmt.Errorf("error creating request: %v", err) + } + + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + req.Header.Set("Content-Type", "application/json") + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + + // If we get a 404, provide helpful debugging info + if resp.StatusCode == http.StatusNotFound { + var errResp map[string]interface{} + if err := json.Unmarshal(body, &errResp); err == nil { + return fmt.Errorf("API error (status 404): %s\nTry running with '-project list' to see available projects and environments", errResp["message"]) + } + } + + if resp.StatusCode == http.StatusConflict || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { + // User already exists or was created successfully + return nil + } + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error.Message != "" { + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, errResp.Error.Message) + } + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + return nil +} + +func assignRole(client *http.Client, config AppConfig, userID, role string) error { + url := fmt.Sprintf("%s/v2/facts/%s/%s/role_assignments", config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID) + + assignment := RoleAssignment{ + User: userID, + Role: role, + Tenant: "default", // Using default tenant + } + + jsonData, err := json.Marshal(assignment) + if err != nil { + return fmt.Errorf("error marshaling role assignment: %v", err) + } + + req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) + if err != nil { + return fmt.Errorf("error creating request: %v", err) + } + + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + req.Header.Set("Content-Type", "application/json") + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + + if resp.StatusCode == http.StatusConflict || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { + // Role already assigned or was assigned successfully + return nil + } + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error.Message != "" { + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, errResp.Error.Message) + } + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + return nil +} + +func findPermitUserByEmail(client *http.Client, config AppConfig, email string) (string, error) { + // Search for user by email + url := fmt.Sprintf("%s/v2/facts/%s/%s/users?search=%s", config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID, email) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return "", fmt.Errorf("error creating request: %v", err) + } + + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + req.Header.Set("Content-Type", "application/json") + + resp, err := client.Do(req) + if err != nil { + return "", fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + // Parse response to find user + // First try to unmarshal as an object (paginated response) + var response map[string]interface{} + if err := json.Unmarshal(body, &response); err != nil { + return "", fmt.Errorf("error parsing response: %v", err) + } + + // Look for users in common pagination structures + var users []interface{} + if data, ok := response["data"].([]interface{}); ok { + users = data + } else if items, ok := response["items"].([]interface{}); ok { + users = items + } else if usersList, ok := response["users"].([]interface{}); ok { + users = usersList + } else if _, ok := response["key"]; ok { + // Single user object returned + users = []interface{}{response} + } else { + // Try direct array unmarshaling as fallback + var directUsers []interface{} + if err := json.Unmarshal(body, &directUsers); err == nil { + users = directUsers + } else { + // If all else fails, assume the response itself is an array + return "", fmt.Errorf("unexpected response format") + } + } + + // Find user with matching email + for _, u := range users { + if user, ok := u.(map[string]interface{}); ok { + if userEmail, ok := user["email"].(string); ok && userEmail == email { + if key, ok := user["key"].(string); ok { + return key, nil + } + } + } + } + + return "", nil // User not found +} + +func deletePermitUser(client *http.Client, config AppConfig, userKey string) error { + url := fmt.Sprintf("%s/v2/facts/%s/%s/users/%s", config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID, userKey) + + req, err := http.NewRequest("DELETE", url, nil) + if err != nil { + return fmt.Errorf("error creating request: %v", err) + } + + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error.Message != "" { + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, errResp.Error.Message) + } + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + return nil +} + +// getPermitUserRoles retrieves the roles assigned to a user in Permit.io +func getPermitUserRoles(client *http.Client, config AppConfig, userKey string) ([]string, error) { + url := fmt.Sprintf("%s/v2/facts/%s/%s/role_assignments?user=%s", + config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID, userKey) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %v", err) + } + + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + req.Header.Set("Content-Type", "application/json") + + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("error reading response: %v", err) + } + + var roles []string + var assignments []interface{} + + // First try to unmarshal as direct array (common case) + var directAssignments []interface{} + if err := json.Unmarshal(body, &directAssignments); err == nil { + assignments = directAssignments + } else { + // If that fails, try as object with data/items/etc + var response map[string]interface{} + if err := json.Unmarshal(body, &response); err != nil { + return nil, fmt.Errorf("error parsing response as object or array: %v", err) + } + + // Look for role assignments in common response structures + if data, ok := response["data"].([]interface{}); ok { + assignments = data + } else if items, ok := response["items"].([]interface{}); ok { + assignments = items + } else if results, ok := response["results"].([]interface{}); ok { + assignments = results + } + } + + // Extract role names from assignments + for _, assignment := range assignments { + if roleAssignment, ok := assignment.(map[string]interface{}); ok { + if role, ok := roleAssignment["role"].(string); ok { + roles = append(roles, role) + } + } + } + + return roles, nil +} + +// unassignRole removes a role assignment from a user in Permit.io +func unassignRole(client *http.Client, config AppConfig, userID, role string) error { + url := fmt.Sprintf("%s/v2/facts/%s/%s/role_assignments", config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID) + + assignment := RoleAssignment{ + User: userID, + Role: role, + Tenant: "default", // Using default tenant + } + + jsonData, err := json.Marshal(assignment) + if err != nil { + return fmt.Errorf("error marshaling role assignment: %v", err) + } + + req, err := http.NewRequest("DELETE", url, bytes.NewBuffer(jsonData)) + if err != nil { + return fmt.Errorf("error creating request: %v", err) + } + + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + req.Header.Set("Content-Type", "application/json") + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + + if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNoContent || resp.StatusCode == http.StatusNotFound { + // Role was unassigned, already unassigned, or didn't exist + return nil + } + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error.Message != "" { + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, errResp.Error.Message) + } + return fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + return nil +} + +// userExistsInPermit checks if a user exists in Permit.io by email +func userExistsInPermit(client *http.Client, config AppConfig, email string) (bool, string, error) { + userKey, err := findPermitUserByEmail(client, config, email) + if err != nil { + return false, "", err + } + return userKey != "", userKey, nil +} + +func listProjectsAndEnvironments(config AppConfig) { + if config.PermitAPIKey == "" { + fmt.Fprintf(os.Stderr, "PERMIT_KEY environment variable is not set\n") + return + } + + client := &http.Client{Timeout: 30 * time.Second} + + fmt.Println("Fetching available projects and environments...") + fmt.Println(strings.Repeat("=", 60)) + + // First, try to get the organization info + orgReq, _ := http.NewRequest("GET", config.PermitBaseURL+"/v2/orgs", nil) + orgReq.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + + orgResp, err := client.Do(orgReq) + if err != nil { + fmt.Fprintf(os.Stderr, "Error fetching organization info: %v\n", err) + return + } + defer orgResp.Body.Close() + + if orgResp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(orgResp.Body) + fmt.Fprintf(os.Stderr, "Error response from API: %s\n", string(body)) + return + } + + // Try to list projects + projReq, _ := http.NewRequest("GET", config.PermitBaseURL+"/v2/projects", nil) + projReq.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + + projResp, err := client.Do(projReq) + if err != nil { + fmt.Fprintf(os.Stderr, "Error fetching projects: %v\n", err) + return + } + defer projResp.Body.Close() + + if projResp.StatusCode == http.StatusOK { + var projects []map[string]interface{} + body, _ := io.ReadAll(projResp.Body) + if err := json.Unmarshal(body, &projects); err == nil { + fmt.Println("Available Projects:") + for _, proj := range projects { + fmt.Printf("\nProject Name: %v\n", proj["name"]) + fmt.Printf("Project Key: %v\n", proj["key"]) + fmt.Printf("Project ID: %v\n", proj["id"]) + + // For each project, try to get environments + if projID, ok := proj["id"].(string); ok { + envReq, _ := http.NewRequest("GET", fmt.Sprintf("%s/v2/projects/%s/envs", config.PermitBaseURL, projID), nil) + envReq.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + + envResp, err := client.Do(envReq) + if err == nil && envResp.StatusCode == http.StatusOK { + var envs []map[string]interface{} + envBody, _ := io.ReadAll(envResp.Body) + if err := json.Unmarshal(envBody, &envs); err == nil { + fmt.Println(" Environments:") + for _, env := range envs { + fmt.Printf(" - Name: %v\n", env["name"]) + fmt.Printf(" Key: %v\n", env["key"]) + fmt.Printf(" ID: %v\n", env["id"]) + } + } + envResp.Body.Close() + } + } + fmt.Println(strings.Repeat("-", 40)) + } + } + } else { + fmt.Println("Unable to list projects. Your API key might be environment-scoped.") + fmt.Println("\nTips for finding your project and environment IDs:") + fmt.Println("1. In the Permit.io dashboard, click on 'Copy Environment Key' - this often shows the context") + fmt.Println("2. Check the API Keys page in Settings - it may show the associated project/environment") + fmt.Println("3. Try using the project 'key' instead of 'name'") + fmt.Println("4. Contact Permit.io support for help identifying your project and environment IDs") + } +} + +// ValidateCSVRoles validates that all roles specified in the CSV data exist in the target Permit.io environment. +// It takes the CSV user data, HTTP client, and configuration parameters, then checks if all requested roles +// are already defined in the Permit.io project/environment. +// +// Parameters: +// - client: HTTP client for making API requests +// - config: Application configuration containing Permit.io credentials and project details +// - csvUsers: Slice of user maps from CSV file, each containing user data and roles +// +// Returns: +// - []string: List of roles that are requested in the CSV. If error is nil, these are all valid roles. +// If error is not nil, these are the missing roles that need to be created. +// - error: nil if all roles exist, error describing missing roles if validation fails +func ValidateCSVRoles(client *http.Client, config AppConfig, csvUsers []map[string]string) ([]string, error) { + // Extract all unique roles requested in the CSV + requestedRoles := extractUniqueRolesFromCSV(csvUsers) + + if len(requestedRoles) == 0 { + return []string{}, nil // No roles to validate + } + + // Get all existing roles from Permit.io + existingRoles, err := getExistingRoles(client, config) + if err != nil { + return requestedRoles, fmt.Errorf("failed to retrieve existing roles from Permit.io: %v", err) + } + + // Check which requested roles are missing + missingRoles := findMissingRoles(requestedRoles, existingRoles) + + if len(missingRoles) > 0 { + return missingRoles, fmt.Errorf("the following roles do not exist in Permit.io and must be created first: %s", + strings.Join(missingRoles, ", ")) + } + + // All roles exist + return requestedRoles, nil +} + +// extractUniqueRolesFromCSV parses the CSV user data and extracts all unique roles +// mentioned across all users. It handles the comma-separated roles field and +// removes duplicates and empty values. +// +// Parameters: +// - csvUsers: Slice of user maps from CSV file +// +// Returns: +// - []string: Slice of unique role names found in the CSV data +func extractUniqueRolesFromCSV(csvUsers []map[string]string) []string { + roleSet := make(map[string]bool) + + // Iterate through all users and collect their roles + for _, user := range csvUsers { + rolesStr, exists := user["roles"] + if !exists || rolesStr == "" { + continue + } + + // Split comma-separated roles and add to set + roles := strings.Split(rolesStr, ",") + for _, role := range roles { + role = strings.TrimSpace(role) + if role != "" { + roleSet[role] = true + } + } + } + + // Convert set to slice + var uniqueRoles []string + for role := range roleSet { + uniqueRoles = append(uniqueRoles, role) + } + + return uniqueRoles +} + +// getExistingRoles retrieves all role definitions from the specified Permit.io project/environment. +// It makes an API call to the Permit.io roles endpoint and parses the response to extract role names. +// +// Parameters: +// - client: HTTP client for making API requests +// - config: Application configuration containing API credentials and project details +// +// Returns: +// - []string: Slice of role names that exist in the Permit.io environment +// - error: Error if API call fails or response cannot be parsed +func getExistingRoles(client *http.Client, config AppConfig) ([]string, error) { + // Construct API URL for roles endpoint + url := fmt.Sprintf("%s/v2/schema/%s/%s/roles", config.PermitBaseURL, config.PermitProjectID, config.PermitEnvID) + + // Create HTTP request + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %v", err) + } + + // Set authorization header + req.Header.Set("Authorization", "Bearer "+config.PermitAPIKey) + req.Header.Set("Content-Type", "application/json") + + // Execute request + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("error making request: %v", err) + } + defer resp.Body.Close() + + // Check for successful response + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body)) + } + + // Read and parse response body + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("error reading response: %v", err) + } + + // Parse JSON response - try different response structures + var roles []string + var rolesData []interface{} + + // First try to unmarshal as direct array + var directRoles []interface{} + if err := json.Unmarshal(body, &directRoles); err == nil { + rolesData = directRoles + } else { + // If that fails, try as object with data/items/etc + var response map[string]interface{} + if err := json.Unmarshal(body, &response); err != nil { + return nil, fmt.Errorf("error parsing response as object or array: %v", err) + } + + // Look for roles in common response structures + if data, ok := response["data"].([]interface{}); ok { + rolesData = data + } else if items, ok := response["items"].([]interface{}); ok { + rolesData = items + } else if results, ok := response["results"].([]interface{}); ok { + rolesData = results + } else { + return nil, fmt.Errorf("unexpected response format: unable to find roles array") + } + } + + // Extract role names from the data + for _, roleData := range rolesData { + if roleObj, ok := roleData.(map[string]interface{}); ok { + // Try different possible field names for role identifier + if key, ok := roleObj["key"].(string); ok { + roles = append(roles, key) + } else if name, ok := roleObj["name"].(string); ok { + roles = append(roles, name) + } else if id, ok := roleObj["id"].(string); ok { + roles = append(roles, id) + } + } + } + + return roles, nil +} + +// findMissingRoles compares the requested roles against existing roles and returns +// a list of roles that are requested but do not exist in the target environment. +// +// Parameters: +// - requestedRoles: Slice of role names that are requested in the CSV +// - existingRoles: Slice of role names that exist in Permit.io +// +// Returns: +// - []string: Slice of role names that are missing (requested but don't exist) +func findMissingRoles(requestedRoles, existingRoles []string) []string { + // Create a set of existing roles for efficient lookup + existingSet := make(map[string]bool) + for _, role := range existingRoles { + existingSet[role] = true + } + + // Find requested roles that don't exist + var missingRoles []string + for _, requestedRole := range requestedRoles { + if !existingSet[requestedRole] { + missingRoles = append(missingRoles, requestedRole) + } + } + + return missingRoles +} diff --git a/cmd/cognito_test/user.creation.tool/readme.md b/cmd/cognito_test/user.creation.tool/readme.md new file mode 100644 index 00000000..e6f70815 --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/readme.md @@ -0,0 +1,496 @@ +# Cognito + Permit.io User Lifecycle Sync Tool + +A CLI tool that creates, updates, deletes, disables, and enables users in AWS Cognito and automatically syncs them to Permit.io with their Cognito Subject ID, maintaining role assignments. The tool is **idempotent** and supports **dry-run mode** with comprehensive **audit logging**. + +## Overview + +This tool: +1. Reads user data from a CSV file (supports comments with #) +2. **Idempotently** creates or updates users in AWS Cognito +3. **Idempotently** creates or updates corresponding users in Permit.io +4. **Intelligently manages roles** - ensures users have exactly the roles specified in the CSV (removes old roles, adds new ones) +5. Provides comprehensive **audit logging** for compliance +6. Supports **dry-run mode** for testing without side effects +7. Reports success/failure for each step + +### Key Features + +- **🔄 Idempotent Operations**: Safe to run multiple times with the same data +- **🎯 Smart Role Management**: Automatically adds/removes roles to match CSV specification +- **🔍 Dry-Run Mode**: Test operations without making actual changes +- **📋 Audit Logging**: Complete audit trail for compliance requirements +- **💬 CSV Comments**: Support for comment lines starting with # +- **⚡ Incremental Updates**: Only processes changes, skips existing data +- **🔐 User Access Control**: Disable/enable users in Cognito without deletion + +## Operation Modes + +### Delete Mode (`--delete-users`) + +Runs the inverse of the normal create operation, deleting any users listed in the CSV: +1. Reads user data from a CSV file +2. Finds each user in Permit.io by email (skips if not found) +3. Deletes the user from Permit.io (if exists) +4. Deletes the user from Cognito (if exists) +5. Reports success/failure for each step + +**Note**: For delete mode, only email addresses are required in the CSV file (names and roles are optional). + +```csv +email,first_name,last_name,admin,viewer +"foo1@gmail.com",,,, +"foo2@gmail.com",,,, +``` + +### Disable Mode (`--disable-users`) + +Disables users in AWS Cognito without deleting them. This prevents users from logging in while preserving their account and settings: +1. Reads user data from a CSV file +2. Checks if each user exists in Cognito +3. Disables the user account in Cognito (if exists and enabled) +4. Reports success/failure for each step +5. **Idempotent**: Reports "already disabled" for users who are already disabled + +**Important Notes**: +- Disabled users cannot authenticate or access applications +- User data, roles, and settings are preserved +- Users can be re-enabled later using `--enable-users` +- Only affects Cognito - does not modify Permit.io roles or user data +- **For disable mode, only email addresses are required in the CSV file (names and roles are optional)** + +### Enable Mode (`--enable-users`) + +Re-enables previously disabled users in AWS Cognito: +1. Reads user data from a CSV file +2. Checks if each user exists in Cognito +3. Enables the user account in Cognito (if exists and disabled) +4. Reports success/failure for each step +5. **Idempotent**: Reports "already enabled" for users who are already enabled + +**Important Notes**: +- Only works on existing Cognito users +- Does not create new users - use default mode for user creation +- Only affects Cognito enable/disable status - does not modify roles +- **For enable mode, only email addresses are required in the CSV file (names and roles are optional)** + +## Prerequisites + +1. **AWS Account** with: + - An existing Cognito User Pool + - Appropriate IAM permissions for Cognito operations + - AWS credentials configured + +2. **Permit.io Account** with: + - A project and environment set up + - API key with user creation permissions + +## Configuration + +### Environment Variables + +Create a `.env` file (see `.env.example`): + +```bash +# Permit.io Configuration +PERMIT_KEY=your-permit-api-key-here + +# AWS Cognito Configuration +COGNITO_USER_POOL_ID=us-east-1_xxxxxxxxx + +# AWS Configuration +AWS_REGION=us-east-1 +AWS_ACCESS_KEY_ID=your-access-key # Or use IAM role +AWS_SECRET_ACCESS_KEY=your-secret-key +# or use profile +AWS_PROFILE=name_of_sso_profile_that_is_already_logged_in +``` + +### CSV Format + +The CSV file should have the following format (no user_id needed): + +```csv +email,first_name,last_name,role1,role2,...,roleN +# This is a comment line - will be ignored +john.doe@example.com,John,Doe,admin,viewer +jane.smith@example.com,Jane,Smith,editor,viewer +# Another comment +bob.wilson@example.com,Bob,Wilson,admin +``` + +- **email**: User's email address (required for all operations, used as Cognito username) +- **first_name**: User's first name (required for create operations only, optional for delete/disable/enable) +- **last_name**: User's last name (required for create operations only, optional for delete/disable/enable) +- **role columns**: Up to 99 role assignments (empty cells are ignored) +- **Comments**: Lines starting with # are ignored + +**Important**: When creating users, both `first_name` and `last_name` are required. For delete, disable, and enable operations, only the `email` field is necessary. + +## Usage + +### Basic Usage + +```bash +# Load environment variables +export $(cat .env | xargs) + +# Create/update users (idempotent) +./cognito-permit-sync -project myproject -env production -csv users.csv + +# Dry run to see what would happen +./cognito-permit-sync -project myproject -env production -csv users.csv --dry-run + +# Delete users +./cognito-permit-sync -project myproject -env production -csv users.csv --delete-users + +# Disable users (prevents login, preserves account) +./cognito-permit-sync -project myproject -env production -csv users.csv --disable-users + +# Enable users (re-enables disabled accounts) +./cognito-permit-sync -project myproject -env production -csv users.csv --enable-users + +# Dry run operations (works with all modes) +./cognito-permit-sync -project myproject -env production -csv users.csv --delete-users --dry-run +./cognito-permit-sync -project myproject -env production -csv users.csv --disable-users --dry-run +./cognito-permit-sync -project myproject -env production -csv users.csv --enable-users --dry-run +``` + +### List Available Projects and Environments + +```bash +./cognito-permit-sync -project list +``` + +### Command Line Options + +- `-project`: Permit.io project ID or key (required, or "list" to show available projects) +- `-env`: Permit.io environment ID or key (required) +- `-csv`: Path to CSV file containing users (required) +- `-api-url`: Permit.io API base URL (default: https://api.permit.io) +- `--delete-users`: Delete users instead of creating/updating them +- `--disable-users`: Disable users in Cognito instead of creating/updating them +- `--enable-users`: Enable users in Cognito instead of creating/updating them +- `--dry-run`: Perform a dry run without making actual changes + +**Important**: Only one operation mode can be specified at a time (`--delete-users`, `--disable-users`, or `--enable-users`). If none are specified, the tool defaults to create/update mode. + +## How It Works + +### Create/Update Mode (Default) + +For each user in the CSV: + +1. **Checks if user exists in Cognito**: + - If exists: Retrieves existing user details + - If not exists: Creates new user with email as username, sets email_verified to true + +2. **Checks if user exists in Permit.io**: + - If exists: Uses existing user + - If not exists: Creates user with Cognito Subject ID as key + +3. **Manages roles intelligently**: + - Gets current roles assigned to user + - Removes roles that are no longer needed + - Adds new roles specified in CSV + - Skips roles that are already assigned correctly + +### Delete Mode (`--delete-users`) + +For each user in the CSV: + +1. **Finds user in Permit.io by email**: + - If found: Proceeds with deletion + - If not found: Skips Permit.io deletion + +2. **Deletes from Permit.io** (if user exists) + +3. **Checks if user exists in Cognito**: + - If found: Deletes user + - If not found: Skips Cognito deletion + +### Disable Mode (`--disable-users`) + +For each user in the CSV: + +1. **Checks if user exists in Cognito**: + - If not found: Reports error and skips + - If found: Proceeds with disable check + +2. **Checks current user status**: + - If already disabled: Reports "already disabled" and skips + - If enabled: Proceeds with disable operation + +3. **Disables user in Cognito**: + - Sets user's enabled status to false + - User cannot authenticate until re-enabled + - All user data and settings are preserved + +### Enable Mode (`--enable-users`) + +For each user in the CSV: + +1. **Checks if user exists in Cognito**: + - If not found: Reports error and skips + - If found: Proceeds with enable check + +2. **Checks current user status**: + - If already enabled: Reports "already enabled" and skips + - If disabled: Proceeds with enable operation + +3. **Enables user in Cognito**: + - Sets user's enabled status to true + - User can authenticate normally + - All previous settings and roles are restored + +### Dry-Run Mode (`--dry-run`) + +Works with all operation modes: +- Simulates all operations without making actual API calls +- Shows exactly what would be done +- Logs all actions to `dry-run-audit.log` +- Perfect for testing and validation +- **Recommended**: Always test with `--dry-run` first, especially for disable/enable operations + +## Audit Logging + +### Audit Files + +- **Normal operations**: Logged to `audit.log` +- **Dry-run operations**: Logged to `dry-run-audit.log` + +### Audit Log Format + +Each audit entry includes: +- Timestamp (YYYY-MM-DD HH:MM:SS) +- Action type (CREATE, DELETE, DISABLE, ENABLE, ASSIGN_ROLE, UNASSIGN_ROLE, SKIP) +- System (COGNITO, PERMIT) +- User identifier (email and/or subject ID) +- Result (SUCCESS, FAILURE, SKIPPED) +- Additional details + +### Sample Audit Entries + +``` +# Create/Update operations +2024-06-04 10:30:15 [CREATE] [COGNITO] [john.doe@example.com|abc123-def456] SUCCESS: User created successfully +2024-06-04 10:30:16 [SKIP] [PERMIT] [john.doe@example.com|abc123-def456] SKIPPED: User already exists +2024-06-04 10:30:17 [UNASSIGN_ROLE] [PERMIT] [john.doe@example.com] SUCCESS: role='old_role', Role removed successfully +2024-06-04 10:30:18 [ASSIGN_ROLE] [PERMIT] [john.doe@example.com] SUCCESS: role='admin', Role assigned successfully + +# Disable/Enable operations +2024-06-04 11:15:20 [DISABLE] [COGNITO] [john.doe@example.com] SUCCESS: User disabled successfully +2024-06-04 11:15:21 [SKIP] [COGNITO] [jane.smith@example.com] SKIPPED: User already disabled +2024-06-04 11:20:30 [ENABLE] [COGNITO] [john.doe@example.com] SUCCESS: User enabled successfully + +# Delete operations +2024-06-04 12:00:45 [DELETE] [PERMIT] [john.doe@example.com|abc123-def456] SUCCESS: User deleted successfully +2024-06-04 12:00:46 [DELETE] [COGNITO] [john.doe@example.com] SUCCESS: User deleted successfully +``` + +### Compliance Benefits + +- **Complete audit trail** of all user lifecycle operations +- **Immutable log entries** with precise timestamps +- **Action tracking** for both successful and failed operations +- **Role change tracking** for access control compliance +- **Dry-run logging** for change planning and approval processes + +## Output Example + +``` +🔍 DRY RUN MODE - No actual changes will be made +============================================================ +Found 2 users to import +Will create users in Cognito User Pool: us-east-2_21upuTkkT +Then sync to Permit.io project: ebde1e1e9623491cab6f8112e67bd61c +============================================================ + +Processing user 1/2: john.doe@example.com + ℹ️ User already exists in Cognito + ℹ️ User already exists in Permit.io with key: abc123-def456-789 + ✓ Removed role: old_admin + 🔍 [DRY RUN] Would assign role: editor + ℹ️ Role already assigned: viewer + ✅ [DRY RUN] User would be successfully processed + +Processing user 2/2: jane.smith@example.com + 🔍 [DRY RUN] Would create user in Cognito + 🔍 [DRY RUN] Would create user in Permit.io + 🔍 [DRY RUN] Would assign role: admin + ✅ [DRY RUN] User would be successfully processed + +============================================================ +IMPORT SUMMARY +============================================================ +Total users processed: 2 +Successfully created: 2 +Failed: 0 +Time taken: 1.234s +Average time per user: 617ms + +🔍 DRY RUN COMPLETED - Check dry-run-audit.log for details +``` + +## Error Handling + +The tool handles various error scenarios gracefully: + +- **Duplicate users**: Safely skips creation, proceeds with role management +- **Missing users**: Safely skips deletion if user doesn't exist +- **Partial failures**: Continues processing other users +- **API errors**: Detailed error messages with context +- **Network errors**: Proper error reporting and logging + +## Idempotent Behavior + +### Safe to Run Multiple Times + +- **User Creation**: Won't fail if user already exists +- **Role Management**: Only makes necessary changes (add missing roles, remove extra roles) +- **Partial Recovery**: Can complete partially failed runs +- **No Duplicate Data**: Smart detection prevents duplicate entries + +### Role Management Examples + +If a user currently has roles `[admin, viewer, old_role]` and CSV specifies `[admin, editor]`: +- ✅ Keeps: `admin` (already assigned) +- ➕ Adds: `editor` (new role) +- ➖ Removes: `viewer`, `old_role` (no longer needed) + +## IAM Permissions Required + +Your AWS credentials need these Cognito permissions: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "cognito-idp:AdminCreateUser", + "cognito-idp:AdminGetUser", + "cognito-idp:AdminDeleteUser", + "cognito-idp:AdminDisableUser", + "cognito-idp:AdminEnableUser" + ], + "Resource": "arn:aws:cognito-idp:REGION:ACCOUNT:userpool/USER_POOL_ID" + } + ] +} +``` + +**New Permissions Required**: +- `cognito-idp:AdminDisableUser`: Required for `--disable-users` functionality +- `cognito-idp:AdminEnableUser`: Required for `--enable-users` functionality + +## Best Practices + +1. **Always Dry-Run First**: Use `--dry-run` to validate changes before applying +2. **Review Audit Logs**: Check audit logs for compliance and troubleshooting +3. **Incremental Updates**: The tool handles incremental changes efficiently +4. **Backup Strategy**: Keep CSV files versioned for rollback capability +5. **Monitor Performance**: Use built-in timing information for optimization +6. **Test with Small Batches**: Validate with a few users before bulk operations +7. **Disable vs Delete**: + - Use `--disable-users` to temporarily prevent access while preserving user data + - Use `--delete-users` only when permanently removing users + - Disabled users can be re-enabled with `--enable-users` +8. **Staged Deployments**: Test disable/enable operations in development environments first + +## Troubleshooting + +### "User already exists" (No Longer an Error) +- ✅ **Fixed**: Tool now handles existing users gracefully +- ✅ **Action**: Continues with role management for existing users + +### Audit Log Analysis +```bash +# Check recent audit activity +tail -f audit.log + +# Filter for failures +grep "FAILURE" audit.log + +# Check role changes +grep "ROLE" audit.log + +# Check disable/enable operations +grep "DISABLE\|ENABLE" audit.log + +# Analyze dry-run results +cat dry-run-audit.log +``` + +### Disable/Enable Issues +- **Permission Errors**: Ensure your AWS credentials have `AdminDisableUser` and `AdminEnableUser` permissions +- **User Not Found**: Disable/enable operations only work on existing Cognito users +- **Already Disabled/Enabled**: The tool reports current state - this is normal idempotent behavior +- **Verification**: Check audit logs to confirm operations completed successfully + +### Role Synchronization Issues +- **Check audit log** for role assignment/removal details +- **Verify CSV format** for role columns +- **Use dry-run mode** to preview role changes + +### API Rate Limiting +- Built-in 100ms delays between operations +- Monitor API response times in console output +- Consider breaking large CSV files into smaller batches + +## Development + +### Running Tests +Set your .env with the required variables or make them part of your environment: + +```bash +PERMIT_KEY="permit_key_redacted..." +COGNITO_USER_POOL_ID="us-east-2_21upuTkkT" +AWS_REGION=us-east-2 +AWS_PROFILE=aarete +``` + +```bash +go test -tags=aws -v ./... +``` + +### Building for Different Platforms + +```bash +# Linux +GOOS=linux GOARCH=amd64 go build -o cognito-permit-sync-linux + +# macOS +GOOS=darwin GOARCH=amd64 go build -o cognito-permit-sync-darwin + +# Windows +GOOS=windows GOARCH=amd64 go build -o cognito-permit-sync.exe +``` + +## Recent Improvements ✨ + +- **✅ Idempotent Operations**: Safe to run multiple times +- **✅ Smart Role Management**: Automatically sync roles to match CSV +- **✅ Audit Logging**: Complete compliance trail with timestamps +- **✅ Dry-Run Mode**: Test changes without side effects +- **✅ CSV Comments**: Support for comment lines with # +- **✅ Better Error Handling**: Graceful handling of missing/existing users +- **✅ Performance Insights**: Detailed timing and success metrics +- **🆕 User Disable/Enable**: Temporarily disable users without deletion +- **🆕 Enhanced Access Control**: Fine-grained user access management +- **🆕 Extended Audit Trail**: Track all disable/enable operations +- **🆕 Idempotent Disable/Enable**: Smart state checking prevents unnecessary operations + +## Future Enhancements + +- [ ] Batch operations for even better performance +- [ ] Progress bar for large imports +- [ ] Export failed users to CSV for retry +- [ ] Support for custom Cognito attributes +- [ ] Multi-tenant support in Permit.io +- [ ] Configuration file support +- [ ] Integration with CI/CD pipelines + +## License + +[Your License Here] \ No newline at end of file diff --git a/cmd/cognito_test/user.creation.tool/run.delete.users.sh b/cmd/cognito_test/user.creation.tool/run.delete.users.sh new file mode 100755 index 00000000..a6426c84 --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/run.delete.users.sh @@ -0,0 +1,15 @@ +# permit stuff +export PERMIT_KEY="permit_key_redacted" +# +## Cognito stuff +export COGNITO_USER_POOL_ID="us-east-2_21upuTkkT" +# +## aws keys +##export AWS_ACCESS_KEY_ID= +##export AWS_SECRET_ACCESS_KEY= +##export AWS_SESSION_TOKEN= +export AWS_REGION=us-east-2 +export AWS_PROFILE=aarete +# must do a project list to get the guid values for the project and environment before making the call to import. +#go run ./... -project ebde1e1e9623491cab6f8112e67bd61c -env 9d6801123cfd4a0ea2ef1df2f430e9d3 -csv ./users.to.import.csv --delete-users --dry-run +go run ./... -project ebde1e1e9623491cab6f8112e67bd61c -env 9d6801123cfd4a0ea2ef1df2f430e9d3 -csv ./users.to.import.csv --delete-users \ No newline at end of file diff --git a/cmd/cognito_test/user.creation.tool/run.tool.sh b/cmd/cognito_test/user.creation.tool/run.tool.sh new file mode 100755 index 00000000..f35ada78 --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/run.tool.sh @@ -0,0 +1,16 @@ +# permit stuff +export PERMIT_KEY="permit_key_redacted" + +# Cognito stuff +export COGNITO_USER_POOL_ID="us-east-2_21upuTkkT" + +# aws keys +#export AWS_ACCESS_KEY_ID= +#export AWS_SECRET_ACCESS_KEY= +#export AWS_SESSION_TOKEN= +export AWS_REGION=us-east-2 +export AWS_PROFILE=aarete +# must do a project list to get the guid values for the project and environment before making the call to import. +#go run ./... -project list +go run ./... -project ebde1e1e9623491cab6f8112e67bd61c -env 9d6801123cfd4a0ea2ef1df2f430e9d3 -csv ./users.to.import.csv --dry-run +#go run ./... -project ebde1e1e9623491cab6f8112e67bd61c -env 9d6801123cfd4a0ea2ef1df2f430e9d3 -csv ./users.to.import.csv diff --git a/cmd/cognito_test/user.creation.tool/userlifecycle_test.go b/cmd/cognito_test/user.creation.tool/userlifecycle_test.go new file mode 100644 index 00000000..25679703 --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/userlifecycle_test.go @@ -0,0 +1,356 @@ +//go:build aws + +package main + +import ( + "context" + "flag" + "fmt" + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" + "github.com/joho/godotenv" +) + +// Test configuration +const ( + testCSVPath = "./temp-users.csv" + testProjectID = "ebde1e1e9623491cab6f8112e67bd61c" + testEnvID = "9d6801123cfd4a0ea2ef1df2f430e9d3" +) + +// Test data +var testUsers = []map[string]string{ + { + "email": "foo1@gmail.com", + "first_name": "john", + "last_name": "smith", + "roles": "editor,viewer", + }, + { + "email": "foo2@gmail.com", + "first_name": "jane", + "last_name": "smith", + "roles": "editor,viewer,admin", + }, +} + +func TestMain(m *testing.M) { + // Load environment variables + if err := godotenv.Overload(); err != nil { + fmt.Println("warning - problem loading .env file - ignoring.") + } + + // Run tests + code := m.Run() + + // Cleanup + if err := os.Remove(testCSVPath); err != nil && !os.IsNotExist(err) { + fmt.Printf("Warning: failed to cleanup test CSV file: %v\n", err) + } + + os.Exit(code) +} + +func TestUserLifecycle(t *testing.T) { + // Skip test if required environment variables are not set + if !checkRequiredEnvVars(t) { + return + } + + // Create test CSV file + if err := createTestCSV(); err != nil { + t.Fatalf("Failed to create test CSV: %v", err) + } + + // Test user creation + t.Run("CreateUsers", func(t *testing.T) { + testCreateUsers(t) + }) + + // Test user verification + t.Run("VerifyUsersExist", func(t *testing.T) { + testVerifyUsersExist(t) + }) + + // Test user deletion + t.Run("DeleteUsers", func(t *testing.T) { + testDeleteUsers(t) + }) + + // Test user deletion verification + t.Run("VerifyUsersDeleted", func(t *testing.T) { + testVerifyUsersDeleted(t) + }) +} + +func checkRequiredEnvVars(t *testing.T) bool { + required := []string{"PERMIT_KEY", "COGNITO_USER_POOL_ID", "AWS_REGION"} + missing := []string{} + + for _, env := range required { + if os.Getenv(env) == "" { + missing = append(missing, env) + } + } + + if len(missing) > 0 { + t.Skipf("Skipping integration test - missing required environment variables: %v", missing) + return false + } + + return true +} + +func createTestCSV() error { + csvContent := "email,first_name,last_name,role1,role2,role3\n" + csvContent += "foo1@gmail.com,john,smith,editor,viewer,\n" + csvContent += "foo2@gmail.com,jane,smith,editor,viewer,admin\n" + + return os.WriteFile(testCSVPath, []byte(csvContent), 0600) +} + +func testCreateUsers(t *testing.T) { + // Save original os.Args + originalArgs := os.Args + + // Set up args for user creation + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", testCSVPath, + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application (this will create its own audit logger internally) + err := run() + if err != nil { + t.Fatalf("Failed to create users: %v", err) + } + + t.Logf("Successfully created users") +} + +func testVerifyUsersExist(t *testing.T) { + ctx := t.Context() + + // Initialize clients + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + httpClient := &http.Client{Timeout: 30 * time.Second} + config := AppConfig{ + PermitAPIKey: os.Getenv("PERMIT_KEY"), + PermitProjectID: testProjectID, + PermitEnvID: testEnvID, + PermitBaseURL: "https://api.permit.io", + CognitoUserPoolID: os.Getenv("COGNITO_USER_POOL_ID"), + CognitoRegion: os.Getenv("AWS_REGION"), + } + + for _, user := range testUsers { + t.Run(fmt.Sprintf("VerifyUser_%s", user["email"]), func(t *testing.T) { + // Verify user exists in Cognito + cognitoSubjectID, err := getCognitoUserSubject(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + if err != nil { + t.Fatalf("Failed to find user %s in Cognito: %v", user["email"], err) + } + if cognitoSubjectID == "" { + t.Fatalf("User %s not found in Cognito", user["email"]) + } + t.Logf("User %s found in Cognito with subject ID: %s", user["email"], cognitoSubjectID) + + // Verify user exists in Permit.io + permitUserKey, err := findPermitUserByEmail(httpClient, config, user["email"]) + if err != nil { + t.Fatalf("Failed to find user %s in Permit.io: %v", user["email"], err) + } + if permitUserKey == "" { + t.Fatalf("User %s not found in Permit.io", user["email"]) + } + t.Logf("User %s found in Permit.io with key: %s", user["email"], permitUserKey) + + // Verify subject IDs match + if cognitoSubjectID != permitUserKey { + t.Fatalf("Subject ID mismatch for user %s: Cognito=%s, Permit.io=%s", + user["email"], cognitoSubjectID, permitUserKey) + } + t.Logf("Subject IDs match for user %s: %s", user["email"], cognitoSubjectID) + + // Verify roles are assigned in Permit.io + if user["roles"] != "" { + expectedRoles := strings.Split(user["roles"], ",") + assignedRoles, err := getPermitUserRoles(httpClient, config, permitUserKey) + if err != nil { + t.Fatalf("Failed to get roles for user %s: %v", user["email"], err) + } + + for _, expectedRole := range expectedRoles { + expectedRole = strings.TrimSpace(expectedRole) + if expectedRole == "" { + continue + } + found := false + for _, assignedRole := range assignedRoles { + if assignedRole == expectedRole { + found = true + break + } + } + if !found { + t.Fatalf("Expected role %s not found for user %s. Assigned roles: %v", + expectedRole, user["email"], assignedRoles) + } + } + t.Logf("All expected roles verified for user %s: %v", user["email"], expectedRoles) + } + }) + } +} + +func testDeleteUsers(t *testing.T) { + // Save original os.Args + originalArgs := os.Args + + // Set up args for user deletion + os.Args = []string{ + "cognito-permit-sync", + "-project", testProjectID, + "-env", testEnvID, + "-csv", testCSVPath, + "--delete-users", + } + + // Restore os.Args after test + defer func() { + os.Args = originalArgs + }() + + // Reset flags for testing + resetFlags() + + // Run the application in delete mode + err := run() + if err != nil { + t.Fatalf("Failed to delete users: %v", err) + } + + t.Logf("Successfully deleted users") +} + +func testVerifyUsersDeleted(t *testing.T) { + ctx := t.Context() + + // Initialize clients + cognitoClient, err := initializeCognitoClient() + if err != nil { + t.Fatalf("Failed to initialize Cognito client: %v", err) + } + + httpClient := &http.Client{Timeout: 30 * time.Second} + config := AppConfig{ + PermitAPIKey: os.Getenv("PERMIT_KEY"), + PermitProjectID: testProjectID, + PermitEnvID: testEnvID, + PermitBaseURL: "https://api.permit.io", + CognitoUserPoolID: os.Getenv("COGNITO_USER_POOL_ID"), + CognitoRegion: os.Getenv("AWS_REGION"), + } + + for _, user := range testUsers { + t.Run(fmt.Sprintf("VerifyUserDeleted_%s", user["email"]), func(t *testing.T) { + // Verify user is deleted from both systems with retry logic + const maxRetries = 12 // 1 minute with 5-second intervals + const retryInterval = 5 * time.Second + + var cognitoDeleted, permitDeleted bool + + for attempt := 0; attempt < maxRetries; attempt++ { + if attempt > 0 { + t.Logf("Retry attempt %d/%d for user %s", attempt+1, maxRetries, user["email"]) + time.Sleep(retryInterval) + } + + // Check Cognito deletion + if !cognitoDeleted { + cognitoSubjectID, err := getCognitoUserSubject(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + cognitoDeleted = (err != nil || cognitoSubjectID == "") + } + + // Check Permit.io deletion + if !permitDeleted { + permitUserKey, err := findPermitUserByEmail(httpClient, config, user["email"]) + permitDeleted = (err != nil || permitUserKey == "") + } + + // If both are deleted, we're done + if cognitoDeleted && permitDeleted { + break + } + } + + // Final verification + if !cognitoDeleted { + cognitoSubjectID, _ := getCognitoUserSubject(ctx, cognitoClient, config.CognitoUserPoolID, user["email"]) + t.Fatalf("User %s still exists in Cognito after %d attempts with subject ID: %s", + user["email"], maxRetries, cognitoSubjectID) + } + t.Logf("User %s successfully deleted from Cognito", user["email"]) + + if !permitDeleted { + permitUserKey, _ := findPermitUserByEmail(httpClient, config, user["email"]) + t.Fatalf("User %s still exists in Permit.io after %d attempts with key: %s", + user["email"], maxRetries, permitUserKey) + } + t.Logf("User %s successfully deleted from Permit.io", user["email"]) + }) + } +} + +// Helper function to get Cognito user subject ID +func getCognitoUserSubject(ctx context.Context, client *cognitoidentityprovider.Client, userPoolID, username string) (string, error) { + input := &cognitoidentityprovider.AdminGetUserInput{ + UserPoolId: aws.String(userPoolID), + Username: aws.String(username), + } + + result, err := client.AdminGetUser(ctx, input) + if err != nil { + // Check if it's a UserNotFoundException + if strings.Contains(err.Error(), "UserNotFoundException") || + strings.Contains(err.Error(), "User does not exist") { + return "", nil // User not found, return empty string + } + return "", err + } + + // Extract subject ID from user attributes + for _, attr := range result.UserAttributes { + if aws.ToString(attr.Name) == "sub" { + return aws.ToString(attr.Value), nil + } + } + + return "", fmt.Errorf("subject ID not found for user %s", username) +} + +// Helper function to reset flags for testing +func resetFlags() { + // Reset the default command line flag set + flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) +} diff --git a/cmd/cognito_test/user.creation.tool/users.to.import.csv b/cmd/cognito_test/user.creation.tool/users.to.import.csv new file mode 100644 index 00000000..441a358f --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/users.to.import.csv @@ -0,0 +1,3 @@ +email,first_name,last_name,admin,viewer +"foo1@gmail.com",john, smith,editor,viewer +"foo2@gmail.com",jane, smith,editor,viewer, admin diff --git a/cmd/cognito_test/user.creation.tool/validate_roles_test.go b/cmd/cognito_test/user.creation.tool/validate_roles_test.go new file mode 100644 index 00000000..0ca387cb --- /dev/null +++ b/cmd/cognito_test/user.creation.tool/validate_roles_test.go @@ -0,0 +1,402 @@ +//go:build aws + +package main + +import ( + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/joho/godotenv" +) + +// Test configuration constants +const ( + testProjectIDForRoles = "ebde1e1e9623491cab6f8112e67bd61c" + testEnvIDForRoles = "9d6801123cfd4a0ea2ef1df2f430e9d3" +) + +// Replace the existing TestValidateCSVRoles function with these separate functions: + +// setupTestConfig creates a test configuration for role validation tests +func setupTestConfig(t *testing.T) (AppConfig, *http.Client, bool) { + // Load environment variables + if err := godotenv.Overload(); err != nil { + t.Logf("Warning: problem loading .env file - ignoring: %v", err) + } + + // Skip test if required environment variables are not set + if !checkRequiredEnvVarsForRoles(t) { + return AppConfig{}, nil, false + } + + // Setup real HTTP client and configuration + httpClient := &http.Client{Timeout: 30 * time.Second} + config := AppConfig{ + PermitAPIKey: os.Getenv("PERMIT_KEY"), + PermitProjectID: testProjectIDForRoles, + PermitEnvID: testEnvIDForRoles, + PermitBaseURL: "https://api.permit.io", + } + + return config, httpClient, true +} + +func TestValidateCSVRoles_MissingRoles(t *testing.T) { + config, httpClient, ok := setupTestConfig(t) + if !ok { + return + } + + // Test CSV data with existing roles (admin, viewer, editor) and one non-existent role 'foo' + csvUsers := []map[string]string{ + { + "email": "user1@example.com", + "first_name": "John", + "last_name": "Doe", + "roles": "admin,viewer", + }, + { + "email": "user2@example.com", + "first_name": "Jane", + "last_name": "Smith", + "roles": "editor,foo", // 'foo' doesn't exist in real Permit.io + }, + { + "email": "user3@example.com", + "first_name": "Bob", + "last_name": "Wilson", + "roles": "viewer", + }, + } + + // Call the function under test with real API + result, err := ValidateCSVRoles(httpClient, config, csvUsers) + + // Verify that an error was returned for missing role 'foo' + if err == nil { + t.Fatalf("Expected error for missing role 'foo', but got nil. Returned roles: %v", result) + } + + // Verify the error message mentions the missing role + if !strings.Contains(err.Error(), "foo") { + t.Errorf("Error message should mention missing role 'foo', got: %s", err.Error()) + } + + // Verify that 'foo' is in the list of missing roles + foundFoo := false + for _, role := range result { + if role == "foo" { + foundFoo = true + break + } + } + if !foundFoo { + t.Errorf("Expected 'foo' to be in missing roles list, got %v", result) + } + + // Verify the error message format + if !strings.Contains(err.Error(), "the following roles do not exist in Permit.io") { + t.Errorf("Error message should contain expected prefix, got: %s", err.Error()) + } + + t.Logf("Successfully detected missing role 'foo'. Missing roles: %v", result) +} + +func TestValidateCSVRoles_AllRolesExist(t *testing.T) { + config, httpClient, ok := setupTestConfig(t) + if !ok { + return + } + + // Test CSV data with only roles that should exist (admin, viewer, editor) + csvUsers := []map[string]string{ + { + "email": "user1@example.com", + "first_name": "John", + "last_name": "Doe", + "roles": "admin,viewer", + }, + { + "email": "user2@example.com", + "first_name": "Jane", + "last_name": "Smith", + "roles": "editor,admin", + }, + } + + // Call the function under test with real API + result, err := ValidateCSVRoles(httpClient, config, csvUsers) + + // Verify that no error was returned since all roles should exist + if err != nil { + t.Fatalf("Expected no error when all roles exist, but got: %v", err) + } + + // Verify that all unique requested roles are returned + expectedRoleCount := 3 // admin, viewer, editor + if len(result) != expectedRoleCount { + t.Errorf("Expected %d unique roles, got %d: %v", expectedRoleCount, len(result), result) + } + + // Verify expected roles are present + expectedRoles := map[string]bool{ + "admin": false, + "viewer": false, + "editor": false, + } + + for _, role := range result { + if _, exists := expectedRoles[role]; exists { + expectedRoles[role] = true + } else { + t.Errorf("Unexpected role in result: %s", role) + } + } + + // Check that all expected roles were found + for role, found := range expectedRoles { + if !found { + t.Errorf("Expected role '%s' not found in result", role) + } + } + + t.Logf("Successfully validated all existing roles: %v", result) +} + +func TestValidateCSVRoles_EmptyCSV(t *testing.T) { + config, httpClient, ok := setupTestConfig(t) + if !ok { + return + } + + // Empty CSV data + csvUsers := []map[string]string{} + + // Call the function under test + result, err := ValidateCSVRoles(httpClient, config, csvUsers) + + // Verify that no error was returned + if err != nil { + t.Fatalf("Expected no error for empty CSV, but got: %v", err) + } + + // Verify that no roles are returned + if len(result) != 0 { + t.Errorf("Expected empty result for empty CSV, got %v", result) + } + + t.Logf("Successfully handled empty CSV") +} + +func TestValidateCSVRoles_NoRolesInCSV(t *testing.T) { + config, httpClient, ok := setupTestConfig(t) + if !ok { + return + } + + // CSV data with users but no roles + csvUsers := []map[string]string{ + { + "email": "user1@example.com", + "first_name": "John", + "last_name": "Doe", + "roles": "", // empty roles + }, + { + "email": "user2@example.com", + "first_name": "Jane", + "last_name": "Smith", + // no roles field + }, + } + + // Call the function under test + result, err := ValidateCSVRoles(httpClient, config, csvUsers) + + // Verify that no error was returned + if err != nil { + t.Fatalf("Expected no error when no roles specified, but got: %v", err) + } + + // Verify that no roles are returned + if len(result) != 0 { + t.Errorf("Expected empty result when no roles specified, got %v", result) + } + + t.Logf("Successfully handled CSV with no roles") +} + +// TestExtractUniqueRolesFromCSV tests the role extraction helper function +func TestExtractUniqueRolesFromCSV(t *testing.T) { + t.Run("ExtractUniqueRoles_NormalCase", func(t *testing.T) { + csvUsers := []map[string]string{ + {"roles": "admin,viewer"}, + {"roles": "editor,admin"}, // admin is duplicate + {"roles": "viewer"}, // viewer is duplicate + {"roles": ""}, // empty roles + } + + result := extractUniqueRolesFromCSV(csvUsers) + + // Should get 3 unique roles + expectedCount := 3 + if len(result) != expectedCount { + t.Errorf("Expected %d unique roles, got %d: %v", expectedCount, len(result), result) + } + + // Check that all expected roles are present + expectedRoles := map[string]bool{ + "admin": false, + "viewer": false, + "editor": false, + } + + for _, role := range result { + if _, exists := expectedRoles[role]; exists { + expectedRoles[role] = true + } else { + t.Errorf("Unexpected role: %s", role) + } + } + + // Verify all expected roles were found + for role, found := range expectedRoles { + if !found { + t.Errorf("Expected role '%s' not found", role) + } + } + }) + + t.Run("ExtractUniqueRoles_WithWhitespace", func(t *testing.T) { + csvUsers := []map[string]string{ + {"roles": " admin , viewer "}, // roles with whitespace + {"roles": "editor, admin "}, // more whitespace + } + + result := extractUniqueRolesFromCSV(csvUsers) + + // Verify whitespace is trimmed and duplicates removed + expectedRoles := map[string]bool{ + "admin": false, + "viewer": false, + "editor": false, + } + + if len(result) != 3 { + t.Errorf("Expected 3 unique roles, got %d: %v", len(result), result) + } + + for _, role := range result { + if _, exists := expectedRoles[role]; exists { + expectedRoles[role] = true + } else { + t.Errorf("Unexpected role: %s", role) + } + } + + // Verify all expected roles were found + for role, found := range expectedRoles { + if !found { + t.Errorf("Expected role '%s' not found", role) + } + } + }) +} + +// TestFindMissingRoles tests the missing roles detection helper function +func TestFindMissingRoles(t *testing.T) { + t.Run("FindMissingRoles_SomeMissing", func(t *testing.T) { + requestedRoles := []string{"admin", "viewer", "foo", "bar"} + existingRoles := []string{"admin", "viewer", "editor"} + + result := findMissingRoles(requestedRoles, existingRoles) + + expectedMissing := map[string]bool{ + "foo": false, + "bar": false, + } + + if len(result) != 2 { + t.Errorf("Expected 2 missing roles, got %d: %v", len(result), result) + } + + for _, role := range result { + if _, exists := expectedMissing[role]; exists { + expectedMissing[role] = true + } else { + t.Errorf("Unexpected missing role: %s", role) + } + } + + // Verify all expected missing roles were found + for role, found := range expectedMissing { + if !found { + t.Errorf("Expected missing role '%s' not found", role) + } + } + }) + + t.Run("FindMissingRoles_NoneMissing", func(t *testing.T) { + requestedRoles := []string{"admin", "viewer"} + existingRoles := []string{"admin", "viewer", "editor"} + + result := findMissingRoles(requestedRoles, existingRoles) + + if len(result) != 0 { + t.Errorf("Expected no missing roles, got %v", result) + } + }) + + t.Run("FindMissingRoles_AllMissing", func(t *testing.T) { + requestedRoles := []string{"foo", "bar"} + existingRoles := []string{"admin", "viewer", "editor"} + + result := findMissingRoles(requestedRoles, existingRoles) + + if len(result) != 2 { + t.Errorf("Expected 2 missing roles, got %d: %v", len(result), result) + } + + expectedMissing := map[string]bool{ + "foo": false, + "bar": false, + } + + for _, role := range result { + if _, exists := expectedMissing[role]; exists { + expectedMissing[role] = true + } else { + t.Errorf("Unexpected missing role: %s", role) + } + } + + // Verify all expected missing roles were found + for role, found := range expectedMissing { + if !found { + t.Errorf("Expected missing role '%s' not found", role) + } + } + }) +} + +// checkRequiredEnvVarsForRoles checks if required environment variables are set for role validation tests +func checkRequiredEnvVarsForRoles(t *testing.T) bool { + required := []string{"PERMIT_KEY"} + missing := []string{} + + for _, env := range required { + if os.Getenv(env) == "" { + missing = append(missing, env) + } + } + + if len(missing) > 0 { + t.Skipf("Skipping role validation integration test - missing required environment variables: %v", missing) + return false + } + + return true +} diff --git a/devbox.json b/devbox.json index 09d256e5..1928d964 100644 --- a/devbox.json +++ b/devbox.json @@ -15,7 +15,7 @@ "COGNITO_CLIENT_SECRET": "aaknqeq9ajr07qjch4tkq38ulghvn2i8v7tn3d2fcv44uevfemf", "COGNITO_DOMAIN": "https://us-east-21y6po8rr8.auth.us-east-2.amazoncognito.com", "COGNITO_REGION": "us-east-2", - "COGNITO_USER_POOL_ID": "us-east-2_1y6po8rR8", + "COGNITO_USER_POOL_ID": "us-east-2_21upuTkkT", "DB_NOSSL": "true", "DOCUMENT_CLEAN_URL": "http://localstack:4566/queue/us-east-1/000000000000/document_clean", "DOCUMENT_INIT_URL": "http://localstack:4566/queue/us-east-1/000000000000/document_init", diff --git a/go.mod b/go.mod index 3a982405..f16d5272 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/alitto/pond/v2 v2.3.4 github.com/aws/aws-sdk-go-v2 v1.36.3 github.com/aws/aws-sdk-go-v2/config v1.29.9 + github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.53.0 github.com/aws/aws-sdk-go-v2/service/s3 v1.78.1 github.com/aws/aws-sdk-go-v2/service/sqs v1.38.1 github.com/aws/aws-sdk-go-v2/service/textract v1.35.1 @@ -24,6 +25,7 @@ require ( github.com/oapi-codegen/echo-middleware v1.0.2 github.com/oapi-codegen/runtime v1.1.1 github.com/pdfcpu/pdfcpu v0.9.1 + github.com/permitio/permit-golang v1.2.5 github.com/prometheus/client_golang v1.21.1 github.com/stretchr/testify v1.10.0 github.com/swaggo/echo-swagger v1.4.1 @@ -121,9 +123,11 @@ require ( go.opentelemetry.io/proto/otlp v1.5.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.26.0 // indirect golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac // indirect golang.org/x/image v0.25.0 // indirect golang.org/x/mod v0.23.0 // indirect + golang.org/x/oauth2 v0.27.0 // indirect golang.org/x/sync v0.12.0 // indirect golang.org/x/term v0.30.0 // indirect golang.org/x/time v0.11.0 // indirect @@ -148,7 +152,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.25.1 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.1 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.33.17 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.33.17 github.com/aws/smithy-go v1.22.3 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/containerd/log v0.1.0 // indirect diff --git a/go.sum b/go.sum index 765cf585..bac746fb 100644 --- a/go.sum +++ b/go.sum @@ -31,6 +31,8 @@ github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo= github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.34 h1:ZNTqv4nIdE/DiBfUUfXcLZ/Spcuz+RjeziUtNJackkM= github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.34/go.mod h1:zf7Vcd1ViW7cPqYWEHLHJkS50X0JS2IKz9Cgaj6ugrs= +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.53.0 h1:3Vje2gVkUDNSksJ8NXLcLCSg5m/YtsTqSNfDupy3qeI= +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.53.0/go.mod h1:ygltZT++6Wn2uG4+tqE0NW1MkdEtb5W2O/CFc0xJX/g= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 h1:eAh2A4b5IzM/lum78bZ590jy36+d/aFLgKF/4Vd1xPE= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3/go.mod h1:0yKJC/kb8sAnmlYa6Zs3QVYqaC8ug2AbnNChv5Ox3uA= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.6.2 h1:t/gZFyrijKuSU0elA5kRngP/oU3mc0I+Dvp8HwRE4c0= @@ -272,6 +274,8 @@ github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNH github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= +github.com/permitio/permit-golang v1.2.5 h1:5XdT5ziFjmWh+GJ2WsCuv4qfEDXdKltknZ7iGnzdpFM= +github.com/permitio/permit-golang v1.2.5/go.mod h1:U3ytJkUh6mH7dPiBt7cWbVVsRSxAiJtnuL7FFhbDk8s= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -394,6 +398,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= +go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -413,6 +419,8 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= +golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= +golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/CHANGELOG.md new file mode 100644 index 00000000..0f22a157 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/CHANGELOG.md @@ -0,0 +1,699 @@ +# v1.53.0 (2025-05-14) + +* **Feature**: Add exceptions to WebAuthn operations. + +# v1.52.0 (2025-04-22) + +* **Feature**: This release adds refresh token rotation. + +# v1.51.4 (2025-04-03) + +* No change notes available for this release. + +# v1.51.3 (2025-03-14) + +* **Documentation**: Minor description updates to API parameters + +# v1.51.2 (2025-03-07) + +* No change notes available for this release. + +# v1.51.1 (2025-03-04.2) + +* **Bug Fix**: Add assurance test for operation order. + +# v1.51.0 (2025-03-04) + +* **Feature**: Added the capacity to return available challenges in admin authentication and to set version 3 of the pre token generation event for M2M ATC. + +# v1.50.0 (2025-02-27) + +* **Feature**: Track credential providers via User-Agent Feature ids +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.49.5 (2025-02-18) + +* **Bug Fix**: Bump go version to 1.22 +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.49.4 (2025-02-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.49.3 (2025-01-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.49.2 (2025-01-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.49.1 (2025-01-24) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.22.2. + +# v1.49.0 (2025-01-21) + +* **Feature**: corrects the dual-stack endpoint configuration for cognitoidp + +# v1.48.6 (2025-01-17) + +* **Bug Fix**: Fix bug where credentials weren't refreshed during retry loop. + +# v1.48.5 (2025-01-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.48.4 (2025-01-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.48.3 (2024-12-20) + +* No change notes available for this release. + +# v1.48.2 (2024-12-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.48.1 (2024-12-11) + +* **Documentation**: Updated descriptions for some API operations and parameters, corrected some errors in Cognito user pools + +# v1.48.0 (2024-12-09) + +* **Feature**: Change `CustomDomainConfig` from a required to an optional parameter for the `UpdateUserPoolDomain` operation. + +# v1.47.1 (2024-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.47.0 (2024-11-22) + +* **Feature**: Add support for users to sign up and sign in without passwords, using email and SMS OTPs and Passkeys. Add support for Passkeys based on WebAuthn. Add support for enhanced branding customization for hosted authentication pages with Amazon Cognito Managed Login. Add feature tiers with new pricing. + +# v1.46.6 (2024-11-18) + +* **Dependency Update**: Update to smithy-go v1.22.1. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.46.5 (2024-11-07) + +* **Bug Fix**: Adds case-insensitive handling of error message fields in service responses + +# v1.46.4 (2024-11-06) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.46.3 (2024-10-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.46.2 (2024-10-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.46.1 (2024-10-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.46.0 (2024-10-04) + +* **Feature**: Add support for HTTP client metrics. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.45.4 (2024-10-03) + +* No change notes available for this release. + +# v1.45.3 (2024-09-27) + +* No change notes available for this release. + +# v1.45.2 (2024-09-25) + +* No change notes available for this release. + +# v1.45.1 (2024-09-23) + +* No change notes available for this release. + +# v1.45.0 (2024-09-20) + +* **Feature**: Add tracing and metrics support to service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.44.1 (2024-09-17) + +* **Bug Fix**: **BREAKFIX**: Only generate AccountIDEndpointMode config for services that use it. This is a compiler break, but removes no actual functionality, as no services currently use the account ID in endpoint resolution. + +# v1.44.0 (2024-09-12) + +* **Feature**: Added email MFA option to user pools with advanced security features. + +# v1.43.4 (2024-09-04) + +* No change notes available for this release. + +# v1.43.3 (2024-09-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.43.2 (2024-08-15) + +* **Dependency Update**: Bump minimum Go version to 1.21. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.43.1 (2024-08-09) + +* **Documentation**: Fixed a description of AdvancedSecurityAdditionalFlows in Amazon Cognito user pool configuration. + +# v1.43.0 (2024-08-08) + +* **Feature**: Added support for threat protection for custom authentication in Amazon Cognito user pools. + +# v1.42.0 (2024-08-06) + +* **Feature**: Advanced security feature updates to include password history and log export for Cognito user pools. + +# v1.41.4 (2024-07-10.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.41.3 (2024-07-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.41.2 (2024-07-05) + +* No change notes available for this release. + +# v1.41.1 (2024-06-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.41.0 (2024-06-26) + +* **Feature**: Support list-of-string endpoint parameter. + +# v1.40.1 (2024-06-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.40.0 (2024-06-18) + +* **Feature**: Track usage of various AWS SDK features in user-agent string. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.39.0 (2024-06-17) + +* **Feature**: Add v2 smoke tests and smithy smokeTests trait for SDK testing. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.5 (2024-06-07) + +* **Bug Fix**: Add clock skew correction on all service clients +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.4 (2024-06-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.3 (2024-05-23) + +* No change notes available for this release. + +# v1.38.2 (2024-05-16) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.1 (2024-05-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.0 (2024-05-08) + +* **Feature**: Add EXTERNAL_PROVIDER enum value to UserStatusType. +* **Bug Fix**: GoDoc improvement + +# v1.37.0 (2024-04-26) + +* **Feature**: Add LimitExceededException to SignUp errors + +# v1.36.5 (2024-04-16) + +* No change notes available for this release. + +# v1.36.4 (2024-04-11) + +* No change notes available for this release. + +# v1.36.3 (2024-03-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.2 (2024-03-18) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.36.1 (2024-03-15) + +* No change notes available for this release. + +# v1.36.0 (2024-03-08) + +* **Feature**: Add ConcurrentModificationException to SetUserPoolMfaConfig + +# v1.35.2 (2024-03-07) + +* **Bug Fix**: Remove dependency on go-cmp. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.1 (2024-02-23) + +* **Bug Fix**: Move all common, SDK-side middleware stack ops into the service client module to prevent cross-module compatibility issues in the future. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.0 (2024-02-22) + +* **Feature**: Add middleware stack snapshot tests. + +# v1.34.3 (2024-02-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.34.2 (2024-02-20) + +* **Bug Fix**: When sourcing values for a service's `EndpointParameters`, the lack of a configured region (i.e. `options.Region == ""`) will now translate to a `nil` value for `EndpointParameters.Region` instead of a pointer to the empty string `""`. This will result in a much more explicit error when calling an operation instead of an obscure hostname lookup failure. + +# v1.34.1 (2024-02-15) + +* **Bug Fix**: Correct failure to determine the error type in awsJson services that could occur when errors were modeled with a non-string `code` field. + +# v1.34.0 (2024-02-13) + +* **Feature**: Bump minimum Go version to 1.20 per our language support policy. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.33.0 (2024-02-01) + +* **Feature**: Added CreateIdentityProvider and UpdateIdentityProvider details for new SAML IdP features + +# v1.32.1 (2024-01-04) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.0 (2023-12-18) + +* **Feature**: Amazon Cognito now supports trigger versions that define the fields in the request sent to pre token generation Lambda triggers. + +# v1.31.6 (2023-12-15) + +* No change notes available for this release. + +# v1.31.5 (2023-12-08) + +* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. + +# v1.31.4 (2023-12-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.3 (2023-12-06) + +* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. + +# v1.31.2 (2023-12-01) + +* **Bug Fix**: Correct wrapping of errors in authentication workflow. +* **Bug Fix**: Correctly recognize cache-wrapped instances of AnonymousCredentials at client construction. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.1 (2023-11-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.0 (2023-11-29) + +* **Feature**: Expose Options() accessor on service clients. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.5 (2023-11-28.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.4 (2023-11-28) + +* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. + +# v1.30.3 (2023-11-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.2 (2023-11-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.1 (2023-11-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.0 (2023-11-01) + +* **Feature**: Adds support for configured endpoints via environment variables and the AWS shared configuration file. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.0 (2023-10-31) + +* **Feature**: **BREAKING CHANGE**: Bump minimum go version to 1.19 per the revised [go version support policy](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-aligns-with-go-release-policy-on-supported-runtimes/). +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.28.0 (2023-10-24) + +* **Feature**: **BREAKFIX**: Correct nullability and default value representation of various input fields across a large number of services. Calling code that references one or more of the affected fields will need to update usage accordingly. See [2162](https://github.com/aws/aws-sdk-go-v2/issues/2162). + +# v1.27.2 (2023-10-12) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.1 (2023-10-06) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.27.0 (2023-09-27) + +* **Feature**: The UserPoolType Status field is no longer used. + +# v1.26.1 (2023-08-31) + +* No change notes available for this release. + +# v1.26.0 (2023-08-29) + +* **Feature**: Added API example requests and responses for several operations. Fixed the validation regex for user pools Identity Provider name. + +# v1.25.4 (2023-08-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.3 (2023-08-18) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.2 (2023-08-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.1 (2023-08-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.25.0 (2023-08-02) + +* **Feature**: New feature that logs Cognito user pool error messages to CloudWatch logs. + +# v1.24.1 (2023-08-01) + +* No change notes available for this release. + +# v1.24.0 (2023-07-31) + +* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.1 (2023-07-28) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.23.0 (2023-07-13) + +* **Feature**: API model updated in Amazon Cognito +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.12 (2023-06-15) + +* No change notes available for this release. + +# v1.22.11 (2023-06-13) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.10 (2023-05-04) + +* No change notes available for this release. + +# v1.22.9 (2023-04-24) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.8 (2023-04-10) + +* No change notes available for this release. + +# v1.22.7 (2023-04-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.6 (2023-03-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.5 (2023-03-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.4 (2023-02-22) + +* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. + +# v1.22.3 (2023-02-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.2 (2023-02-15) + +* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. +* **Bug Fix**: Correct error type parsing for restJson services. + +# v1.22.1 (2023-02-03) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.22.0 (2023-01-05) + +* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). + +# v1.21.4 (2022-12-15) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.3 (2022-12-07) + +* No change notes available for this release. + +# v1.21.2 (2022-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.1 (2022-10-24) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.21.0 (2022-10-21) + +* **Feature**: This release adds a new "DeletionProtection" field to the UserPool in Cognito. Application admins can configure this value with either ACTIVE or INACTIVE value. Setting this field to ACTIVE will prevent a user pool from accidental deletion. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.1 (2022-09-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.20.0 (2022-09-14) + +* **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.0 (2022-09-02) + +* **Feature**: This release adds a new "AuthSessionValidity" field to the UserPoolClient in Cognito. Application admins can configure this value for their users' authentication duration, which is currently fixed at 3 minutes, up to 15 minutes. Setting this field will also apply to the SMS MFA authentication flow. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.6 (2022-08-31) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.5 (2022-08-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.4 (2022-08-18) + +* **Documentation**: This change is being made simply to fix the public documentation based on the models. We have included the PasswordChange and ResendCode events, along with the Pass, Fail and InProgress status. We have removed the Success and Failure status which are never returned by our APIs. + +# v1.18.3 (2022-08-11) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.2 (2022-08-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.1 (2022-08-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.0 (2022-08-03) + +* **Feature**: Add a new exception type, ForbiddenException, that is returned when request is not allowed + +# v1.17.4 (2022-08-01) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.3 (2022-07-05) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.2 (2022-06-29) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.1 (2022-06-07) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.17.0 (2022-05-31) + +* **Feature**: Amazon Cognito now supports IP Address propagation for all unauthenticated APIs (e.g. SignUp, ForgotPassword). + +# v1.16.0 (2022-05-24) + +* **Feature**: Amazon Cognito now supports requiring attribute verification (ex. email and phone number) before update. + +# v1.15.5 (2022-05-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.4 (2022-04-25) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.3 (2022-03-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.2 (2022-03-24) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.1 (2022-03-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.15.0 (2022-03-15) + +* **Feature**: Updated EmailConfigurationType and SmsConfigurationType to reflect that you can now choose Amazon SES and Amazon SNS resources in the same Region. + +# v1.14.0 (2022-03-08) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.13.0 (2022-02-24) + +* **Feature**: API client updated +* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.12.0 (2022-01-14) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.11.0 (2022-01-07) + +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.10.0 (2021-12-21) + +* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens. + +# v1.9.2 (2021-12-02) + +* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.9.1 (2021-11-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.9.0 (2021-11-12) + +* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. + +# v1.8.0 (2021-11-06) + +* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.7.0 (2021-10-21) + +* **Feature**: Updated to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.6.2 (2021-10-11) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.6.1 (2021-09-17) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.6.0 (2021-08-27) + +* **Feature**: Updated API model to latest revision. +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.5.1 (2021-08-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.5.0 (2021-08-04) + +* **Feature**: Updated to latest API model. +* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.1 (2021-07-15) + +* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.0 (2021-06-25) + +* **Feature**: API client updated +* **Feature**: Updated `github.com/aws/smithy-go` to latest version +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.3 (2021-06-11) + +* **Documentation**: Updated to latest API model. + +# v1.3.2 (2021-06-04) + +* No change notes available for this release. + +# v1.3.1 (2021-05-20) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.3.0 (2021-05-14) + +* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. +* **Dependency Update**: Updated to the latest SDK module versions + diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_client.go new file mode 100644 index 00000000..5d5a2c08 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_client.go @@ -0,0 +1,944 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "errors" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/defaults" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/aws/retry" + "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + internalmiddleware "github.com/aws/aws-sdk-go-v2/internal/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + smithydocument "github.com/aws/smithy-go/document" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net" + "net/http" + "sync/atomic" + "time" +) + +const ServiceID = "Cognito Identity Provider" +const ServiceAPIVersion = "2016-04-18" + +type operationMetrics struct { + Duration metrics.Float64Histogram + SerializeDuration metrics.Float64Histogram + ResolveIdentityDuration metrics.Float64Histogram + ResolveEndpointDuration metrics.Float64Histogram + SignRequestDuration metrics.Float64Histogram + DeserializeDuration metrics.Float64Histogram +} + +func (m *operationMetrics) histogramFor(name string) metrics.Float64Histogram { + switch name { + case "client.call.duration": + return m.Duration + case "client.call.serialization_duration": + return m.SerializeDuration + case "client.call.resolve_identity_duration": + return m.ResolveIdentityDuration + case "client.call.resolve_endpoint_duration": + return m.ResolveEndpointDuration + case "client.call.signing_duration": + return m.SignRequestDuration + case "client.call.deserialization_duration": + return m.DeserializeDuration + default: + panic("unrecognized operation metric") + } +} + +func timeOperationMetric[T any]( + ctx context.Context, metric string, fn func() (T, error), + opts ...metrics.RecordMetricOption, +) (T, error) { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + start := time.Now() + v, err := fn() + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + return v, err +} + +func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { + instr := getOperationMetrics(ctx).histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + var ended bool + start := time.Now() + return func() { + if ended { + return + } + ended = true + + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + } +} + +func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { + return func(o *metrics.RecordMetricOptions) { + o.Properties.Set("rpc.service", middleware.GetServiceID(ctx)) + o.Properties.Set("rpc.method", middleware.GetOperationName(ctx)) + } +} + +type operationMetricsKey struct{} + +func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider") + om := &operationMetrics{} + + var err error + + om.Duration, err = operationMetricTimer(meter, "client.call.duration", + "Overall call duration (including retries and time to send or receive request and response body)") + if err != nil { + return nil, err + } + om.SerializeDuration, err = operationMetricTimer(meter, "client.call.serialization_duration", + "The time it takes to serialize a message body") + if err != nil { + return nil, err + } + om.ResolveIdentityDuration, err = operationMetricTimer(meter, "client.call.auth.resolve_identity_duration", + "The time taken to acquire an identity (AWS credentials, bearer token, etc) from an Identity Provider") + if err != nil { + return nil, err + } + om.ResolveEndpointDuration, err = operationMetricTimer(meter, "client.call.resolve_endpoint_duration", + "The time it takes to resolve an endpoint (endpoint resolver, not DNS) for the request") + if err != nil { + return nil, err + } + om.SignRequestDuration, err = operationMetricTimer(meter, "client.call.auth.signing_duration", + "The time it takes to sign a request") + if err != nil { + return nil, err + } + om.DeserializeDuration, err = operationMetricTimer(meter, "client.call.deserialization_duration", + "The time it takes to deserialize a message body") + if err != nil { + return nil, err + } + + return context.WithValue(parent, operationMetricsKey{}, om), nil +} + +func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Histogram, error) { + return m.Float64Histogram(name, func(o *metrics.InstrumentOptions) { + o.UnitLabel = "s" + o.Description = desc + }) +} + +func getOperationMetrics(ctx context.Context) *operationMetrics { + return ctx.Value(operationMetricsKey{}).(*operationMetrics) +} + +func operationTracer(p tracing.TracerProvider) tracing.Tracer { + return p.Tracer("github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider") +} + +// Client provides the API client to make operations call for Amazon Cognito +// Identity Provider. +type Client struct { + options Options + + // Difference between the time reported by the server and the client + timeOffset *atomic.Int64 +} + +// New returns an initialized Client based on the functional options. Provide +// additional functional options to further configure the behavior of the client, +// such as changing the client's endpoint or adding custom middleware behavior. +func New(options Options, optFns ...func(*Options)) *Client { + options = options.Copy() + + resolveDefaultLogger(&options) + + setResolvedDefaultsMode(&options) + + resolveRetryer(&options) + + resolveHTTPClient(&options) + + resolveHTTPSignerV4(&options) + + resolveEndpointResolverV2(&options) + + resolveTracerProvider(&options) + + resolveMeterProvider(&options) + + resolveAuthSchemeResolver(&options) + + for _, fn := range optFns { + fn(&options) + } + + finalizeRetryMaxAttempts(&options) + + ignoreAnonymousAuth(&options) + + wrapWithAnonymousAuth(&options) + + resolveAuthSchemes(&options) + + client := &Client{ + options: options, + } + + initializeTimeOffsetResolver(client) + + return client +} + +// Options returns a copy of the client configuration. +// +// Callers SHOULD NOT perform mutations on any inner structures within client +// config. Config overrides should instead be made on a per-operation basis through +// functional options. +func (c *Client) Options() Options { + return c.options.Copy() +} + +func (c *Client) invokeOperation( + ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error, +) ( + result interface{}, metadata middleware.Metadata, err error, +) { + ctx = middleware.ClearStackValues(ctx) + ctx = middleware.WithServiceID(ctx, ServiceID) + ctx = middleware.WithOperationName(ctx, opID) + + stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) + options := c.options.Copy() + + for _, fn := range optFns { + fn(&options) + } + + finalizeOperationRetryMaxAttempts(&options, *c) + + finalizeClientEndpointResolverOptions(&options) + + for _, fn := range stackFns { + if err := fn(stack, options); err != nil { + return nil, metadata, err + } + } + + for _, fn := range options.APIOptions { + if err := fn(stack); err != nil { + return nil, metadata, err + } + } + + ctx, err = withOperationMetrics(ctx, options.MeterProvider) + if err != nil { + return nil, metadata, err + } + + tracer := operationTracer(options.TracerProvider) + spanName := fmt.Sprintf("%s.%s", ServiceID, opID) + + ctx = tracing.WithOperationTracer(ctx, tracer) + + ctx, span := tracer.StartSpan(ctx, spanName, func(o *tracing.SpanOptions) { + o.Kind = tracing.SpanKindClient + o.Properties.Set("rpc.system", "aws-api") + o.Properties.Set("rpc.method", opID) + o.Properties.Set("rpc.service", ServiceID) + }) + endTimer := startMetricTimer(ctx, "client.call.duration") + defer endTimer() + defer span.End() + + handler := smithyhttp.NewClientHandlerWithOptions(options.HTTPClient, func(o *smithyhttp.ClientHandler) { + o.Meter = options.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider") + }) + decorated := middleware.DecorateHandler(handler, stack) + result, metadata, err = decorated.Handle(ctx, params) + if err != nil { + span.SetProperty("exception.type", fmt.Sprintf("%T", err)) + span.SetProperty("exception.message", err.Error()) + + var aerr smithy.APIError + if errors.As(err, &aerr) { + span.SetProperty("api.error_code", aerr.ErrorCode()) + span.SetProperty("api.error_message", aerr.ErrorMessage()) + span.SetProperty("api.error_fault", aerr.ErrorFault().String()) + } + + err = &smithy.OperationError{ + ServiceID: ServiceID, + OperationName: opID, + Err: err, + } + } + + span.SetProperty("error", err != nil) + if err == nil { + span.SetStatus(tracing.SpanStatusOK) + } else { + span.SetStatus(tracing.SpanStatusError) + } + + return result, metadata, err +} + +type operationInputKey struct{} + +func setOperationInput(ctx context.Context, input interface{}) context.Context { + return middleware.WithStackValue(ctx, operationInputKey{}, input) +} + +func getOperationInput(ctx context.Context) interface{} { + return middleware.GetStackValue(ctx, operationInputKey{}) +} + +type setOperationInputMiddleware struct { +} + +func (*setOperationInputMiddleware) ID() string { + return "setOperationInput" +} + +func (m *setOperationInputMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + ctx = setOperationInput(ctx, in.Parameters) + return next.HandleSerialize(ctx, in) +} + +func addProtocolFinalizerMiddlewares(stack *middleware.Stack, options Options, operation string) error { + if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, middleware.Before); err != nil { + return fmt.Errorf("add ResolveAuthScheme: %w", err) + } + if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", middleware.After); err != nil { + return fmt.Errorf("add GetIdentity: %v", err) + } + if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil { + return fmt.Errorf("add ResolveEndpointV2: %v", err) + } + if err := stack.Finalize.Insert(&signRequestMiddleware{options: options}, "ResolveEndpointV2", middleware.After); err != nil { + return fmt.Errorf("add Signing: %w", err) + } + return nil +} +func resolveAuthSchemeResolver(options *Options) { + if options.AuthSchemeResolver == nil { + options.AuthSchemeResolver = &defaultAuthSchemeResolver{} + } +} + +func resolveAuthSchemes(options *Options) { + if options.AuthSchemes == nil { + options.AuthSchemes = []smithyhttp.AuthScheme{ + internalauth.NewHTTPAuthScheme("aws.auth#sigv4", &internalauthsmithy.V4SignerAdapter{ + Signer: options.HTTPSignerV4, + Logger: options.Logger, + LogSigning: options.ClientLogMode.IsSigning(), + }), + } + } +} + +type noSmithyDocumentSerde = smithydocument.NoSerde + +type legacyEndpointContextSetter struct { + LegacyResolver EndpointResolver +} + +func (*legacyEndpointContextSetter) ID() string { + return "legacyEndpointContextSetter" +} + +func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + if m.LegacyResolver != nil { + ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) + } + + return next.HandleInitialize(ctx, in) + +} +func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { + return stack.Initialize.Add(&legacyEndpointContextSetter{ + LegacyResolver: o.EndpointResolver, + }, middleware.Before) +} + +func resolveDefaultLogger(o *Options) { + if o.Logger != nil { + return + } + o.Logger = logging.Nop{} +} + +func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { + return middleware.AddSetLoggerMiddleware(stack, o.Logger) +} + +func setResolvedDefaultsMode(o *Options) { + if len(o.resolvedDefaultsMode) > 0 { + return + } + + var mode aws.DefaultsMode + mode.SetFromString(string(o.DefaultsMode)) + + if mode == aws.DefaultsModeAuto { + mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) + } + + o.resolvedDefaultsMode = mode +} + +// NewFromConfig returns a new client from the provided config. +func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { + opts := Options{ + Region: cfg.Region, + DefaultsMode: cfg.DefaultsMode, + RuntimeEnvironment: cfg.RuntimeEnvironment, + HTTPClient: cfg.HTTPClient, + Credentials: cfg.Credentials, + APIOptions: cfg.APIOptions, + Logger: cfg.Logger, + ClientLogMode: cfg.ClientLogMode, + AppID: cfg.AppID, + } + resolveAWSRetryerProvider(cfg, &opts) + resolveAWSRetryMaxAttempts(cfg, &opts) + resolveAWSRetryMode(cfg, &opts) + resolveAWSEndpointResolver(cfg, &opts) + resolveUseDualStackEndpoint(cfg, &opts) + resolveUseFIPSEndpoint(cfg, &opts) + resolveBaseEndpoint(cfg, &opts) + return New(opts, optFns...) +} + +func resolveHTTPClient(o *Options) { + var buildable *awshttp.BuildableClient + + if o.HTTPClient != nil { + var ok bool + buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) + if !ok { + return + } + } else { + buildable = awshttp.NewBuildableClient() + } + + modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) + if err == nil { + buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { + if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { + dialer.Timeout = dialerTimeout + } + }) + + buildable = buildable.WithTransportOptions(func(transport *http.Transport) { + if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { + transport.TLSHandshakeTimeout = tlsHandshakeTimeout + } + }) + } + + o.HTTPClient = buildable +} + +func resolveRetryer(o *Options) { + if o.Retryer != nil { + return + } + + if len(o.RetryMode) == 0 { + modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) + if err == nil { + o.RetryMode = modeConfig.RetryMode + } + } + if len(o.RetryMode) == 0 { + o.RetryMode = aws.RetryModeStandard + } + + var standardOptions []func(*retry.StandardOptions) + if v := o.RetryMaxAttempts; v != 0 { + standardOptions = append(standardOptions, func(so *retry.StandardOptions) { + so.MaxAttempts = v + }) + } + + switch o.RetryMode { + case aws.RetryModeAdaptive: + var adaptiveOptions []func(*retry.AdaptiveModeOptions) + if len(standardOptions) != 0 { + adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { + ao.StandardOptions = append(ao.StandardOptions, standardOptions...) + }) + } + o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) + + default: + o.Retryer = retry.NewStandard(standardOptions...) + } +} + +func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { + if cfg.Retryer == nil { + return + } + o.Retryer = cfg.Retryer() +} + +func resolveAWSRetryMode(cfg aws.Config, o *Options) { + if len(cfg.RetryMode) == 0 { + return + } + o.RetryMode = cfg.RetryMode +} +func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { + if cfg.RetryMaxAttempts == 0 { + return + } + o.RetryMaxAttempts = cfg.RetryMaxAttempts +} + +func finalizeRetryMaxAttempts(o *Options) { + if o.RetryMaxAttempts == 0 { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func finalizeOperationRetryMaxAttempts(o *Options, client Client) { + if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { + if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { + return + } + o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) +} + +func addClientUserAgent(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "cognitoidentityprovider", goModuleVersion) + if len(options.AppID) > 0 { + ua.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID) + } + + return nil +} + +func getOrAddRequestUserAgent(stack *middleware.Stack) (*awsmiddleware.RequestUserAgent, error) { + id := (*awsmiddleware.RequestUserAgent)(nil).ID() + mw, ok := stack.Build.Get(id) + if !ok { + mw = awsmiddleware.NewRequestUserAgent() + if err := stack.Build.Add(mw, middleware.After); err != nil { + return nil, err + } + } + + ua, ok := mw.(*awsmiddleware.RequestUserAgent) + if !ok { + return nil, fmt.Errorf("%T for %s middleware did not match expected type", mw, id) + } + + return ua, nil +} + +type HTTPSignerV4 interface { + SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error +} + +func resolveHTTPSignerV4(o *Options) { + if o.HTTPSignerV4 != nil { + return + } + o.HTTPSignerV4 = newDefaultV4Signer(*o) +} + +func newDefaultV4Signer(o Options) *v4.Signer { + return v4.NewSigner(func(so *v4.SignerOptions) { + so.Logger = o.Logger + so.LogSigning = o.ClientLogMode.IsSigning() + }) +} + +func addClientRequestID(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.ClientRequestID{}, middleware.After) +} + +func addComputeContentLength(stack *middleware.Stack) error { + return stack.Build.Add(&smithyhttp.ComputeContentLength{}, middleware.After) +} + +func addRawResponseToMetadata(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.AddRawResponse{}, middleware.Before) +} + +func addRecordResponseTiming(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.RecordResponseTiming{}, middleware.After) +} + +func addSpanRetryLoop(stack *middleware.Stack, options Options) error { + return stack.Finalize.Insert(&spanRetryLoop{options: options}, "Retry", middleware.Before) +} + +type spanRetryLoop struct { + options Options +} + +func (*spanRetryLoop) ID() string { + return "spanRetryLoop" +} + +func (m *spanRetryLoop) HandleFinalize( + ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, +) ( + middleware.FinalizeOutput, middleware.Metadata, error, +) { + tracer := operationTracer(m.options.TracerProvider) + ctx, span := tracer.StartSpan(ctx, "RetryLoop") + defer span.End() + + return next.HandleFinalize(ctx, in) +} +func addStreamingEventsPayload(stack *middleware.Stack) error { + return stack.Finalize.Add(&v4.StreamingEventsPayload{}, middleware.Before) +} + +func addUnsignedPayload(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.UnsignedPayload{}, "ResolveEndpointV2", middleware.After) +} + +func addComputePayloadSHA256(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ComputePayloadSHA256{}, "ResolveEndpointV2", middleware.After) +} + +func addContentSHA256Header(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ContentSHA256Header{}, (*v4.ComputePayloadSHA256)(nil).ID(), middleware.After) +} + +func addIsWaiterUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureWaiter) + return nil + }) +} + +func addIsPaginatorUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeaturePaginator) + return nil + }) +} + +func addRetry(stack *middleware.Stack, o Options) error { + attempt := retry.NewAttemptMiddleware(o.Retryer, smithyhttp.RequestCloner, func(m *retry.Attempt) { + m.LogAttempts = o.ClientLogMode.IsRetries() + m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider") + }) + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { + return err + } + if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { + return err + } + return nil +} + +// resolves dual-stack endpoint configuration +func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { + if len(cfg.ConfigSources) == 0 { + return nil + } + value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) + if err != nil { + return err + } + if found { + o.EndpointOptions.UseDualStackEndpoint = value + } + return nil +} + +// resolves FIPS endpoint configuration +func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { + if len(cfg.ConfigSources) == 0 { + return nil + } + value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) + if err != nil { + return err + } + if found { + o.EndpointOptions.UseFIPSEndpoint = value + } + return nil +} + +func resolveAccountID(identity smithyauth.Identity, mode aws.AccountIDEndpointMode) *string { + if mode == aws.AccountIDEndpointModeDisabled { + return nil + } + + if ca, ok := identity.(*internalauthsmithy.CredentialsAdapter); ok && ca.Credentials.AccountID != "" { + return aws.String(ca.Credentials.AccountID) + } + + return nil +} + +func addTimeOffsetBuild(stack *middleware.Stack, c *Client) error { + mw := internalmiddleware.AddTimeOffsetMiddleware{Offset: c.timeOffset} + if err := stack.Build.Add(&mw, middleware.After); err != nil { + return err + } + return stack.Deserialize.Insert(&mw, "RecordResponseTiming", middleware.Before) +} +func initializeTimeOffsetResolver(c *Client) { + c.timeOffset = new(atomic.Int64) +} + +func addUserAgentRetryMode(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + switch options.Retryer.(type) { + case *retry.Standard: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeStandard) + case *retry.AdaptiveMode: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeAdaptive) + } + return nil +} + +type setCredentialSourceMiddleware struct { + ua *awsmiddleware.RequestUserAgent + options Options +} + +func (m setCredentialSourceMiddleware) ID() string { return "SetCredentialSourceMiddleware" } + +func (m setCredentialSourceMiddleware) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( + out middleware.BuildOutput, metadata middleware.Metadata, err error, +) { + asProviderSource, ok := m.options.Credentials.(aws.CredentialProviderSource) + if !ok { + return next.HandleBuild(ctx, in) + } + providerSources := asProviderSource.ProviderSources() + for _, source := range providerSources { + m.ua.AddCredentialsSource(source) + } + return next.HandleBuild(ctx, in) +} + +func addCredentialSource(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + mw := setCredentialSourceMiddleware{ua: ua, options: options} + return stack.Build.Insert(&mw, "UserAgent", middleware.Before) +} + +func resolveTracerProvider(options *Options) { + if options.TracerProvider == nil { + options.TracerProvider = &tracing.NopTracerProvider{} + } +} + +func resolveMeterProvider(options *Options) { + if options.MeterProvider == nil { + options.MeterProvider = metrics.NopMeterProvider{} + } +} + +func addRecursionDetection(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.RecursionDetection{}, middleware.After) +} + +func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { + return stack.Deserialize.Insert(&awsmiddleware.RequestIDRetriever{}, "OperationDeserializer", middleware.Before) + +} + +func addResponseErrorMiddleware(stack *middleware.Stack) error { + return stack.Deserialize.Insert(&awshttp.ResponseErrorWrapper{}, "RequestIDRetriever", middleware.Before) + +} + +func addRequestResponseLogging(stack *middleware.Stack, o Options) error { + return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ + LogRequest: o.ClientLogMode.IsRequest(), + LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), + LogResponse: o.ClientLogMode.IsResponse(), + LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), + }, middleware.After) +} + +type disableHTTPSMiddleware struct { + DisableHTTPS bool +} + +func (*disableHTTPSMiddleware) ID() string { + return "disableHTTPS" +} + +func (m *disableHTTPSMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.DisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { + req.URL.Scheme = "http" + } + + return next.HandleFinalize(ctx, in) +} + +func addDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { + return stack.Finalize.Insert(&disableHTTPSMiddleware{ + DisableHTTPS: o.EndpointOptions.DisableHTTPS, + }, "ResolveEndpointV2", middleware.After) +} + +type spanInitializeStart struct { +} + +func (*spanInitializeStart) ID() string { + return "spanInitializeStart" +} + +func (m *spanInitializeStart) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "Initialize") + + return next.HandleInitialize(ctx, in) +} + +type spanInitializeEnd struct { +} + +func (*spanInitializeEnd) ID() string { + return "spanInitializeEnd" +} + +func (m *spanInitializeEnd) HandleInitialize( + ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, +) ( + middleware.InitializeOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + + return next.HandleInitialize(ctx, in) +} + +type spanBuildRequestStart struct { +} + +func (*spanBuildRequestStart) ID() string { + return "spanBuildRequestStart" +} + +func (m *spanBuildRequestStart) HandleSerialize( + ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, +) ( + middleware.SerializeOutput, middleware.Metadata, error, +) { + ctx, _ = tracing.StartSpan(ctx, "BuildRequest") + + return next.HandleSerialize(ctx, in) +} + +type spanBuildRequestEnd struct { +} + +func (*spanBuildRequestEnd) ID() string { + return "spanBuildRequestEnd" +} + +func (m *spanBuildRequestEnd) HandleBuild( + ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, +) ( + middleware.BuildOutput, middleware.Metadata, error, +) { + ctx, span := tracing.PopSpan(ctx) + span.End() + + return next.HandleBuild(ctx, in) +} + +func addSpanInitializeStart(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) +} + +func addSpanInitializeEnd(stack *middleware.Stack) error { + return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) +} + +func addSpanBuildRequestStart(stack *middleware.Stack) error { + return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) +} + +func addSpanBuildRequestEnd(stack *middleware.Stack) error { + return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AddCustomAttributes.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AddCustomAttributes.go new file mode 100644 index 00000000..4fcaed3f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AddCustomAttributes.go @@ -0,0 +1,205 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Adds additional user attributes to the user pool schema. Custom attributes can +// be mutable or immutable and have a custom: or dev: prefix. For more +// information, see [Custom attributes]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Custom attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-custom-attributes +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AddCustomAttributes(ctx context.Context, params *AddCustomAttributesInput, optFns ...func(*Options)) (*AddCustomAttributesOutput, error) { + if params == nil { + params = &AddCustomAttributesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AddCustomAttributes", params, optFns, c.addOperationAddCustomAttributesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AddCustomAttributesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to add custom attributes. +type AddCustomAttributesInput struct { + + // An array of custom attribute names and other properties. Sets the following + // characteristics: + // + // AttributeDataType The expected data type. Can be a string, a number, a date and + // time, or a boolean. + // + // Mutable If true, you can grant app clients write access to the attribute value. + // If false, the attribute value can only be set up on sign-up or administrator + // creation of users. + // + // Name The attribute name. For an attribute like custom:myAttribute , enter + // myAttribute for this field. + // + // Required When true, users who sign up or are created must set a value for the + // attribute. + // + // NumberAttributeConstraints The minimum and maximum length of accepted values + // for a Number -type attribute. + // + // StringAttributeConstraints The minimum and maximum length of accepted values + // for a String -type attribute. + // + // DeveloperOnlyAttribute This legacy option creates an attribute with a dev: + // prefix. You can only set the value of a developer-only attribute with + // administrative IAM credentials. + // + // This member is required. + CustomAttributes []types.SchemaAttributeType + + // The ID of the user pool where you want to add custom attributes. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server for the request to add custom +// attributes. +type AddCustomAttributesOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAddCustomAttributesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAddCustomAttributes{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAddCustomAttributes{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AddCustomAttributes"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAddCustomAttributesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAddCustomAttributes(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAddCustomAttributes(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AddCustomAttributes", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminAddUserToGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminAddUserToGroup.go new file mode 100644 index 00000000..b479fcee --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminAddUserToGroup.go @@ -0,0 +1,186 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Adds a user to a group. A user who is in a group can present a preferred-role +// claim to an identity pool, and populates a cognito:groups claim to their access +// and identity tokens. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminAddUserToGroup(ctx context.Context, params *AdminAddUserToGroupInput, optFns ...func(*Options)) (*AdminAddUserToGroupOutput, error) { + if params == nil { + params = &AdminAddUserToGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminAddUserToGroup", params, optFns, c.addOperationAdminAddUserToGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminAddUserToGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminAddUserToGroupInput struct { + + // The name of the group that you want to add your user to. + // + // This member is required. + GroupName *string + + // The ID of the user pool that contains the group that you want to add the user + // to. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +type AdminAddUserToGroupOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminAddUserToGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminAddUserToGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminAddUserToGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminAddUserToGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminAddUserToGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminAddUserToGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminAddUserToGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminAddUserToGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminConfirmSignUp.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminConfirmSignUp.go new file mode 100644 index 00000000..ea6b85a7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminConfirmSignUp.go @@ -0,0 +1,219 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Confirms user sign-up as an administrator. +// +// This request sets a user account active in a user pool that [requires confirmation of new user accounts] before they can +// sign in. You can configure your user pool to not send confirmation codes to new +// users and instead confirm them with this API operation on the back end. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// To configure your user pool to require administrative confirmation of users, +// set AllowAdminCreateUserOnly to true in a CreateUserPool or UpdateUserPool +// request. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [requires confirmation of new user accounts]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#signing-up-users-in-your-app-and-confirming-them-as-admin +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminConfirmSignUp(ctx context.Context, params *AdminConfirmSignUpInput, optFns ...func(*Options)) (*AdminConfirmSignUpOutput, error) { + if params == nil { + params = &AdminConfirmSignUpInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminConfirmSignUp", params, optFns, c.addOperationAdminConfirmSignUpMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminConfirmSignUpOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Confirm a user's registration as a user pool administrator. +type AdminConfirmSignUpInput struct { + + // The ID of the user pool where you want to confirm a user's sign-up request. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // If your user pool configuration includes triggers, the AdminConfirmSignUp API + // action invokes the Lambda function that is specified for the post confirmation + // trigger. When Amazon Cognito invokes this function, it passes a JSON payload, + // which the function receives as input. In this payload, the clientMetadata + // attribute provides the data that you assigned to the ClientMetadata parameter in + // your AdminConfirmSignUp request. In your function code in Lambda, you can + // process the ClientMetadata value to enhance your workflow for your specific + // needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + noSmithyDocumentSerde +} + +// Represents the response from the server for the request to confirm registration. +type AdminConfirmSignUpOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminConfirmSignUpMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminConfirmSignUp{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminConfirmSignUp{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminConfirmSignUp"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminConfirmSignUpValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminConfirmSignUp(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminConfirmSignUp(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminConfirmSignUp", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminCreateUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminCreateUser.go new file mode 100644 index 00000000..f9d2c820 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminCreateUser.go @@ -0,0 +1,350 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a new user in the specified user pool. +// +// If MessageAction isn't set, the default is to send a welcome message via email +// or phone (SMS). +// +// This message is based on a template that you configured in your call to create +// or update a user pool. This template includes your custom sign-up instructions +// and placeholders for user name and temporary password. +// +// Alternatively, you can call AdminCreateUser with SUPPRESS for the MessageAction +// parameter, and Amazon Cognito won't send any email. +// +// In either case, if the user has a password, they will be in the +// FORCE_CHANGE_PASSWORD state until they sign in and set their password. Your +// invitation message template must have the {####} password placeholder if your +// users have passwords. If your template doesn't have this placeholder, Amazon +// Cognito doesn't deliver the invitation message. In this case, you must update +// your message template and resend the password with a new AdminCreateUser +// request with a MessageAction value of RESEND . +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) AdminCreateUser(ctx context.Context, params *AdminCreateUserInput, optFns ...func(*Options)) (*AdminCreateUserOutput, error) { + if params == nil { + params = &AdminCreateUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminCreateUser", params, optFns, c.addOperationAdminCreateUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminCreateUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Creates a new user in the specified user pool. +type AdminCreateUserInput struct { + + // The ID of the user pool where you want to create a user. + // + // This member is required. + UserPoolId *string + + // The value that you want to set as the username sign-in attribute. The following + // conditions apply to the username parameter. + // + // - The username can't be a duplicate of another username in the same user pool. + // + // - You can't change the value of a username after you create it. + // + // - You can only provide a value if usernames are a valid sign-in attribute for + // your user pool. If your user pool only supports phone numbers or email addresses + // as sign-in attributes, Amazon Cognito automatically generates a username value. + // For more information, see [Customizing sign-in attributes]. + // + // [Customizing sign-in attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases + // + // This member is required. + Username *string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the AdminCreateUser API action, Amazon Cognito invokes + // the function that is assigned to the pre sign-up trigger. When Amazon Cognito + // invokes this function, it passes a JSON payload, which the function receives as + // input. This payload contains a ClientMetadata attribute, which provides the + // data that you assigned to the ClientMetadata parameter in your AdminCreateUser + // request. In your function code in Lambda, you can process the clientMetadata + // value to enhance your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // Specify EMAIL if email will be used to send the welcome message. Specify SMS if + // the phone number will be used. The default value is SMS . You can specify more + // than one value. + DesiredDeliveryMediums []types.DeliveryMediumType + + // This parameter is used only if the phone_number_verified or email_verified + // attribute is set to True . Otherwise, it is ignored. + // + // If this parameter is set to True and the phone number or email address + // specified in the UserAttributes parameter already exists as an alias with a + // different user, this request migrates the alias from the previous user to the + // newly-created user. The previous user will no longer be able to log in using + // that alias. + // + // If this parameter is set to False , the API throws an AliasExistsException + // error if the alias already exists. The default value is False . + ForceAliasCreation bool + + // Set to RESEND to resend the invitation message to a user that already exists, + // and to reset the temporary-password duration with a new temporary password. Set + // to SUPPRESS to suppress sending the message. You can specify only one value. + MessageAction types.MessageActionType + + // The user's temporary password. This password must conform to the password + // policy that you specified when you created the user pool. + // + // The exception to the requirement for a password is when your user pool supports + // passwordless sign-in with email or SMS OTPs. To create a user with no password, + // omit this parameter or submit a blank value. You can only create a passwordless + // user when passwordless sign-in is available. + // + // The temporary password is valid only once. To complete the Admin Create User + // flow, the user must enter the temporary password in the sign-in page, along with + // a new password to be used in all future sign-ins. + // + // If you don't specify a value, Amazon Cognito generates one for you unless you + // have passwordless options active for your user pool. + // + // The temporary password can only be used until the user account expiration limit + // that you set for your user pool. To reset the account after that time limit, you + // must call AdminCreateUser again and specify RESEND for the MessageAction + // parameter. + TemporaryPassword *string + + // An array of name-value pairs that contain user attributes and attribute values + // to be set for the user to be created. You can create a user without specifying + // any attributes other than Username . However, any attributes that you specify as + // required (when creating a user pool or in the Attributes tab of the console) + // either you should supply (in your call to AdminCreateUser ) or the user should + // supply (when they sign up in response to your welcome message). + // + // For custom attributes, you must prepend the custom: prefix to the attribute + // name. + // + // To send a message inviting the user to sign up, you must specify the user's + // email address or phone number. You can do this in your call to AdminCreateUser + // or in the Users tab of the Amazon Cognito console for managing your user pools. + // + // You must also provide an email address or phone number when you expect the user + // to do passwordless sign-in with an email or SMS OTP. These attributes must be + // provided when passwordless options are the only available, or when you don't + // submit a TemporaryPassword . + // + // In your AdminCreateUser request, you can set the email_verified and + // phone_number_verified attributes to true . The following conditions apply: + // + // email The email address where you want the user to receive their confirmation + // code and username. You must provide a value for email when you want to set + // email_verified to true , or if you set EMAIL in the DesiredDeliveryMediums + // parameter. + // + // phone_number The phone number where you want the user to receive their + // confirmation code and username. You must provide a value for phone_number when + // you want to set phone_number_verified to true , or if you set SMS in the + // DesiredDeliveryMediums parameter. + UserAttributes []types.AttributeType + + // Temporary user attributes that contribute to the outcomes of your pre sign-up + // Lambda trigger. This set of key-value pairs are for custom validation of + // information that you collect from your users but don't need to retain. + // + // Your Lambda function can analyze this additional data and act on it. Your + // function can automatically confirm and verify select users or perform external + // API operations like logging user attributes and validation data to Amazon + // CloudWatch Logs. + // + // For more information about the pre sign-up Lambda trigger, see [Pre sign-up Lambda trigger]. + // + // [Pre sign-up Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html + ValidationData []types.AttributeType + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to create the user. +type AdminCreateUserOutput struct { + + // The new user's profile details. + User *types.UserType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminCreateUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminCreateUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminCreateUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminCreateUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminCreateUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminCreateUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminCreateUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminCreateUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUser.go new file mode 100644 index 00000000..ad8e64b0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUser.go @@ -0,0 +1,179 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a user profile in your user pool. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminDeleteUser(ctx context.Context, params *AdminDeleteUserInput, optFns ...func(*Options)) (*AdminDeleteUserOutput, error) { + if params == nil { + params = &AdminDeleteUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminDeleteUser", params, optFns, c.addOperationAdminDeleteUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminDeleteUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to delete a user as an administrator. +type AdminDeleteUserInput struct { + + // The ID of the user pool where you want to delete the user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +type AdminDeleteUserOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminDeleteUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminDeleteUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminDeleteUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminDeleteUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminDeleteUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminDeleteUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminDeleteUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminDeleteUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUserAttributes.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUserAttributes.go new file mode 100644 index 00000000..d6e9e6ce --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDeleteUserAttributes.go @@ -0,0 +1,191 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes attribute values from a user. This operation doesn't affect tokens for +// existing user sessions. The next ID token that the user receives will no longer +// have the deleted attributes. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminDeleteUserAttributes(ctx context.Context, params *AdminDeleteUserAttributesInput, optFns ...func(*Options)) (*AdminDeleteUserAttributesOutput, error) { + if params == nil { + params = &AdminDeleteUserAttributesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminDeleteUserAttributes", params, optFns, c.addOperationAdminDeleteUserAttributesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminDeleteUserAttributesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to delete user attributes as an administrator. +type AdminDeleteUserAttributesInput struct { + + // An array of strings representing the user attribute names you want to delete. + // + // For custom attributes, you must prepend the custom: prefix to the attribute + // name. + // + // This member is required. + UserAttributeNames []string + + // The ID of the user pool where you want to delete user attributes. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// Represents the response received from the server for a request to delete user +// attributes. +type AdminDeleteUserAttributesOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminDeleteUserAttributesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminDeleteUserAttributes{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminDeleteUserAttributes{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminDeleteUserAttributes"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminDeleteUserAttributesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminDeleteUserAttributes(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminDeleteUserAttributes(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminDeleteUserAttributes", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableProviderForUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableProviderForUser.go new file mode 100644 index 00000000..de7ad5b5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableProviderForUser.go @@ -0,0 +1,200 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Prevents the user from signing in with the specified external (SAML or social) +// identity provider (IdP). If the user that you want to deactivate is a Amazon +// Cognito user pools native username + password user, they can't use their +// password to sign in. If the user to deactivate is a linked external IdP user, +// any link between that user and an existing user is removed. When the external +// user signs in again, and the user is no longer attached to the previously linked +// DestinationUser , the user must create a new user account. +// +// The value of ProviderName must match the name of a user pool IdP. +// +// To deactivate a local user, set ProviderName to Cognito and the +// ProviderAttributeName to Cognito_Subject . The ProviderAttributeValue must be +// user's local username. +// +// The ProviderAttributeName must always be Cognito_Subject for social IdPs. The +// ProviderAttributeValue must always be the exact subject that was used when the +// user was originally linked as a source user. +// +// For de-linking a SAML identity, there are two scenarios. If the linked identity +// has not yet been used to sign in, the ProviderAttributeName and +// ProviderAttributeValue must be the same values that were used for the SourceUser +// when the identities were originally linked using AdminLinkProviderForUser call. +// This is also true if the linking was done with ProviderAttributeName set to +// Cognito_Subject . If the user has already signed in, the ProviderAttributeName +// must be Cognito_Subject and ProviderAttributeValue must be the NameID from +// their SAML assertion. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminDisableProviderForUser(ctx context.Context, params *AdminDisableProviderForUserInput, optFns ...func(*Options)) (*AdminDisableProviderForUserOutput, error) { + if params == nil { + params = &AdminDisableProviderForUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminDisableProviderForUser", params, optFns, c.addOperationAdminDisableProviderForUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminDisableProviderForUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminDisableProviderForUserInput struct { + + // The user profile that you want to delete a linked identity from. + // + // This member is required. + User *types.ProviderUserIdentifierType + + // The ID of the user pool where you want to delete the user's linked identities. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type AdminDisableProviderForUserOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminDisableProviderForUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminDisableProviderForUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminDisableProviderForUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminDisableProviderForUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminDisableProviderForUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminDisableProviderForUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminDisableProviderForUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminDisableProviderForUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableUser.go new file mode 100644 index 00000000..3cb35487 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminDisableUser.go @@ -0,0 +1,183 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deactivates a user profile and revokes all access tokens for the user. A +// deactivated user can't sign in, but still appears in the responses to ListUsers +// API requests. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminDisableUser(ctx context.Context, params *AdminDisableUserInput, optFns ...func(*Options)) (*AdminDisableUserOutput, error) { + if params == nil { + params = &AdminDisableUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminDisableUser", params, optFns, c.addOperationAdminDisableUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminDisableUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to disable the user as an administrator. +type AdminDisableUserInput struct { + + // The ID of the user pool where you want to disable the user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// Represents the response received from the server to disable the user as an +// administrator. +type AdminDisableUserOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminDisableUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminDisableUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminDisableUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminDisableUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminDisableUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminDisableUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminDisableUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminDisableUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminEnableUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminEnableUser.go new file mode 100644 index 00000000..8f9939fa --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminEnableUser.go @@ -0,0 +1,182 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Activates sign-in for a user profile that previously had sign-in access +// disabled. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminEnableUser(ctx context.Context, params *AdminEnableUserInput, optFns ...func(*Options)) (*AdminEnableUserOutput, error) { + if params == nil { + params = &AdminEnableUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminEnableUser", params, optFns, c.addOperationAdminEnableUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminEnableUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request that enables the user as an administrator. +type AdminEnableUserInput struct { + + // The ID of the user pool where you want to activate sign-in for the user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// Represents the response from the server for the request to enable a user as an +// administrator. +type AdminEnableUserOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminEnableUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminEnableUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminEnableUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminEnableUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminEnableUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminEnableUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminEnableUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminEnableUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminForgetDevice.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminForgetDevice.go new file mode 100644 index 00000000..78f0930d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminForgetDevice.go @@ -0,0 +1,188 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Forgets, or deletes, a remembered device from a user's profile. After you +// forget the device, the user can no longer complete device authentication with +// that device and when applicable, must submit MFA codes again. For more +// information, see [Working with devices]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminForgetDevice(ctx context.Context, params *AdminForgetDeviceInput, optFns ...func(*Options)) (*AdminForgetDeviceOutput, error) { + if params == nil { + params = &AdminForgetDeviceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminForgetDevice", params, optFns, c.addOperationAdminForgetDeviceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminForgetDeviceOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Sends the forgot device request, as an administrator. +type AdminForgetDeviceInput struct { + + // The key ID of the device that you want to delete. + // + // This member is required. + DeviceKey *string + + // The ID of the user pool where the device owner is a user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +type AdminForgetDeviceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminForgetDeviceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminForgetDevice{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminForgetDevice{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminForgetDevice"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminForgetDeviceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminForgetDevice(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminForgetDevice(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminForgetDevice", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetDevice.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetDevice.go new file mode 100644 index 00000000..fe9029cd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetDevice.go @@ -0,0 +1,195 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given the device key, returns details for a user's device. For more +// information, see [Working with devices]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminGetDevice(ctx context.Context, params *AdminGetDeviceInput, optFns ...func(*Options)) (*AdminGetDeviceOutput, error) { + if params == nil { + params = &AdminGetDeviceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminGetDevice", params, optFns, c.addOperationAdminGetDeviceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminGetDeviceOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to get the device, as an administrator. +type AdminGetDeviceInput struct { + + // The key of the device that you want to delete. + // + // This member is required. + DeviceKey *string + + // The ID of the user pool where the device owner is a user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// Gets the device response, as an administrator. +type AdminGetDeviceOutput struct { + + // Details of the requested device. Includes device information, last-accessed and + // created dates, and the device key. + // + // This member is required. + Device *types.DeviceType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminGetDeviceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminGetDevice{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminGetDevice{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminGetDevice"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminGetDeviceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminGetDevice(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminGetDevice(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminGetDevice", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetUser.go new file mode 100644 index 00000000..54daeeed --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminGetUser.go @@ -0,0 +1,243 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Given a username, returns details about a user profile in a user pool. You can +// specify alias attributes in the Username request parameter. +// +// This operation contributes to your monthly active user (MAU) count for the +// purpose of billing. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminGetUser(ctx context.Context, params *AdminGetUserInput, optFns ...func(*Options)) (*AdminGetUserOutput, error) { + if params == nil { + params = &AdminGetUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminGetUser", params, optFns, c.addOperationAdminGetUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminGetUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to get the specified user as an administrator. +type AdminGetUserInput struct { + + // The ID of the user pool where you want to get information about the user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// Represents the response from the server from the request to get the specified +// user as an administrator. +type AdminGetUserOutput struct { + + // The username of the user that you requested. + // + // This member is required. + Username *string + + // Indicates whether the user is activated for sign-in. + Enabled bool + + // This response parameter is no longer supported. It provides information only + // about SMS MFA configurations. It doesn't provide information about time-based + // one-time password (TOTP) software token MFA configurations. To look up + // information about either type of MFA configuration, use UserMFASettingList + // instead. + MFAOptions []types.MFAOptionType + + // The user's preferred MFA. Users can prefer SMS message, email message, or TOTP + // MFA. + PreferredMfaSetting *string + + // An array of name-value pairs of user attributes and their values, for example + // "email": "testuser@example.com" . + UserAttributes []types.AttributeType + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + UserCreateDate *time.Time + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + UserLastModifiedDate *time.Time + + // The MFA options that are activated for the user. The possible values in this + // list are SMS_MFA , EMAIL_OTP , and SOFTWARE_TOKEN_MFA . + UserMFASettingList []string + + // The user's status. Can be one of the following: + // + // - UNCONFIRMED - User has been created but not confirmed. + // + // - CONFIRMED - User has been confirmed. + // + // - UNKNOWN - User status isn't known. + // + // - RESET_REQUIRED - User is confirmed, but the user must request a code and + // reset their password before they can sign in. + // + // - FORCE_CHANGE_PASSWORD - The user is confirmed and the user can sign in + // using a temporary password, but on first sign-in, the user must change their + // password to a new value before doing anything else. + // + // - EXTERNAL_PROVIDER - The user signed in with a third-party identity provider. + UserStatus types.UserStatusType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminGetUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminGetUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminGetUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminGetUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminGetUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminGetUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminGetUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminGetUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminInitiateAuth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminInitiateAuth.go new file mode 100644 index 00000000..bc2d7771 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminInitiateAuth.go @@ -0,0 +1,458 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Starts sign-in for applications with a server-side component, for example a +// traditional web application. This operation specifies the authentication flow +// that you'd like to begin. The authentication flow that you specify must be +// supported in your app client configuration. For more information about +// authentication flows, see [Authentication flows]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Authentication flows]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) AdminInitiateAuth(ctx context.Context, params *AdminInitiateAuthInput, optFns ...func(*Options)) (*AdminInitiateAuthOutput, error) { + if params == nil { + params = &AdminInitiateAuthInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminInitiateAuth", params, optFns, c.addOperationAdminInitiateAuthMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminInitiateAuthOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Initiates the authorization request, as an administrator. +type AdminInitiateAuthInput struct { + + // The authentication flow that you want to initiate. Each AuthFlow has linked + // AuthParameters that you must submit. The following are some example flows. + // + // USER_AUTH The entry point for [choice-based authentication] with passwords, one-time passwords, and WebAuthn + // authenticators. Request a preferred authentication type or review available + // authentication types. From the offered authentication types, select one in a + // challenge response and then authenticate with that method in an additional + // challenge response. To activate this setting, your user pool must be in the [Essentials tier]or + // higher. + // + // USER_SRP_AUTH Username-password authentication with the Secure Remote Password + // (SRP) protocol. For more information, see [Use SRP password verification in custom authentication flow]. + // + // REFRESH_TOKEN_AUTH and REFRESH_TOKEN Receive new ID and access tokens when you + // pass a REFRESH_TOKEN parameter with a valid refresh token as the value. For + // more information, see [Using the refresh token]. + // + // CUSTOM_AUTH Custom authentication with Lambda triggers. For more information, + // see [Custom authentication challenge Lambda triggers]. + // + // ADMIN_USER_PASSWORD_AUTH Server-side username-password authentication with the + // password sent directly in the request. For more information about client-side + // and server-side authentication, see [SDK authorization models]. + // + // [SDK authorization models]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-public-server-side.html + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + // [Use SRP password verification in custom authentication flow]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#Using-SRP-password-verification-in-custom-authentication-flow + // [Using the refresh token]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + // [Custom authentication challenge Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html + // + // This member is required. + AuthFlow types.AuthFlowType + + // The ID of the app client where the user wants to sign in. + // + // This member is required. + ClientId *string + + // The ID of the user pool where the user wants to sign in. + // + // This member is required. + UserPoolId *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // The authentication parameters. These are inputs corresponding to the AuthFlow + // that you're invoking. The required values depend on the value of AuthFlow for + // example: + // + // - For USER_AUTH : USERNAME (required), PREFERRED_CHALLENGE . If you don't + // provide a value for PREFERRED_CHALLENGE , Amazon Cognito responds with the + // AvailableChallenges parameter that specifies the available sign-in methods. + // + // - For USER_SRP_AUTH : USERNAME (required), SRP_A (required), SECRET_HASH + // (required if the app client is configured with a client secret), DEVICE_KEY . + // + // - For ADMIN_USER_PASSWORD_AUTH : USERNAME (required), PASSWORD (required), + // SECRET_HASH (required if the app client is configured with a client secret), + // DEVICE_KEY . + // + // - For REFRESH_TOKEN_AUTH/REFRESH_TOKEN : REFRESH_TOKEN (required), SECRET_HASH + // (required if the app client is configured with a client secret), DEVICE_KEY . + // + // - For CUSTOM_AUTH : USERNAME (required), SECRET_HASH (if app client is + // configured with client secret), DEVICE_KEY . To start the authentication flow + // with password verification, include ChallengeName: SRP_A and SRP_A: (The + // SRP_A Value) . + // + // For more information about SECRET_HASH , see [Computing secret hash values]. For information about DEVICE_KEY + // , see [Working with user devices in your user pool]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + // [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + AuthParameters map[string]string + + // A map of custom key-value pairs that you can provide as input for certain + // custom workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the AdminInitiateAuth API action, Amazon Cognito invokes + // the Lambda functions that are specified for various triggers. The ClientMetadata + // value is passed as input to the functions for only the following triggers: + // + // - Pre signup + // + // - Pre authentication + // + // - User migration + // + // When Amazon Cognito invokes the functions for these triggers, it passes a JSON + // payload, which the function receives as input. This payload contains a + // validationData attribute, which provides the data that you assigned to the + // ClientMetadata parameter in your AdminInitiateAuth request. In your function + // code in Lambda, you can process the validationData value to enhance your + // workflow for your specific needs. + // + // When you use the AdminInitiateAuth API action, Amazon Cognito also invokes the + // functions for the following triggers, but it doesn't provide the ClientMetadata + // value as input: + // + // - Post authentication + // + // - Custom message + // + // - Pre token generation + // + // - Create auth challenge + // + // - Define auth challenge + // + // - Custom email sender + // + // - Custom SMS sender + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + ContextData *types.ContextDataType + + // The optional session ID from a ConfirmSignUp API request. You can sign in a + // user directly from the sign-up process with an AuthFlow of USER_AUTH and + // AuthParameters of EMAIL_OTP or SMS_OTP , depending on how your user pool sent + // the confirmation-code message. + Session *string + + noSmithyDocumentSerde +} + +// Initiates the authentication response, as an administrator. +type AdminInitiateAuthOutput struct { + + // The outcome of successful authentication. This is only returned if the user + // pool has no additional challenges to return. If Amazon Cognito returns another + // challenge, the response includes ChallengeName , ChallengeParameters , and + // Session so that your user can answer the challenge. + AuthenticationResult *types.AuthenticationResultType + + // This response parameter lists the available authentication challenges that + // users can select from in [choice-based authentication]. For example, they might be able to choose between + // passkey authentication, a one-time password from an SMS message, and a + // traditional password. + // + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + AvailableChallenges []types.ChallengeNameType + + // The name of the challenge that you're responding to with this call. This is + // returned in the AdminInitiateAuth response if you must pass another challenge. + // + // Possible challenges include the following: + // + // All of the following challenges require USERNAME and, when the app client has a + // client secret, SECRET_HASH in the parameters. + // + // - WEB_AUTHN : Respond to the challenge with the results of a successful + // authentication with a WebAuthn authenticator, or passkey. Examples of WebAuthn + // authenticators include biometric devices and security keys. + // + // - PASSWORD : Respond with USER_PASSWORD_AUTH parameters: USERNAME (required), + // PASSWORD (required), SECRET_HASH (required if the app client is configured + // with a client secret), DEVICE_KEY . + // + // - PASSWORD_SRP : Respond with USER_SRP_AUTH parameters: USERNAME (required), + // SRP_A (required), SECRET_HASH (required if the app client is configured with a + // client secret), DEVICE_KEY . + // + // - SELECT_CHALLENGE : Respond to the challenge with USERNAME and an ANSWER that + // matches one of the challenge types in the AvailableChallenges response + // parameter. + // + // - SMS_MFA : Respond with an SMS_MFA_CODE that your user pool delivered in an + // SMS message. + // + // - EMAIL_OTP : Respond with an EMAIL_OTP_CODE that your user pool delivered in + // an email message. + // + // - PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP calculations. + // + // - CUSTOM_CHALLENGE : This is returned if your custom authentication flow + // determines that the user should pass another challenge before tokens are issued. + // The parameters of the challenge are determined by your Lambda function. + // + // - DEVICE_SRP_AUTH : Respond with the initial parameters of device SRP + // authentication. For more information, see [Signing in with a device]. + // + // - DEVICE_PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP + // calculations. For more information, see [Signing in with a device]. + // + // - NEW_PASSWORD_REQUIRED : For users who are required to change their passwords + // after successful first login. Respond to this challenge with NEW_PASSWORD and + // any required attributes that Amazon Cognito returned in the requiredAttributes + // parameter. You can also set values for attributes that aren't required by your + // user pool and that your app client can write. + // + // Amazon Cognito only returns this challenge for users who have temporary + // passwords. When you create passwordless users, you must provide values for all + // required attributes. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // - MFA_SETUP : For users who are required to setup an MFA factor before they + // can sign in. The MFA types activated for the user pool will be listed in the + // challenge parameters MFAS_CAN_SETUP value. + // + // To set up time-based one-time password (TOTP) MFA, use the session returned in + // this challenge from InitiateAuth or AdminInitiateAuth as an input to + // AssociateSoftwareToken . Then, use the session returned by VerifySoftwareToken + // as an input to RespondToAuthChallenge or AdminRespondToAuthChallenge with + // challenge name MFA_SETUP to complete sign-in. + // + // To set up SMS or email MFA, collect a phone_number or email attribute for the + // user. Then restart the authentication flow with an InitiateAuth or + // AdminInitiateAuth request. + // + // [Signing in with a device]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-signing-in-with-a-device + ChallengeName types.ChallengeNameType + + // The parameters of an authentication challenge. Amazon Cognito returns challenge + // parameters as a guide to the responses your user or application must provide for + // the returned ChallengeName . Calculate responses to the challenge parameters and + // pass them in the ChallengeParameters of AdminRespondToAuthChallenge . + // + // All challenges require USERNAME and, when the app client has a client secret, + // SECRET_HASH . + // + // In SRP challenges, Amazon Cognito returns the username attribute in + // USER_ID_FOR_SRP instead of any email address, preferred username, or phone + // number alias that you might have specified in your AdminInitiateAuth request. + // You must use the username and not an alias in the ChallengeResponses of your + // challenge response. + ChallengeParameters map[string]string + + // The session that must be passed to challenge-response requests. If an + // AdminInitiateAuth or AdminRespondToAuthChallenge API request results in another + // authentication challenge, Amazon Cognito returns a session ID and the parameters + // of the next challenge. Pass this session ID in the Session parameter of + // AdminRespondToAuthChallenge . + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminInitiateAuthMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminInitiateAuth{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminInitiateAuth{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminInitiateAuth"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminInitiateAuthValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminInitiateAuth(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminInitiateAuth(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminInitiateAuth", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminLinkProviderForUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminLinkProviderForUser.go new file mode 100644 index 00000000..23d095aa --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminLinkProviderForUser.go @@ -0,0 +1,235 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Links an existing user account in a user pool, or DestinationUser , to an +// identity from an external IdP, or SourceUser , based on a specified attribute +// name and value from the external IdP. +// +// This operation connects a local user profile with a user identity who hasn't +// yet signed in from their third-party IdP. When the user signs in with their IdP, +// they get access-control configuration from the local user profile. Linked local +// users can also sign in with SDK-based API operations like InitiateAuth after +// they sign in at least once through their IdP. For more information, see [Linking federated users]. +// +// The maximum number of federated identities linked to a user is five. +// +// Because this API allows a user with an external federated identity to sign in +// as a local user, it is critical that it only be used with external IdPs and +// linked attributes that you trust. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Linking federated users]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation-consolidate-users.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminLinkProviderForUser(ctx context.Context, params *AdminLinkProviderForUserInput, optFns ...func(*Options)) (*AdminLinkProviderForUserOutput, error) { + if params == nil { + params = &AdminLinkProviderForUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminLinkProviderForUser", params, optFns, c.addOperationAdminLinkProviderForUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminLinkProviderForUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminLinkProviderForUserInput struct { + + // The existing user in the user pool that you want to assign to the external IdP + // user account. This user can be a local (Username + Password) Amazon Cognito user + // pools user or a federated user (for example, a SAML or Facebook user). If the + // user doesn't exist, Amazon Cognito generates an exception. Amazon Cognito + // returns this user when the new user (with the linked IdP attribute) signs in. + // + // For a native username + password user, the ProviderAttributeValue for the + // DestinationUser should be the username in the user pool. For a federated user, + // it should be the provider-specific user_id . + // + // The ProviderAttributeName of the DestinationUser is ignored. + // + // The ProviderName should be set to Cognito for users in Cognito user pools. + // + // All attributes in the DestinationUser profile must be mutable. If you have + // assigned the user any immutable custom attributes, the operation won't succeed. + // + // This member is required. + DestinationUser *types.ProviderUserIdentifierType + + // An external IdP account for a user who doesn't exist yet in the user pool. This + // user must be a federated user (for example, a SAML or Facebook user), not + // another native user. + // + // If the SourceUser is using a federated social IdP, such as Facebook, Google, or + // Login with Amazon, you must set the ProviderAttributeName to Cognito_Subject . + // For social IdPs, the ProviderName will be Facebook , Google , or LoginWithAmazon + // , and Amazon Cognito will automatically parse the Facebook, Google, and Login + // with Amazon tokens for id , sub , and user_id , respectively. The + // ProviderAttributeValue for the user must be the same value as the id , sub , or + // user_id value found in the social IdP token. + // + // For OIDC, the ProviderAttributeName can be any mapped value from a claim in the + // ID token, or that your app retrieves from the userInfo endpoint. For SAML, the + // ProviderAttributeName can be any mapped value from a claim in the SAML assertion. + // + // The following additional considerations apply to SourceUser for OIDC and SAML + // providers. + // + // - You must map the claim to a user pool attribute in your IdP configuration, + // and set the user pool attribute name as the value of ProviderAttributeName in + // your AdminLinkProviderForUser request. For example, email . + // + // - When you set ProviderAttributeName to Cognito_Subject , Amazon Cognito will + // automatically parse the default unique identifier found in the subject from the + // IdP token. + // + // This member is required. + SourceUser *types.ProviderUserIdentifierType + + // The ID of the user pool where you want to link a federated identity. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type AdminLinkProviderForUserOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminLinkProviderForUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminLinkProviderForUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminLinkProviderForUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminLinkProviderForUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminLinkProviderForUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminLinkProviderForUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminLinkProviderForUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminLinkProviderForUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListDevices.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListDevices.go new file mode 100644 index 00000000..03a8c9d2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListDevices.go @@ -0,0 +1,209 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists a user's registered devices. Remembered devices are used in +// authentication services where you offer a "Remember me" option for users who you +// want to permit to sign in without MFA from a trusted device. Users can bypass +// MFA while your application performs device SRP authentication on the back end. +// For more information, see [Working with devices]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminListDevices(ctx context.Context, params *AdminListDevicesInput, optFns ...func(*Options)) (*AdminListDevicesOutput, error) { + if params == nil { + params = &AdminListDevicesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminListDevices", params, optFns, c.addOperationAdminListDevicesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminListDevicesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to list devices, as an administrator. +type AdminListDevicesInput struct { + + // The ID of the user pool where the device owner is a user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // The maximum number of devices that you want Amazon Cognito to return in the + // response. + Limit *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + PaginationToken *string + + noSmithyDocumentSerde +} + +// Lists the device's response, as an administrator. +type AdminListDevicesOutput struct { + + // An array of devices and their information. Each entry that's returned includes + // device information, last-accessed and created dates, and the device key. + Devices []types.DeviceType + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + PaginationToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminListDevicesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminListDevices{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminListDevices{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminListDevices"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminListDevicesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminListDevices(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminListDevices(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminListDevices", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListGroupsForUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListGroupsForUser.go new file mode 100644 index 00000000..33e03dd4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListGroupsForUser.go @@ -0,0 +1,299 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists the groups that a user belongs to. User pool groups are identifiers that +// you can reference from the contents of ID and access tokens, and set preferred +// IAM roles for identity-pool authentication. For more information, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminListGroupsForUser(ctx context.Context, params *AdminListGroupsForUserInput, optFns ...func(*Options)) (*AdminListGroupsForUserOutput, error) { + if params == nil { + params = &AdminListGroupsForUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminListGroupsForUser", params, optFns, c.addOperationAdminListGroupsForUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminListGroupsForUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminListGroupsForUserInput struct { + + // The ID of the user pool where you want to view a user's groups. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // The maximum number of groups that you want Amazon Cognito to return in the + // response. + Limit *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type AdminListGroupsForUserOutput struct { + + // An array of groups and information about them. + Groups []types.GroupType + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminListGroupsForUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminListGroupsForUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminListGroupsForUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminListGroupsForUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminListGroupsForUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminListGroupsForUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// AdminListGroupsForUserPaginatorOptions is the paginator options for +// AdminListGroupsForUser +type AdminListGroupsForUserPaginatorOptions struct { + // The maximum number of groups that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// AdminListGroupsForUserPaginator is a paginator for AdminListGroupsForUser +type AdminListGroupsForUserPaginator struct { + options AdminListGroupsForUserPaginatorOptions + client AdminListGroupsForUserAPIClient + params *AdminListGroupsForUserInput + nextToken *string + firstPage bool +} + +// NewAdminListGroupsForUserPaginator returns a new AdminListGroupsForUserPaginator +func NewAdminListGroupsForUserPaginator(client AdminListGroupsForUserAPIClient, params *AdminListGroupsForUserInput, optFns ...func(*AdminListGroupsForUserPaginatorOptions)) *AdminListGroupsForUserPaginator { + if params == nil { + params = &AdminListGroupsForUserInput{} + } + + options := AdminListGroupsForUserPaginatorOptions{} + if params.Limit != nil { + options.Limit = *params.Limit + } + + for _, fn := range optFns { + fn(&options) + } + + return &AdminListGroupsForUserPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *AdminListGroupsForUserPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next AdminListGroupsForUser page. +func (p *AdminListGroupsForUserPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*AdminListGroupsForUserOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.Limit = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.AdminListGroupsForUser(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// AdminListGroupsForUserAPIClient is a client that implements the +// AdminListGroupsForUser operation. +type AdminListGroupsForUserAPIClient interface { + AdminListGroupsForUser(context.Context, *AdminListGroupsForUserInput, ...func(*Options)) (*AdminListGroupsForUserOutput, error) +} + +var _ AdminListGroupsForUserAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opAdminListGroupsForUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminListGroupsForUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListUserAuthEvents.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListUserAuthEvents.go new file mode 100644 index 00000000..59e3989d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminListUserAuthEvents.go @@ -0,0 +1,300 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Requests a history of user activity and any risks detected as part of Amazon +// Cognito threat protection. For more information, see [Viewing user event history]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Viewing user event history]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-event-user-history +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminListUserAuthEvents(ctx context.Context, params *AdminListUserAuthEventsInput, optFns ...func(*Options)) (*AdminListUserAuthEventsOutput, error) { + if params == nil { + params = &AdminListUserAuthEventsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminListUserAuthEvents", params, optFns, c.addOperationAdminListUserAuthEventsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminListUserAuthEventsOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminListUserAuthEventsInput struct { + + // The Id of the user pool that contains the user profile with the logged events. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // The maximum number of authentication events to return. Returns 60 events if you + // set MaxResults to 0, or if you don't include a MaxResults parameter. + MaxResults *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type AdminListUserAuthEventsOutput struct { + + // The response object. It includes the EventID , EventType , CreationDate , + // EventRisk , and EventResponse . + AuthEvents []types.AuthEventType + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminListUserAuthEventsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminListUserAuthEvents{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminListUserAuthEvents{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminListUserAuthEvents"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminListUserAuthEventsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminListUserAuthEvents(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// AdminListUserAuthEventsPaginatorOptions is the paginator options for +// AdminListUserAuthEvents +type AdminListUserAuthEventsPaginatorOptions struct { + // The maximum number of authentication events to return. Returns 60 events if you + // set MaxResults to 0, or if you don't include a MaxResults parameter. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// AdminListUserAuthEventsPaginator is a paginator for AdminListUserAuthEvents +type AdminListUserAuthEventsPaginator struct { + options AdminListUserAuthEventsPaginatorOptions + client AdminListUserAuthEventsAPIClient + params *AdminListUserAuthEventsInput + nextToken *string + firstPage bool +} + +// NewAdminListUserAuthEventsPaginator returns a new +// AdminListUserAuthEventsPaginator +func NewAdminListUserAuthEventsPaginator(client AdminListUserAuthEventsAPIClient, params *AdminListUserAuthEventsInput, optFns ...func(*AdminListUserAuthEventsPaginatorOptions)) *AdminListUserAuthEventsPaginator { + if params == nil { + params = &AdminListUserAuthEventsInput{} + } + + options := AdminListUserAuthEventsPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &AdminListUserAuthEventsPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *AdminListUserAuthEventsPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next AdminListUserAuthEvents page. +func (p *AdminListUserAuthEventsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*AdminListUserAuthEventsOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.AdminListUserAuthEvents(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// AdminListUserAuthEventsAPIClient is a client that implements the +// AdminListUserAuthEvents operation. +type AdminListUserAuthEventsAPIClient interface { + AdminListUserAuthEvents(context.Context, *AdminListUserAuthEventsInput, ...func(*Options)) (*AdminListUserAuthEventsOutput, error) +} + +var _ AdminListUserAuthEventsAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opAdminListUserAuthEvents(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminListUserAuthEvents", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRemoveUserFromGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRemoveUserFromGroup.go new file mode 100644 index 00000000..97e68b78 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRemoveUserFromGroup.go @@ -0,0 +1,189 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a username and a group name, removes them from the group. User pool +// groups are identifiers that you can reference from the contents of ID and access +// tokens, and set preferred IAM roles for identity-pool authentication. For more +// information, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminRemoveUserFromGroup(ctx context.Context, params *AdminRemoveUserFromGroupInput, optFns ...func(*Options)) (*AdminRemoveUserFromGroupOutput, error) { + if params == nil { + params = &AdminRemoveUserFromGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminRemoveUserFromGroup", params, optFns, c.addOperationAdminRemoveUserFromGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminRemoveUserFromGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminRemoveUserFromGroupInput struct { + + // The name of the group that you want to remove the user from, for example + // MyTestGroup . + // + // This member is required. + GroupName *string + + // The ID of the user pool that contains the group and the user that you want to + // remove. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +type AdminRemoveUserFromGroupOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminRemoveUserFromGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminRemoveUserFromGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminRemoveUserFromGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminRemoveUserFromGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminRemoveUserFromGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminRemoveUserFromGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminRemoveUserFromGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminRemoveUserFromGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminResetUserPassword.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminResetUserPassword.go new file mode 100644 index 00000000..dd54ca77 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminResetUserPassword.go @@ -0,0 +1,233 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Resets the specified user's password in a user pool. This operation doesn't +// change the user's password, but sends a password-reset code. +// +// To use this API operation, your user pool must have self-service account +// recovery configured. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) AdminResetUserPassword(ctx context.Context, params *AdminResetUserPasswordInput, optFns ...func(*Options)) (*AdminResetUserPasswordOutput, error) { + if params == nil { + params = &AdminResetUserPasswordInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminResetUserPassword", params, optFns, c.addOperationAdminResetUserPasswordMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminResetUserPasswordOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to reset a user's password as an administrator. +type AdminResetUserPasswordInput struct { + + // The ID of the user pool where you want to reset the user's password. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. The AdminResetUserPassword API operation invokes the function that is + // assigned to the custom message trigger. When Amazon Cognito invokes this + // function, it passes a JSON payload, which the function receives as input. This + // payload contains a clientMetadata attribute, which provides the data that you + // assigned to the ClientMetadata parameter in your AdminResetUserPassword request. + // In your function code in Lambda, you can process the clientMetadata value to + // enhance your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + noSmithyDocumentSerde +} + +// Represents the response from the server to reset a user password as an +// administrator. +type AdminResetUserPasswordOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminResetUserPasswordMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminResetUserPassword{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminResetUserPassword{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminResetUserPassword"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminResetUserPasswordValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminResetUserPassword(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminResetUserPassword(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminResetUserPassword", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRespondToAuthChallenge.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRespondToAuthChallenge.go new file mode 100644 index 00000000..895b9680 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminRespondToAuthChallenge.go @@ -0,0 +1,552 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Some API operations in a user pool generate a challenge, like a prompt for an +// MFA code, for device authentication that bypasses MFA, or for a custom +// authentication challenge. An AdminRespondToAuthChallenge API request provides +// the answer to that challenge, like a code or a secure remote password (SRP). The +// parameters of a response to an authentication challenge vary with the type of +// challenge. +// +// For more information about custom authentication challenges, see [Custom authentication challenge Lambda triggers]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Custom authentication challenge Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) AdminRespondToAuthChallenge(ctx context.Context, params *AdminRespondToAuthChallengeInput, optFns ...func(*Options)) (*AdminRespondToAuthChallengeOutput, error) { + if params == nil { + params = &AdminRespondToAuthChallengeInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminRespondToAuthChallenge", params, optFns, c.addOperationAdminRespondToAuthChallengeMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminRespondToAuthChallengeOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The request to respond to the authentication challenge, as an administrator. +type AdminRespondToAuthChallengeInput struct { + + // The name of the challenge that you are responding to. + // + // Possible challenges include the following: + // + // All of the following challenges require USERNAME and, when the app client has a + // client secret, SECRET_HASH in the parameters. + // + // - WEB_AUTHN : Respond to the challenge with the results of a successful + // authentication with a WebAuthn authenticator, or passkey. Examples of WebAuthn + // authenticators include biometric devices and security keys. + // + // - PASSWORD : Respond with USER_PASSWORD_AUTH parameters: USERNAME (required), + // PASSWORD (required), SECRET_HASH (required if the app client is configured + // with a client secret), DEVICE_KEY . + // + // - PASSWORD_SRP : Respond with USER_SRP_AUTH parameters: USERNAME (required), + // SRP_A (required), SECRET_HASH (required if the app client is configured with a + // client secret), DEVICE_KEY . + // + // - SELECT_CHALLENGE : Respond to the challenge with USERNAME and an ANSWER that + // matches one of the challenge types in the AvailableChallenges response + // parameter. + // + // - SMS_MFA : Respond with an SMS_MFA_CODE that your user pool delivered in an + // SMS message. + // + // - EMAIL_OTP : Respond with an EMAIL_OTP_CODE that your user pool delivered in + // an email message. + // + // - PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP calculations. + // + // - CUSTOM_CHALLENGE : This is returned if your custom authentication flow + // determines that the user should pass another challenge before tokens are issued. + // The parameters of the challenge are determined by your Lambda function. + // + // - DEVICE_SRP_AUTH : Respond with the initial parameters of device SRP + // authentication. For more information, see [Signing in with a device]. + // + // - DEVICE_PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP + // calculations. For more information, see [Signing in with a device]. + // + // - NEW_PASSWORD_REQUIRED : For users who are required to change their passwords + // after successful first login. Respond to this challenge with NEW_PASSWORD and + // any required attributes that Amazon Cognito returned in the requiredAttributes + // parameter. You can also set values for attributes that aren't required by your + // user pool and that your app client can write. + // + // Amazon Cognito only returns this challenge for users who have temporary + // passwords. When you create passwordless users, you must provide values for all + // required attributes. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // - MFA_SETUP : For users who are required to setup an MFA factor before they + // can sign in. The MFA types activated for the user pool will be listed in the + // challenge parameters MFAS_CAN_SETUP value. + // + // To set up time-based one-time password (TOTP) MFA, use the session returned in + // this challenge from InitiateAuth or AdminInitiateAuth as an input to + // AssociateSoftwareToken . Then, use the session returned by VerifySoftwareToken + // as an input to RespondToAuthChallenge or AdminRespondToAuthChallenge with + // challenge name MFA_SETUP to complete sign-in. + // + // To set up SMS or email MFA, collect a phone_number or email attribute for the + // user. Then restart the authentication flow with an InitiateAuth or + // AdminInitiateAuth request. + // + // [Signing in with a device]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-signing-in-with-a-device + // + // This member is required. + ChallengeName types.ChallengeNameType + + // The ID of the app client where you initiated sign-in. + // + // This member is required. + ClientId *string + + // The ID of the user pool where you want to respond to an authentication + // challenge. + // + // This member is required. + UserPoolId *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // The responses to the challenge that you received in the previous request. Each + // challenge has its own required response parameters. The following examples are + // partial JSON request bodies that highlight challenge-response parameters. + // + // You must provide a SECRET_HASH parameter in all challenge responses to an app + // client that has a client secret. Include a DEVICE_KEY for device authentication. + // + // SELECT_CHALLENGE "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { + // "USERNAME": "[username]", "ANSWER": "[Challenge name]"} + // + // Available challenges are PASSWORD , PASSWORD_SRP , EMAIL_OTP , SMS_OTP , and + // WEB_AUTHN . + // + // Complete authentication in the SELECT_CHALLENGE response for PASSWORD , + // PASSWORD_SRP , and WEB_AUTHN : + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "WEB_AUTHN", "USERNAME": "[username]", "CREDENTIAL": + // "[AuthenticationResponseJSON]"} + // + // See [AuthenticationResponseJSON]. + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "PASSWORD", "USERNAME": "[username]", "PASSWORD": "[password]"} + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "PASSWORD_SRP", "USERNAME": "[username]", "SRP_A": "[SRP_A]"} + // + // For SMS_OTP and EMAIL_OTP , respond with the username and answer. Your user pool + // will send a code for the user to submit in the next challenge response. + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "SMS_OTP", "USERNAME": "[username]"} + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "EMAIL_OTP", "USERNAME": "[username]"} + // + // SMS_OTP "ChallengeName": "SMS_OTP", "ChallengeResponses": {"SMS_OTP_CODE": + // "[code]", "USERNAME": "[username]"} + // + // EMAIL_OTP "ChallengeName": "EMAIL_OTP", "ChallengeResponses": + // {"EMAIL_OTP_CODE": "[code]", "USERNAME": "[username]"} + // + // SMS_MFA "ChallengeName": "SMS_MFA", "ChallengeResponses": {"SMS_MFA_CODE": + // "[code]", "USERNAME": "[username]"} + // + // PASSWORD_VERIFIER This challenge response is part of the SRP flow. Amazon + // Cognito requires that your application respond to this challenge within a few + // seconds. When the response time exceeds this period, your user pool returns a + // NotAuthorizedException error. + // + // "ChallengeName": "PASSWORD_VERIFIER", "ChallengeResponses": + // {"PASSWORD_CLAIM_SIGNATURE": "[claim_signature]", "PASSWORD_CLAIM_SECRET_BLOCK": + // "[secret_block]", "TIMESTAMP": [timestamp], "USERNAME": "[username]"} + // + // Add "DEVICE_KEY" when you sign in with a remembered device. + // + // CUSTOM_CHALLENGE "ChallengeName": "CUSTOM_CHALLENGE", "ChallengeResponses": + // {"USERNAME": "[username]", "ANSWER": "[challenge_answer]"} + // + // Add "DEVICE_KEY" when you sign in with a remembered device. + // + // NEW_PASSWORD_REQUIRED "ChallengeName": "NEW_PASSWORD_REQUIRED", + // "ChallengeResponses": {"NEW_PASSWORD": "[new_password]", "USERNAME": + // "[username]"} + // + // To set any required attributes that InitiateAuth returned in an + // requiredAttributes parameter, add "userAttributes.[attribute_name]": + // "[attribute_value]" . This parameter can also set values for writable attributes + // that aren't required by your user pool. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // SOFTWARE_TOKEN_MFA "ChallengeName": "SOFTWARE_TOKEN_MFA", "ChallengeResponses": + // {"USERNAME": "[username]", "SOFTWARE_TOKEN_MFA_CODE": [authenticator_code]} + // + // DEVICE_SRP_AUTH "ChallengeName": "DEVICE_SRP_AUTH", "ChallengeResponses": + // {"USERNAME": "[username]", "DEVICE_KEY": "[device_key]", "SRP_A": "[srp_a]"} + // + // DEVICE_PASSWORD_VERIFIER "ChallengeName": "DEVICE_PASSWORD_VERIFIER", + // "ChallengeResponses": {"DEVICE_KEY": "[device_key]", "PASSWORD_CLAIM_SIGNATURE": + // "[claim_signature]", "PASSWORD_CLAIM_SECRET_BLOCK": "[secret_block]", + // "TIMESTAMP": [timestamp], "USERNAME": "[username]"} + // + // MFA_SETUP "ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": + // "[username]"}, "SESSION": "[Session ID from VerifySoftwareToken]" + // + // SELECT_MFA_TYPE "ChallengeName": "SELECT_MFA_TYPE", "ChallengeResponses": + // {"USERNAME": "[username]", "ANSWER": "[SMS_MFA or SOFTWARE_TOKEN_MFA]"} + // + // For more information about SECRET_HASH , see [Computing secret hash values]. For information about DEVICE_KEY + // , see [Working with user devices in your user pool]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + // [AuthenticationResponseJSON]: https://www.w3.org/TR/WebAuthn-3/#dictdef-authenticationresponsejson + // [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + ChallengeResponses map[string]string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the AdminRespondToAuthChallenge API action, Amazon + // Cognito invokes any functions that you have assigned to the following triggers: + // + // - Pre sign-up + // + // - custom message + // + // - Post authentication + // + // - User migration + // + // - Pre token generation + // + // - Define auth challenge + // + // - Create auth challenge + // + // - Verify auth challenge response + // + // When Amazon Cognito invokes any of these functions, it passes a JSON payload, + // which the function receives as input. This payload contains a clientMetadata + // attribute that provides the data that you assigned to the ClientMetadata + // parameter in your AdminRespondToAuthChallenge request. In your function code in + // Lambda, you can process the clientMetadata value to enhance your workflow for + // your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + ContextData *types.ContextDataType + + // The session identifier that maintains the state of authentication requests and + // challenge responses. If an AdminInitiateAuth or AdminRespondToAuthChallenge API + // request results in a determination that your application must pass another + // challenge, Amazon Cognito returns a session with other challenge parameters. + // Send this session identifier, unmodified, to the next + // AdminRespondToAuthChallenge request. + Session *string + + noSmithyDocumentSerde +} + +// Responds to the authentication challenge, as an administrator. +type AdminRespondToAuthChallengeOutput struct { + + // The outcome of a successful authentication process. After your application has + // passed all challenges, Amazon Cognito returns an AuthenticationResult with the + // JSON web tokens (JWTs) that indicate successful sign-in. + AuthenticationResult *types.AuthenticationResultType + + // The name of the next challenge that you must respond to. + // + // Possible challenges include the following: + // + // All of the following challenges require USERNAME and, when the app client has a + // client secret, SECRET_HASH in the parameters. + // + // - WEB_AUTHN : Respond to the challenge with the results of a successful + // authentication with a WebAuthn authenticator, or passkey. Examples of WebAuthn + // authenticators include biometric devices and security keys. + // + // - PASSWORD : Respond with USER_PASSWORD_AUTH parameters: USERNAME (required), + // PASSWORD (required), SECRET_HASH (required if the app client is configured + // with a client secret), DEVICE_KEY . + // + // - PASSWORD_SRP : Respond with USER_SRP_AUTH parameters: USERNAME (required), + // SRP_A (required), SECRET_HASH (required if the app client is configured with a + // client secret), DEVICE_KEY . + // + // - SELECT_CHALLENGE : Respond to the challenge with USERNAME and an ANSWER that + // matches one of the challenge types in the AvailableChallenges response + // parameter. + // + // - SMS_MFA : Respond with an SMS_MFA_CODE that your user pool delivered in an + // SMS message. + // + // - EMAIL_OTP : Respond with an EMAIL_OTP_CODE that your user pool delivered in + // an email message. + // + // - PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP calculations. + // + // - CUSTOM_CHALLENGE : This is returned if your custom authentication flow + // determines that the user should pass another challenge before tokens are issued. + // The parameters of the challenge are determined by your Lambda function. + // + // - DEVICE_SRP_AUTH : Respond with the initial parameters of device SRP + // authentication. For more information, see [Signing in with a device]. + // + // - DEVICE_PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP + // calculations. For more information, see [Signing in with a device]. + // + // - NEW_PASSWORD_REQUIRED : For users who are required to change their passwords + // after successful first login. Respond to this challenge with NEW_PASSWORD and + // any required attributes that Amazon Cognito returned in the requiredAttributes + // parameter. You can also set values for attributes that aren't required by your + // user pool and that your app client can write. + // + // Amazon Cognito only returns this challenge for users who have temporary + // passwords. When you create passwordless users, you must provide values for all + // required attributes. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // - MFA_SETUP : For users who are required to setup an MFA factor before they + // can sign in. The MFA types activated for the user pool will be listed in the + // challenge parameters MFAS_CAN_SETUP value. + // + // To set up time-based one-time password (TOTP) MFA, use the session returned in + // this challenge from InitiateAuth or AdminInitiateAuth as an input to + // AssociateSoftwareToken . Then, use the session returned by VerifySoftwareToken + // as an input to RespondToAuthChallenge or AdminRespondToAuthChallenge with + // challenge name MFA_SETUP to complete sign-in. + // + // To set up SMS or email MFA, collect a phone_number or email attribute for the + // user. Then restart the authentication flow with an InitiateAuth or + // AdminInitiateAuth request. + // + // [Signing in with a device]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-signing-in-with-a-device + ChallengeName types.ChallengeNameType + + // The parameters that define your response to the next challenge. + ChallengeParameters map[string]string + + // The session identifier that maintains the state of authentication requests and + // challenge responses. If an AdminInitiateAuth or AdminRespondToAuthChallenge API + // request results in a determination that your application must pass another + // challenge, Amazon Cognito returns a session with other challenge parameters. + // Send this session identifier, unmodified, to the next + // AdminRespondToAuthChallenge request. + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminRespondToAuthChallengeMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminRespondToAuthChallenge{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminRespondToAuthChallenge{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminRespondToAuthChallenge"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminRespondToAuthChallengeValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminRespondToAuthChallenge(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminRespondToAuthChallenge(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminRespondToAuthChallenge", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserMFAPreference.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserMFAPreference.go new file mode 100644 index 00000000..38ac38bf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserMFAPreference.go @@ -0,0 +1,201 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Sets the user's multi-factor authentication (MFA) preference, including which +// MFA options are activated, and if any are preferred. Only one factor can be set +// as preferred. The preferred MFA factor will be used to authenticate a user if +// multiple factors are activated. If multiple options are activated and no +// preference is set, a challenge to choose an MFA option will be returned during +// sign-in. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminSetUserMFAPreference(ctx context.Context, params *AdminSetUserMFAPreferenceInput, optFns ...func(*Options)) (*AdminSetUserMFAPreferenceOutput, error) { + if params == nil { + params = &AdminSetUserMFAPreferenceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminSetUserMFAPreference", params, optFns, c.addOperationAdminSetUserMFAPreferenceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminSetUserMFAPreferenceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminSetUserMFAPreferenceInput struct { + + // The ID of the user pool where you want to set a user's MFA preferences. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // User preferences for email message MFA. Activates or deactivates email MFA and + // sets it as the preferred MFA method when multiple methods are available. To + // activate this setting, your user pool must be in the [Essentials tier]or higher. + // + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + EmailMfaSettings *types.EmailMfaSettingsType + + // User preferences for SMS message MFA. Activates or deactivates SMS MFA and sets + // it as the preferred MFA method when multiple methods are available. + SMSMfaSettings *types.SMSMfaSettingsType + + // User preferences for time-based one-time password (TOTP) MFA. Activates or + // deactivates TOTP MFA and sets it as the preferred MFA method when multiple + // methods are available. This operation can set TOTP as a user's preferred MFA + // method before they register a TOTP authenticator. + SoftwareTokenMfaSettings *types.SoftwareTokenMfaSettingsType + + noSmithyDocumentSerde +} + +type AdminSetUserMFAPreferenceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminSetUserMFAPreferenceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminSetUserMFAPreference{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminSetUserMFAPreference{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminSetUserMFAPreference"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminSetUserMFAPreferenceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminSetUserMFAPreference(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminSetUserMFAPreference(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminSetUserMFAPreference", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserPassword.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserPassword.go new file mode 100644 index 00000000..10052662 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserPassword.go @@ -0,0 +1,218 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Sets the specified user's password in a user pool. This operation +// administratively sets a temporary or permanent password for a user. With this +// operation, you can bypass self-service password changes and permit immediate +// sign-in with the password that you set. To do this, set Permanent to true . +// +// You can also set a new temporary password in this request, send it to a user, +// and require them to choose a new password on their next sign-in. To do this, set +// Permanent to false . +// +// If the password is temporary, the user's Status becomes FORCE_CHANGE_PASSWORD . +// When the user next tries to sign in, the InitiateAuth or AdminInitiateAuth +// response includes the NEW_PASSWORD_REQUIRED challenge. If the user doesn't sign +// in before the temporary password expires, they can no longer sign in and you +// must repeat this operation to set a temporary or permanent password for them. +// +// After the user sets a new password, or if you set a permanent password, their +// status becomes Confirmed . +// +// AdminSetUserPassword can set a password for the user profile that Amazon +// Cognito creates for third-party federated users. When you set a password, the +// federated user's status changes from EXTERNAL_PROVIDER to CONFIRMED . A user in +// this state can sign in as a federated user, and initiate authentication flows in +// the API like a linked native user. They can also modify their password and +// attributes in token-authenticated API requests like ChangePassword and +// UpdateUserAttributes . As a best security practice and to keep users in sync +// with your external IdP, don't set passwords on federated user profiles. To set +// up a federated user for native sign-in with a linked native user, refer to [Linking federated users to an existing user profile]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Linking federated users to an existing user profile]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation-consolidate-users.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminSetUserPassword(ctx context.Context, params *AdminSetUserPasswordInput, optFns ...func(*Options)) (*AdminSetUserPasswordOutput, error) { + if params == nil { + params = &AdminSetUserPasswordInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminSetUserPassword", params, optFns, c.addOperationAdminSetUserPasswordMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminSetUserPasswordOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminSetUserPasswordInput struct { + + // The new temporary or permanent password that you want to set for the user. You + // can't remove the password for a user who already has a password so that they can + // only sign in with passwordless methods. In this scenario, you must create a new + // user without a password. + // + // This member is required. + Password *string + + // The ID of the user pool where you want to set the user's password. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // Set to true to set a password that the user can immediately sign in with. Set + // to false to set a temporary password that the user must change on their next + // sign-in. + Permanent bool + + noSmithyDocumentSerde +} + +type AdminSetUserPasswordOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminSetUserPasswordMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminSetUserPassword{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminSetUserPassword{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminSetUserPassword"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminSetUserPasswordValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminSetUserPassword(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminSetUserPassword(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminSetUserPassword", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserSettings.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserSettings.go new file mode 100644 index 00000000..204d7b60 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminSetUserSettings.go @@ -0,0 +1,192 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// This action is no longer supported. You can use it to configure only SMS MFA. +// +// You can't use it to configure time-based one-time password (TOTP) software token +// MFA. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminSetUserSettings(ctx context.Context, params *AdminSetUserSettingsInput, optFns ...func(*Options)) (*AdminSetUserSettingsOutput, error) { + if params == nil { + params = &AdminSetUserSettingsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminSetUserSettings", params, optFns, c.addOperationAdminSetUserSettingsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminSetUserSettingsOutput) + out.ResultMetadata = metadata + return out, nil +} + +// You can use this parameter to set an MFA configuration that uses the SMS +// delivery medium. +type AdminSetUserSettingsInput struct { + + // You can use this parameter only to set an SMS configuration that uses SMS for + // delivery. + // + // This member is required. + MFAOptions []types.MFAOptionType + + // The ID of the user pool that contains the user whose options you're setting. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to set user settings as an +// administrator. +type AdminSetUserSettingsOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminSetUserSettingsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminSetUserSettings{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminSetUserSettings{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminSetUserSettings"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminSetUserSettingsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminSetUserSettings(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminSetUserSettings(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminSetUserSettings", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateAuthEventFeedback.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateAuthEventFeedback.go new file mode 100644 index 00000000..dd9ea423 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateAuthEventFeedback.go @@ -0,0 +1,205 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Provides the feedback for an authentication event generated by threat +// protection features. Your response indicates that you think that the event +// either was from a valid user or was an unwanted authentication attempt. This +// feedback improves the risk evaluation decision for the user pool as part of +// Amazon Cognito threat protection. To activate this setting, your user pool must +// be on the [Plus tier]. +// +// To train the threat-protection model to recognize trusted and untrusted sign-in +// characteristics, configure threat protection in audit-only mode and provide a +// mechanism for users or administrators to submit feedback. Your feedback can tell +// Amazon Cognito that a risk rating was assigned at a level you don't agree with. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminUpdateAuthEventFeedback(ctx context.Context, params *AdminUpdateAuthEventFeedbackInput, optFns ...func(*Options)) (*AdminUpdateAuthEventFeedbackOutput, error) { + if params == nil { + params = &AdminUpdateAuthEventFeedbackInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminUpdateAuthEventFeedback", params, optFns, c.addOperationAdminUpdateAuthEventFeedbackMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminUpdateAuthEventFeedbackOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AdminUpdateAuthEventFeedbackInput struct { + + // The ID of the threat protection authentication event that you want to update. + // + // This member is required. + EventId *string + + // Your feedback to the authentication event. When you provide a FeedbackValue + // value of valid , you tell Amazon Cognito that you trust a user session where + // Amazon Cognito has evaluated some level of risk. When you provide a + // FeedbackValue value of invalid , you tell Amazon Cognito that you don't trust a + // user session, or you don't believe that Amazon Cognito evaluated a high-enough + // risk level. + // + // This member is required. + FeedbackValue types.FeedbackValueType + + // The ID of the user pool where you want to submit authentication-event feedback. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +type AdminUpdateAuthEventFeedbackOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminUpdateAuthEventFeedbackMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminUpdateAuthEventFeedback{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminUpdateAuthEventFeedback{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminUpdateAuthEventFeedback"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminUpdateAuthEventFeedbackValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminUpdateAuthEventFeedback(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminUpdateAuthEventFeedback(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminUpdateAuthEventFeedback", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateDeviceStatus.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateDeviceStatus.go new file mode 100644 index 00000000..ad438f2e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateDeviceStatus.go @@ -0,0 +1,197 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates the status of a user's device so that it is marked as remembered or not +// remembered for the purpose of device authentication. Device authentication is a +// "remember me" mechanism that silently completes sign-in from trusted devices +// with a device key instead of a user-provided MFA code. This operation changes +// the status of a device without deleting it, so you can enable it again later. +// For more information about device authentication, see [Working with devices]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) AdminUpdateDeviceStatus(ctx context.Context, params *AdminUpdateDeviceStatusInput, optFns ...func(*Options)) (*AdminUpdateDeviceStatusOutput, error) { + if params == nil { + params = &AdminUpdateDeviceStatusInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminUpdateDeviceStatus", params, optFns, c.addOperationAdminUpdateDeviceStatusMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminUpdateDeviceStatusOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The request to update the device status, as an administrator. +type AdminUpdateDeviceStatusInput struct { + + // The unique identifier, or device key, of the device that you want to update the + // status for. + // + // This member is required. + DeviceKey *string + + // The ID of the user pool where you want to change a user's device status. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // To enable device authentication with the specified device, set to remembered .To + // disable, set to not_remembered . + DeviceRememberedStatus types.DeviceRememberedStatusType + + noSmithyDocumentSerde +} + +// The status response to the request to update the device, as an administrator. +type AdminUpdateDeviceStatusOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminUpdateDeviceStatusMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminUpdateDeviceStatus{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminUpdateDeviceStatus{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminUpdateDeviceStatus"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminUpdateDeviceStatusValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminUpdateDeviceStatus(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminUpdateDeviceStatus(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminUpdateDeviceStatus", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateUserAttributes.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateUserAttributes.go new file mode 100644 index 00000000..34622373 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUpdateUserAttributes.go @@ -0,0 +1,262 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates the specified user's attributes. To delete an attribute from your user, +// submit the attribute in your API request with a blank value. +// +// For custom attributes, you must add a custom: prefix to the attribute name, for +// example custom:department . +// +// This operation can set a user's email address or phone number as verified and +// permit immediate sign-in in user pools that require verification of these +// attributes. To do this, set the email_verified or phone_number_verified +// attribute to true . +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) AdminUpdateUserAttributes(ctx context.Context, params *AdminUpdateUserAttributesInput, optFns ...func(*Options)) (*AdminUpdateUserAttributesOutput, error) { + if params == nil { + params = &AdminUpdateUserAttributesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminUpdateUserAttributes", params, optFns, c.addOperationAdminUpdateUserAttributesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminUpdateUserAttributesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to update the user's attributes as an administrator. +type AdminUpdateUserAttributesInput struct { + + // An array of name-value pairs representing user attributes. + // + // For custom attributes, you must prepend the custom: prefix to the attribute + // name. + // + // If your user pool requires verification before Amazon Cognito updates an + // attribute value that you specify in this request, Amazon Cognito doesn’t + // immediately update the value of that attribute. After your user receives and + // responds to a verification message to verify the new value, Amazon Cognito + // updates the attribute value. Your user can sign in and receive messages with the + // original attribute value until they verify the new value. + // + // To skip the verification message and update the value of an attribute that + // requires verification in the same API request, include the email_verified or + // phone_number_verified attribute, with a value of true . If you set the + // email_verified or phone_number_verified value for an email or phone_number + // attribute that requires verification to true , Amazon Cognito doesn’t send a + // verification message to your user. + // + // This member is required. + UserAttributes []types.AttributeType + + // The ID of the user pool where you want to update user attributes. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the AdminUpdateUserAttributes API action, Amazon Cognito + // invokes the function that is assigned to the custom message trigger. When Amazon + // Cognito invokes this function, it passes a JSON payload, which the function + // receives as input. This payload contains a clientMetadata attribute, which + // provides the data that you assigned to the ClientMetadata parameter in your + // AdminUpdateUserAttributes request. In your function code in Lambda, you can + // process the clientMetadata value to enhance your workflow for your specific + // needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + noSmithyDocumentSerde +} + +// Represents the response from the server for the request to update user +// attributes as an administrator. +type AdminUpdateUserAttributesOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminUpdateUserAttributesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminUpdateUserAttributes{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminUpdateUserAttributes{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminUpdateUserAttributes"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminUpdateUserAttributesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminUpdateUserAttributes(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminUpdateUserAttributes(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminUpdateUserAttributes", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUserGlobalSignOut.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUserGlobalSignOut.go new file mode 100644 index 00000000..a104a43b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AdminUserGlobalSignOut.go @@ -0,0 +1,207 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Invalidates the identity, access, and refresh tokens that Amazon Cognito issued +// to a user. Call this operation with your administrative credentials when your +// user signs out of your app. This results in the following behavior. +// +// - Amazon Cognito no longer accepts token-authorized user operations that you +// authorize with a signed-out user's access tokens. For more information, see [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// Amazon Cognito returns an Access Token has been revoked error when your app +// +// attempts to authorize a user pools API request with a revoked access token that +// contains the scope aws.cognito.signin.user.admin . +// +// - Amazon Cognito no longer accepts a signed-out user's ID token in a [GetId]request +// to an identity pool with ServerSideTokenCheck enabled for its user pool IdP +// configuration in [CognitoIdentityProvider]. +// +// - Amazon Cognito no longer accepts a signed-out user's refresh tokens in +// refresh requests. +// +// Other requests might be valid until your user's token expires. This operation +// doesn't clear the [managed login]session cookie. To clear the session for a user who signed in +// with managed login or the classic hosted UI, direct their browser session to the +// [logout endpoint]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [logout endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// +// [CognitoIdentityProvider]: https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_CognitoIdentityProvider.html +// [GetId]: https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html +func (c *Client) AdminUserGlobalSignOut(ctx context.Context, params *AdminUserGlobalSignOutInput, optFns ...func(*Options)) (*AdminUserGlobalSignOutOutput, error) { + if params == nil { + params = &AdminUserGlobalSignOutInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AdminUserGlobalSignOut", params, optFns, c.addOperationAdminUserGlobalSignOutMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AdminUserGlobalSignOutOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The request to sign out of all devices, as an administrator. +type AdminUserGlobalSignOutInput struct { + + // The ID of the user pool where you want to sign out a user. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +// The global sign-out response, as an administrator. +type AdminUserGlobalSignOutOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAdminUserGlobalSignOutMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAdminUserGlobalSignOut{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAdminUserGlobalSignOut{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AdminUserGlobalSignOut"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpAdminUserGlobalSignOutValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAdminUserGlobalSignOut(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAdminUserGlobalSignOut(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AdminUserGlobalSignOut", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AssociateSoftwareToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AssociateSoftwareToken.go new file mode 100644 index 00000000..df1f9830 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_AssociateSoftwareToken.go @@ -0,0 +1,180 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Begins setup of time-based one-time password (TOTP) multi-factor authentication +// (MFA) for a user, with a unique private key that Amazon Cognito generates and +// returns in the API response. You can authorize an AssociateSoftwareToken +// request with either the user's access token, or a session string from a +// challenge response that you received from Amazon Cognito. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) AssociateSoftwareToken(ctx context.Context, params *AssociateSoftwareTokenInput, optFns ...func(*Options)) (*AssociateSoftwareTokenOutput, error) { + if params == nil { + params = &AssociateSoftwareTokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "AssociateSoftwareToken", params, optFns, c.addOperationAssociateSoftwareTokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*AssociateSoftwareTokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +type AssociateSoftwareTokenInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // You can provide either an access token or a session ID in the request. + AccessToken *string + + // The session identifier that maintains the state of authentication requests and + // challenge responses. In AssociateSoftwareToken , this is the session ID from a + // successful sign-in. You can provide either an access token or a session ID in + // the request. + Session *string + + noSmithyDocumentSerde +} + +type AssociateSoftwareTokenOutput struct { + + // A unique generated shared secret code that is used by the TOTP algorithm to + // generate a one-time code. + SecretCode *string + + // The session identifier that maintains the state of authentication requests and + // challenge responses. + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationAssociateSoftwareTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpAssociateSoftwareToken{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAssociateSoftwareToken{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "AssociateSoftwareToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssociateSoftwareToken(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opAssociateSoftwareToken(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "AssociateSoftwareToken", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ChangePassword.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ChangePassword.go new file mode 100644 index 00000000..f1b25a2f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ChangePassword.go @@ -0,0 +1,176 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Changes the password for the currently signed-in user. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) ChangePassword(ctx context.Context, params *ChangePasswordInput, optFns ...func(*Options)) (*ChangePasswordOutput, error) { + if params == nil { + params = &ChangePasswordInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ChangePassword", params, optFns, c.addOperationChangePasswordMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ChangePasswordOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to change a user password. +type ChangePasswordInput struct { + + // A valid access token that Amazon Cognito issued to the user whose password you + // want to change. + // + // This member is required. + AccessToken *string + + // A new password that you prompted the user to enter in your application. + // + // This member is required. + ProposedPassword *string + + // The user's previous password. Required if the user has a password. If the user + // has no password and only signs in with passwordless authentication options, you + // can omit this parameter. + PreviousPassword *string + + noSmithyDocumentSerde +} + +// The response from the server to the change password request. +type ChangePasswordOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationChangePasswordMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpChangePassword{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpChangePassword{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ChangePassword"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpChangePasswordValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opChangePassword(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opChangePassword(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ChangePassword", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CompleteWebAuthnRegistration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CompleteWebAuthnRegistration.go new file mode 100644 index 00000000..f86703ad --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CompleteWebAuthnRegistration.go @@ -0,0 +1,165 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Completes registration of a passkey authenticator for the currently signed-in +// user. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +func (c *Client) CompleteWebAuthnRegistration(ctx context.Context, params *CompleteWebAuthnRegistrationInput, optFns ...func(*Options)) (*CompleteWebAuthnRegistrationOutput, error) { + if params == nil { + params = &CompleteWebAuthnRegistrationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CompleteWebAuthnRegistration", params, optFns, c.addOperationCompleteWebAuthnRegistrationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CompleteWebAuthnRegistrationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CompleteWebAuthnRegistrationInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // A [RegistrationResponseJSON] public-key credential response from the user's passkey provider. + // + // [RegistrationResponseJSON]: https://www.w3.org/TR/WebAuthn-3/#dictdef-registrationresponsejson + // + // This member is required. + Credential document.Interface + + noSmithyDocumentSerde +} + +type CompleteWebAuthnRegistrationOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCompleteWebAuthnRegistrationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCompleteWebAuthnRegistration{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCompleteWebAuthnRegistration{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CompleteWebAuthnRegistration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCompleteWebAuthnRegistrationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCompleteWebAuthnRegistration(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCompleteWebAuthnRegistration(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CompleteWebAuthnRegistration", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmDevice.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmDevice.go new file mode 100644 index 00000000..97f75038 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmDevice.go @@ -0,0 +1,196 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Confirms a device that a user wants to remember. A remembered device is a +// "Remember me on this device" option for user pools that perform authentication +// with the device key of a trusted device in the back end, instead of a +// user-provided MFA code. For more information about device authentication, see [Working with user devices in your user pool]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +func (c *Client) ConfirmDevice(ctx context.Context, params *ConfirmDeviceInput, optFns ...func(*Options)) (*ConfirmDeviceOutput, error) { + if params == nil { + params = &ConfirmDeviceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ConfirmDevice", params, optFns, c.addOperationConfirmDeviceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ConfirmDeviceOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The confirm-device request. +type ConfirmDeviceInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The unique identifier, or device key, of the device that you want to update the + // status for. + // + // This member is required. + DeviceKey *string + + // A friendly name for the device, for example MyMobilePhone . + DeviceName *string + + // The configuration of the device secret verifier. + DeviceSecretVerifierConfig *types.DeviceSecretVerifierConfigType + + noSmithyDocumentSerde +} + +// The confirm-device response. +type ConfirmDeviceOutput struct { + + // When true , your user must confirm that they want to remember the device. Prompt + // the user for an answer. + // + // When false , immediately sets the device as remembered and eligible for device + // authentication. + // + // You can configure your user pool to always remember devices, in which case this + // response is false , or to allow users to opt in, in which case this response is + // true . Configure this option under Device tracking in the Sign-in menu of your + // user pool. + UserConfirmationNecessary bool + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationConfirmDeviceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpConfirmDevice{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpConfirmDevice{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ConfirmDevice"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpConfirmDeviceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opConfirmDevice(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opConfirmDevice(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ConfirmDevice", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmForgotPassword.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmForgotPassword.go new file mode 100644 index 00000000..0736b361 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmForgotPassword.go @@ -0,0 +1,242 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// This public API operation accepts a confirmation code that Amazon Cognito sent +// to a user and accepts a new password for that user. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) ConfirmForgotPassword(ctx context.Context, params *ConfirmForgotPasswordInput, optFns ...func(*Options)) (*ConfirmForgotPasswordOutput, error) { + if params == nil { + params = &ConfirmForgotPasswordInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ConfirmForgotPassword", params, optFns, c.addOperationConfirmForgotPasswordMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ConfirmForgotPasswordOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The request representing the confirmation for a password reset. +type ConfirmForgotPasswordInput struct { + + // The ID of the app client where the user wants to reset their password. This + // parameter is an identifier of the client application that users are resetting + // their password from, but this operation resets users' irrespective of the app + // clients they sign in to. + // + // This member is required. + ClientId *string + + // The confirmation code that your user pool delivered when your user requested to + // reset their password. + // + // This member is required. + ConfirmationCode *string + + // The new password that your user wants to set. + // + // This member is required. + Password *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the ConfirmForgotPassword API action, Amazon Cognito + // invokes the function that is assigned to the post confirmation trigger. When + // Amazon Cognito invokes this function, it passes a JSON payload, which the + // function receives as input. This payload contains a clientMetadata attribute, + // which provides the data that you assigned to the ClientMetadata parameter in + // your ConfirmForgotPassword request. In your function code in Lambda, you can + // process the clientMetadata value to enhance your workflow for your specific + // needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // A keyed-hash message authentication code (HMAC) calculated using the secret key + // of a user pool client and username plus the client ID in the message. For more + // information about SecretHash , see [Computing secret hash values]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + SecretHash *string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + noSmithyDocumentSerde +} + +// The response from the server that results from a user's request to retrieve a +// forgotten password. +type ConfirmForgotPasswordOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationConfirmForgotPasswordMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpConfirmForgotPassword{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpConfirmForgotPassword{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ConfirmForgotPassword"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpConfirmForgotPasswordValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opConfirmForgotPassword(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opConfirmForgotPassword(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ConfirmForgotPassword", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmSignUp.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmSignUp.go new file mode 100644 index 00000000..83247743 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ConfirmSignUp.go @@ -0,0 +1,269 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Confirms the account of a new user. This public API operation submits a code +// that Amazon Cognito sent to your user when they signed up in your user pool. +// After your user enters their code, they confirm ownership of the email address +// or phone number that they provided, and their user account becomes active. +// Depending on your user pool configuration, your users will receive their +// confirmation code in an email or SMS message. +// +// Local users who signed up in your user pool are the only type of user who can +// confirm sign-up with a code. Users who federate through an external identity +// provider (IdP) have already been confirmed by their IdP. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) ConfirmSignUp(ctx context.Context, params *ConfirmSignUpInput, optFns ...func(*Options)) (*ConfirmSignUpOutput, error) { + if params == nil { + params = &ConfirmSignUpInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ConfirmSignUp", params, optFns, c.addOperationConfirmSignUpMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ConfirmSignUpOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to confirm registration of a user. +type ConfirmSignUpInput struct { + + // The ID of the app client associated with the user pool. + // + // This member is required. + ClientId *string + + // The confirmation code that your user pool sent in response to the SignUp + // request. + // + // This member is required. + ConfirmationCode *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the ConfirmSignUp API action, Amazon Cognito invokes the + // function that is assigned to the post confirmation trigger. When Amazon Cognito + // invokes this function, it passes a JSON payload, which the function receives as + // input. This payload contains a clientMetadata attribute, which provides the + // data that you assigned to the ClientMetadata parameter in your ConfirmSignUp + // request. In your function code in Lambda, you can process the clientMetadata + // value to enhance your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // When true , forces user confirmation despite any existing aliases. Defaults to + // false . A value of true migrates the alias from an existing user to the new + // user if an existing user already has the phone number or email address as an + // alias. + // + // Say, for example, that an existing user has an email attribute of + // bob@example.com and email is an alias in your user pool. If the new user also + // has an email of bob@example.com and your ConfirmSignUp response sets + // ForceAliasCreation to true , the new user can sign in with a username of + // bob@example.com and the existing user can no longer do so. + // + // If false and an attribute belongs to an existing alias, this request returns an + // AliasExistsException error. + // + // For more information about sign-in aliases, see [Customizing sign-in attributes]. + // + // [Customizing sign-in attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases + ForceAliasCreation bool + + // A keyed-hash message authentication code (HMAC) calculated using the secret key + // of a user pool client and username plus the client ID in the message. For more + // information about SecretHash , see [Computing secret hash values]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + SecretHash *string + + // The optional session ID from a SignUp API request. You can sign in a user + // directly from the sign-up process with the USER_AUTH authentication flow. + Session *string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + noSmithyDocumentSerde +} + +// Represents the response from the server for the registration confirmation. +type ConfirmSignUpOutput struct { + + // A session identifier that you can use to immediately sign in the confirmed + // user. You can automatically sign users in with the one-time password that they + // provided in a successful ConfirmSignUp request. + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationConfirmSignUpMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpConfirmSignUp{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpConfirmSignUp{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ConfirmSignUp"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpConfirmSignUpValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opConfirmSignUp(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opConfirmSignUp(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ConfirmSignUp", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateGroup.go new file mode 100644 index 00000000..3355c67f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateGroup.go @@ -0,0 +1,209 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a new group in the specified user pool. For more information about user +// pool groups, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateGroup(ctx context.Context, params *CreateGroupInput, optFns ...func(*Options)) (*CreateGroupOutput, error) { + if params == nil { + params = &CreateGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateGroup", params, optFns, c.addOperationCreateGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateGroupInput struct { + + // A name for the group. This name must be unique in your user pool. + // + // This member is required. + GroupName *string + + // The ID of the user pool where you want to create a user group. + // + // This member is required. + UserPoolId *string + + // A description of the group that you're creating. + Description *string + + // A non-negative integer value that specifies the precedence of this group + // relative to the other groups that a user can belong to in the user pool. Zero is + // the highest precedence value. Groups with lower Precedence values take + // precedence over groups with higher or null Precedence values. If a user belongs + // to two or more groups, it is the group with the lowest precedence value whose + // role ARN is given in the user's tokens for the cognito:roles and + // cognito:preferred_role claims. + // + // Two groups can have the same Precedence value. If this happens, neither group + // takes precedence over the other. If two groups with the same Precedence have + // the same role ARN, that role is used in the cognito:preferred_role claim in + // tokens for users in each group. If the two groups have different role ARNs, the + // cognito:preferred_role claim isn't set in users' tokens. + // + // The default Precedence value is null. The maximum Precedence value is 2^31-1 . + Precedence *int32 + + // The Amazon Resource Name (ARN) for the IAM role that you want to associate with + // the group. A group role primarily declares a preferred role for the credentials + // that you get from an identity pool. Amazon Cognito ID tokens have a + // cognito:preferred_role claim that presents the highest-precedence group that a + // user belongs to. Both ID and access tokens also contain a cognito:groups claim + // that list all the groups that a user is a member of. + RoleArn *string + + noSmithyDocumentSerde +} + +type CreateGroupOutput struct { + + // The response object for a created group. + Group *types.GroupType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateIdentityProvider.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateIdentityProvider.go new file mode 100644 index 00000000..223fe0c7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateIdentityProvider.go @@ -0,0 +1,306 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Adds a configuration and trust relationship between a third-party identity +// provider (IdP) and a user pool. Amazon Cognito accepts sign-in with third-party +// identity providers through managed login and OIDC relying-party libraries. For +// more information, see [Third-party IdP sign-in]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Third-party IdP sign-in]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateIdentityProvider(ctx context.Context, params *CreateIdentityProviderInput, optFns ...func(*Options)) (*CreateIdentityProviderOutput, error) { + if params == nil { + params = &CreateIdentityProviderInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateIdentityProvider", params, optFns, c.addOperationCreateIdentityProviderMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateIdentityProviderOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateIdentityProviderInput struct { + + // The scopes, URLs, and identifiers for your external identity provider. The + // following examples describe the provider detail keys for each IdP type. These + // values and their schema are subject to change. Social IdP authorize_scopes + // values must match the values listed here. + // + // OpenID Connect (OIDC) Amazon Cognito accepts the following elements when it + // can't discover endpoint URLs from oidc_issuer : attributes_url , authorize_url , + // jwks_uri , token_url . + // + // Create or update request: "ProviderDetails": { "attributes_request_method": + // "GET", "attributes_url": "https://auth.example.com/userInfo", + // "authorize_scopes": "openid profile email", "authorize_url": + // "https://auth.example.com/authorize", "client_id": "1example23456789", + // "client_secret": "provider-app-client-secret", "jwks_uri": + // "https://auth.example.com/.well-known/jwks.json", "oidc_issuer": + // "https://auth.example.com", "token_url": "https://example.com/token" } + // + // Describe response: "ProviderDetails": { "attributes_request_method": "GET", + // "attributes_url": "https://auth.example.com/userInfo", + // "attributes_url_add_attributes": "false", "authorize_scopes": "openid profile + // email", "authorize_url": "https://auth.example.com/authorize", "client_id": + // "1example23456789", "client_secret": "provider-app-client-secret", "jwks_uri": + // "https://auth.example.com/.well-known/jwks.json", "oidc_issuer": + // "https://auth.example.com", "token_url": "https://example.com/token" } + // + // SAML Create or update request with Metadata URL: "ProviderDetails": { + // "IDPInit": "true", "IDPSignout": "true", "EncryptedResponses" : "true", + // "MetadataURL": "https://auth.example.com/sso/saml/metadata", + // "RequestSigningAlgorithm": "rsa-sha256" } + // + // Create or update request with Metadata file: "ProviderDetails": { "IDPInit": + // "true", "IDPSignout": "true", "EncryptedResponses" : "true", "MetadataFile": + // "[metadata XML]", "RequestSigningAlgorithm": "rsa-sha256" } + // + // The value of MetadataFile must be the plaintext metadata document with all + // quote (") characters escaped by backslashes. + // + // Describe response: "ProviderDetails": { "IDPInit": "true", "IDPSignout": + // "true", "EncryptedResponses" : "true", "ActiveEncryptionCertificate": + // "[certificate]", "MetadataURL": "https://auth.example.com/sso/saml/metadata", + // "RequestSigningAlgorithm": "rsa-sha256", "SLORedirectBindingURI": + // "https://auth.example.com/slo/saml", "SSORedirectBindingURI": + // "https://auth.example.com/sso/saml" } + // + // LoginWithAmazon Create or update request: "ProviderDetails": { + // "authorize_scopes": "profile postal_code", "client_id": + // "amzn1.application-oa2-client.1example23456789", "client_secret": + // "provider-app-client-secret" + // + // Describe response: "ProviderDetails": { "attributes_url": + // "https://api.amazon.com/user/profile", "attributes_url_add_attributes": "false", + // "authorize_scopes": "profile postal_code", "authorize_url": + // "https://www.amazon.com/ap/oa", "client_id": + // "amzn1.application-oa2-client.1example23456789", "client_secret": + // "provider-app-client-secret", "token_request_method": "POST", "token_url": + // "https://api.amazon.com/auth/o2/token" } + // + // Google Create or update request: "ProviderDetails": { "authorize_scopes": + // "email profile openid", "client_id": + // "1example23456789.apps.googleusercontent.com", "client_secret": + // "provider-app-client-secret" } + // + // Describe response: "ProviderDetails": { "attributes_url": + // "https://people.googleapis.com/v1/people/me?personFields=", + // "attributes_url_add_attributes": "true", "authorize_scopes": "email profile + // openid", "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth", + // "client_id": "1example23456789.apps.googleusercontent.com", "client_secret": + // "provider-app-client-secret", "oidc_issuer": "https://accounts.google.com", + // "token_request_method": "POST", "token_url": + // "https://www.googleapis.com/oauth2/v4/token" } + // + // SignInWithApple Create or update request: "ProviderDetails": { + // "authorize_scopes": "email name", "client_id": "com.example.cognito", + // "private_key": "1EXAMPLE", "key_id": "2EXAMPLE", "team_id": "3EXAMPLE" } + // + // Describe response: "ProviderDetails": { "attributes_url_add_attributes": + // "false", "authorize_scopes": "email name", "authorize_url": + // "https://appleid.apple.com/auth/authorize", "client_id": "com.example.cognito", + // "key_id": "1EXAMPLE", "oidc_issuer": "https://appleid.apple.com", "team_id": + // "2EXAMPLE", "token_request_method": "POST", "token_url": + // "https://appleid.apple.com/auth/token" } + // + // Facebook Create or update request: "ProviderDetails": { "api_version": "v17.0", + // "authorize_scopes": "public_profile, email", "client_id": "1example23456789", + // "client_secret": "provider-app-client-secret" } + // + // Describe response: "ProviderDetails": { "api_version": "v17.0", + // "attributes_url": "https://graph.facebook.com/v17.0/me?fields=", + // "attributes_url_add_attributes": "true", "authorize_scopes": "public_profile, + // email", "authorize_url": "https://www.facebook.com/v17.0/dialog/oauth", + // "client_id": "1example23456789", "client_secret": "provider-app-client-secret", + // "token_request_method": "GET", "token_url": + // "https://graph.facebook.com/v17.0/oauth/access_token" } + // + // This member is required. + ProviderDetails map[string]string + + // The name that you want to assign to the IdP. You can pass the identity provider + // name in the identity_provider query parameter of requests to the [Authorize endpoint] to silently + // redirect to sign-in with the associated IdP. + // + // [Authorize endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html + // + // This member is required. + ProviderName *string + + // The type of IdP that you want to add. Amazon Cognito supports OIDC, SAML 2.0, + // Login With Amazon, Sign In With Apple, Google, and Facebook IdPs. + // + // This member is required. + ProviderType types.IdentityProviderTypeType + + // The Id of the user pool where you want to create an IdP. + // + // This member is required. + UserPoolId *string + + // A mapping of IdP attributes to standard and custom user pool attributes. + // Specify a user pool attribute as the key of the key-value pair, and the IdP + // attribute claim name as the value. + AttributeMapping map[string]string + + // An array of IdP identifiers, for example "IdPIdentifiers": [ "MyIdP", "MyIdP2" ] + // . Identifiers are friendly names that you can pass in the idp_identifier query + // parameter of requests to the [Authorize endpoint]to silently redirect to sign-in with the + // associated IdP. Identifiers in a domain format also enable the use of [email-address matching with SAML providers]. + // + // [Authorize endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html + // [email-address matching with SAML providers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managing-saml-idp-naming.html + IdpIdentifiers []string + + noSmithyDocumentSerde +} + +type CreateIdentityProviderOutput struct { + + // The details of the new user pool IdP. + // + // This member is required. + IdentityProvider *types.IdentityProviderType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateIdentityProviderMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateIdentityProvider{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateIdentityProvider{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateIdentityProvider"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateIdentityProviderValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateIdentityProvider(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateIdentityProvider(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateIdentityProvider", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateManagedLoginBranding.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateManagedLoginBranding.go new file mode 100644 index 00000000..7b97ed44 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateManagedLoginBranding.go @@ -0,0 +1,213 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a new set of branding settings for a user pool style and associates it +// with an app client. This operation is the programmatic option for the creation +// of a new style in the branding designer. +// +// Provides values for UI customization in a Settings JSON object and image files +// in an Assets array. To send the JSON object Document type parameter in Settings +// , you might need to update to the most recent version of your Amazon Web +// Services SDK. To create a new style with default settings, set +// UseCognitoProvidedValues to true and don't provide values for any other options. +// +// This operation has a 2-megabyte request-size limit and include the CSS settings +// and image assets for your app client. Your branding settings might exceed 2MB in +// size. Amazon Cognito doesn't require that you pass all parameters in one request +// and preserves existing style settings that you don't specify. If your request is +// larger than 2MB, separate it into multiple requests, each with a size smaller +// than the limit. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateManagedLoginBranding(ctx context.Context, params *CreateManagedLoginBrandingInput, optFns ...func(*Options)) (*CreateManagedLoginBrandingOutput, error) { + if params == nil { + params = &CreateManagedLoginBrandingInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateManagedLoginBranding", params, optFns, c.addOperationCreateManagedLoginBrandingMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateManagedLoginBrandingOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateManagedLoginBrandingInput struct { + + // The app client that you want to create the branding style for. Each style is + // linked to an app client until you delete it. + // + // This member is required. + ClientId *string + + // The ID of the user pool where you want to create a new branding style. + // + // This member is required. + UserPoolId *string + + // An array of image files that you want to apply to functions like backgrounds, + // logos, and icons. Each object must also indicate whether it is for dark mode, + // light mode, or browser-adaptive mode. + Assets []types.AssetType + + // A JSON file, encoded as a Document type, with the the settings that you want to + // apply to your style. + Settings document.Interface + + // When true, applies the default branding style options. These default options + // are managed by Amazon Cognito. You can modify them later in the branding + // designer. + // + // When you specify true for this option, you must also omit values for Settings + // and Assets in the request. + UseCognitoProvidedValues bool + + noSmithyDocumentSerde +} + +type CreateManagedLoginBrandingOutput struct { + + // The details of the branding style that you created. + ManagedLoginBranding *types.ManagedLoginBrandingType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateManagedLoginBrandingMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateManagedLoginBranding"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateManagedLoginBrandingValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateManagedLoginBranding(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateManagedLoginBranding(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateManagedLoginBranding", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateResourceServer.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateResourceServer.go new file mode 100644 index 00000000..a043c1fc --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateResourceServer.go @@ -0,0 +1,201 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a new OAuth2.0 resource server and defines custom scopes within it. +// Resource servers are associated with custom scopes and machine-to-machine (M2M) +// authorization. For more information, see [Access control with resource servers]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Access control with resource servers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateResourceServer(ctx context.Context, params *CreateResourceServerInput, optFns ...func(*Options)) (*CreateResourceServerOutput, error) { + if params == nil { + params = &CreateResourceServerInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateResourceServer", params, optFns, c.addOperationCreateResourceServerMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateResourceServerOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateResourceServerInput struct { + + // A unique resource server identifier for the resource server. The identifier can + // be an API friendly name like solar-system-data . You can also set an API URL + // like https://solar-system-data-api.example.com as your identifier. + // + // Amazon Cognito represents scopes in the access token in the format + // $resource-server-identifier/$scope . Longer scope-identifier strings increase + // the size of your access tokens. + // + // This member is required. + Identifier *string + + // A friendly name for the resource server. + // + // This member is required. + Name *string + + // The ID of the user pool where you want to create a resource server. + // + // This member is required. + UserPoolId *string + + // A list of custom scopes. Each scope is a key-value map with the keys ScopeName + // and ScopeDescription . The name of a custom scope is a combination of ScopeName + // and the resource server Name in this request, for example + // MyResourceServerName/MyScopeName . + Scopes []types.ResourceServerScopeType + + noSmithyDocumentSerde +} + +type CreateResourceServerOutput struct { + + // The details of the new resource server. + // + // This member is required. + ResourceServer *types.ResourceServerType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateResourceServerMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateResourceServer{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateResourceServer{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateResourceServer"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateResourceServerValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateResourceServer(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateResourceServer(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateResourceServer", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserImportJob.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserImportJob.go new file mode 100644 index 00000000..ae43bcdb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserImportJob.go @@ -0,0 +1,191 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a user import job. You can import users into user pools from a +// comma-separated values (CSV) file without adding Amazon Cognito MAU costs to +// your Amazon Web Services bill. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateUserImportJob(ctx context.Context, params *CreateUserImportJobInput, optFns ...func(*Options)) (*CreateUserImportJobOutput, error) { + if params == nil { + params = &CreateUserImportJobInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateUserImportJob", params, optFns, c.addOperationCreateUserImportJobMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateUserImportJobOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to create the user import job. +type CreateUserImportJobInput struct { + + // You must specify an IAM role that has permission to log import-job results to + // Amazon CloudWatch Logs. This parameter is the ARN of that role. + // + // This member is required. + CloudWatchLogsRoleArn *string + + // A friendly name for the user import job. + // + // This member is required. + JobName *string + + // The ID of the user pool that you want to import users into. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to create the user +// import job. +type CreateUserImportJobOutput struct { + + // The details of the user import job. Includes logging destination, status, and + // the Amazon S3 pre-signed URL for CSV upload. + UserImportJob *types.UserImportJobType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateUserImportJobMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateUserImportJob{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateUserImportJob{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateUserImportJob"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateUserImportJobValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateUserImportJob(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateUserImportJob(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateUserImportJob", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPool.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPool.go new file mode 100644 index 00000000..cac2d860 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPool.go @@ -0,0 +1,374 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates a new Amazon Cognito user pool. This operation sets basic and advanced +// configuration options. +// +// If you don't provide a value for an attribute, Amazon Cognito sets it to its +// default value. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) CreateUserPool(ctx context.Context, params *CreateUserPoolInput, optFns ...func(*Options)) (*CreateUserPoolOutput, error) { + if params == nil { + params = &CreateUserPoolInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateUserPool", params, optFns, c.addOperationCreateUserPoolMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateUserPoolOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to create a user pool. +type CreateUserPoolInput struct { + + // A friendly name for your user pool. + // + // This member is required. + PoolName *string + + // The available verified method a user can use to recover their password when + // they call ForgotPassword . You can use this setting to define a preferred method + // when a user has more than one method available. With this setting, SMS doesn't + // qualify for a valid password recovery mechanism if the user also has SMS + // multi-factor authentication (MFA) activated. Email MFA is also disqualifying for + // account recovery with email. In the absence of this setting, Amazon Cognito uses + // the legacy behavior to determine the recovery method where SMS is preferred over + // email. + // + // As a best practice, configure both verified_email and verified_phone_number , + // with one having a higher priority than the other. + AccountRecoverySetting *types.AccountRecoverySettingType + + // The configuration for administrative creation of users. Includes the template + // for the invitation message for new users, the duration of temporary passwords, + // and permitting self-service sign-up. + AdminCreateUserConfig *types.AdminCreateUserConfigType + + // Attributes supported as an alias for this user pool. For more information about + // alias attributes, see [Customizing sign-in attributes]. + // + // [Customizing sign-in attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases + AliasAttributes []types.AliasAttributeType + + // The attributes that you want your user pool to automatically verify. For more + // information, see [Verifying contact information at sign-up]. + // + // [Verifying contact information at sign-up]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#allowing-users-to-sign-up-and-confirm-themselves + AutoVerifiedAttributes []types.VerifiedAttributeType + + // When active, DeletionProtection prevents accidental deletion of your user pool. + // Before you can delete a user pool that you have protected against deletion, you + // must deactivate this feature. + // + // When you try to delete a protected user pool in a DeleteUserPool API request, + // Amazon Cognito returns an InvalidParameterException error. To delete a + // protected user pool, send a new DeleteUserPool request after you deactivate + // deletion protection in an UpdateUserPool API request. + DeletionProtection types.DeletionProtectionType + + // The device-remembering configuration for a user pool. Device remembering or + // device tracking is a "Remember me on this device" option for user pools that + // perform authentication with the device key of a trusted device in the back end, + // instead of a user-provided MFA code. For more information about device + // authentication, see [Working with user devices in your user pool]. A null value indicates that you have deactivated device + // remembering in your user pool. + // + // When you provide a value for any DeviceConfiguration field, you activate the + // Amazon Cognito device-remembering feature. For more information, see [Working with devices]. + // + // [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + // [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + DeviceConfiguration *types.DeviceConfigurationType + + // The email configuration of your user pool. The email configuration type sets + // your preferred sending method, Amazon Web Services Region, and sender for + // messages from your user pool. + EmailConfiguration *types.EmailConfigurationType + + // This parameter is no longer used. + EmailVerificationMessage *string + + // This parameter is no longer used. + EmailVerificationSubject *string + + // A collection of user pool Lambda triggers. Amazon Cognito invokes triggers at + // several possible stages of authentication operations. Triggers can modify the + // outcome of the operations that invoked them. + LambdaConfig *types.LambdaConfigType + + // Sets multi-factor authentication (MFA) to be on, off, or optional. When ON , all + // users must set up MFA before they can sign in. When OPTIONAL , your application + // must make a client-side determination of whether a user wants to register an MFA + // device. For user pools with adaptive authentication with threat protection, + // choose OPTIONAL . + // + // When MfaConfiguration is OPTIONAL , managed login doesn't automatically prompt + // users to set up MFA. Amazon Cognito generates MFA prompts in API responses and + // in managed login for users who have chosen and configured a preferred MFA + // factor. + MfaConfiguration types.UserPoolMfaType + + // The password policy and sign-in policy in the user pool. The password policy + // sets options like password complexity requirements and password history. The + // sign-in policy sets the options available to applications in [choice-based authentication]. + // + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + Policies *types.UserPoolPolicyType + + // An array of attributes for the new user pool. You can add custom attributes and + // modify the properties of default attributes. The specifications in this + // parameter set the required attributes in your user pool. For more information, + // see [Working with user attributes]. + // + // [Working with user attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html + Schema []types.SchemaAttributeType + + // The contents of the SMS message that your user pool sends to users in SMS OTP + // and MFA authentication. + SmsAuthenticationMessage *string + + // The settings for your Amazon Cognito user pool to send SMS messages with Amazon + // Simple Notification Service. To send SMS messages with Amazon SNS in the Amazon + // Web Services Region that you want, the Amazon Cognito user pool uses an Identity + // and Access Management (IAM) role in your Amazon Web Services account. For more + // information see [SMS message settings]. + // + // [SMS message settings]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html + SmsConfiguration *types.SmsConfigurationType + + // This parameter is no longer used. + SmsVerificationMessage *string + + // The settings for updates to user attributes. These settings include the + // property AttributesRequireVerificationBeforeUpdate , a user-pool setting that + // tells Amazon Cognito how to handle changes to the value of your users' email + // address and phone number attributes. For more information, see [Verifying updates to email addresses and phone numbers]. + // + // [Verifying updates to email addresses and phone numbers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html#user-pool-settings-verifications-verify-attribute-updates + UserAttributeUpdateSettings *types.UserAttributeUpdateSettingsType + + // Contains settings for activation of threat protection, including the operating + // mode and additional authentication types. To log user security information but + // take no action, set to AUDIT . To configure automatic security responses to + // potentially unwanted traffic to your user pool, set to ENFORCED . + // + // For more information, see [Adding advanced security to a user pool]. To activate this setting, your user pool must be on + // the [Plus tier]. + // + // [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html + // [Adding advanced security to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-advanced-security.html + UserPoolAddOns *types.UserPoolAddOnsType + + // The tag keys and values to assign to the user pool. A tag is a label that you + // can use to categorize and manage user pools in different ways, such as by + // purpose, owner, environment, or other criteria. + UserPoolTags map[string]string + + // The user pool [feature plan], or tier. This parameter determines the eligibility of the user + // pool for features like managed login, access-token customization, and threat + // protection. Defaults to ESSENTIALS . + // + // [feature plan]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sign-in-feature-plans.html + UserPoolTier types.UserPoolTierType + + // Specifies whether a user can use an email address or phone number as a username + // when they sign up. For more information, see [Customizing sign-in attributes]. + // + // [Customizing sign-in attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases + UsernameAttributes []types.UsernameAttributeType + + // Sets the case sensitivity option for sign-in usernames. When CaseSensitive is + // false (case insensitive), users can sign in with any combination of capital and + // lowercase letters. For example, username , USERNAME , or UserName , or for + // email, email@example.com or EMaiL@eXamplE.Com . For most use cases, set case + // sensitivity to false as a best practice. When usernames and email addresses are + // case insensitive, Amazon Cognito treats any variation in case as the same user, + // and prevents a case variation from being assigned to the same attribute for a + // different user. + // + // When CaseSensitive is true (case sensitive), Amazon Cognito interprets USERNAME + // and UserName as distinct users. + // + // This configuration is immutable after you set it. + UsernameConfiguration *types.UsernameConfigurationType + + // The template for the verification message that your user pool delivers to users + // who set an email address or phone number attribute. + // + // Set the email message type that corresponds to your DefaultEmailOption + // selection. For CONFIRM_WITH_LINK , specify an EmailMessageByLink and leave + // EmailMessage blank. For CONFIRM_WITH_CODE , specify an EmailMessage and leave + // EmailMessageByLink blank. When you supply both parameters with either choice, + // Amazon Cognito returns an error. + VerificationMessageTemplate *types.VerificationMessageTemplateType + + noSmithyDocumentSerde +} + +// Represents the response from the server for the request to create a user pool. +type CreateUserPoolOutput struct { + + // The details of the created user pool. + UserPool *types.UserPoolType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateUserPoolMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateUserPool{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateUserPool{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateUserPool"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateUserPoolValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateUserPool(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateUserPool(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateUserPool", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolClient.go new file mode 100644 index 00000000..e650e546 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolClient.go @@ -0,0 +1,484 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Creates an app client in a user pool. This operation sets basic and advanced +// configuration options. +// +// Unlike app clients created in the console, Amazon Cognito doesn't automatically +// assign a branding style to app clients that you configure with this API +// operation. Managed login and classic hosted UI pages aren't available for your +// client until after you apply a branding style. +// +// If you don't provide a value for an attribute, Amazon Cognito sets it to its +// default value. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateUserPoolClient(ctx context.Context, params *CreateUserPoolClientInput, optFns ...func(*Options)) (*CreateUserPoolClientOutput, error) { + if params == nil { + params = &CreateUserPoolClientInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateUserPoolClient", params, optFns, c.addOperationCreateUserPoolClientMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateUserPoolClientOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to create a user pool client. +type CreateUserPoolClientInput struct { + + // A friendly name for the app client that you want to create. + // + // This member is required. + ClientName *string + + // The ID of the user pool where you want to create an app client. + // + // This member is required. + UserPoolId *string + + // The access token time limit. After this limit expires, your user can't use + // their access token. To specify the time unit for AccessTokenValidity as seconds + // , minutes , hours , or days , set a TokenValidityUnits value in your API + // request. + // + // For example, when you set AccessTokenValidity to 10 and TokenValidityUnits to + // hours , your user can authorize access with their access token for 10 hours. + // + // The default time unit for AccessTokenValidity in an API request is hours. Valid + // range is displayed below in seconds. + // + // If you don't specify otherwise in the configuration of your app client, your + // access tokens are valid for one hour. + AccessTokenValidity *int32 + + // The OAuth grant types that you want your app client to generate for clients in + // managed login authentication. To create an app client that generates client + // credentials grants, you must add client_credentials as the only allowed OAuth + // flow. + // + // code Use a code grant flow, which provides an authorization code as the + // response. This code can be exchanged for access tokens with the /oauth2/token + // endpoint. + // + // implicit Issue the access token, and the ID token when scopes like openid and + // profile are requested, directly to your user. + // + // client_credentials Issue the access token from the /oauth2/token endpoint + // directly to a non-person user, authorized by a combination of the client ID and + // client secret. + AllowedOAuthFlows []types.OAuthFlowType + + // Set to true to use OAuth 2.0 authorization server features in your app client. + // + // This parameter must have a value of true before you can configure the following + // features in your app client. + // + // - CallBackURLs : Callback URLs. + // + // - LogoutURLs : Sign-out redirect URLs. + // + // - AllowedOAuthScopes : OAuth 2.0 scopes. + // + // - AllowedOAuthFlows : Support for authorization code, implicit, and client + // credentials OAuth 2.0 grants. + // + // To use authorization server features, configure one of these features in the + // Amazon Cognito console or set AllowedOAuthFlowsUserPoolClient to true in a + // CreateUserPoolClient or UpdateUserPoolClient API request. If you don't set a + // value for AllowedOAuthFlowsUserPoolClient in a request with the CLI or SDKs, it + // defaults to false . When false , only SDK-based API sign-in is permitted. + AllowedOAuthFlowsUserPoolClient bool + + // The OAuth, OpenID Connect (OIDC), and custom scopes that you want to permit + // your app client to authorize access with. Scopes govern access control to user + // pool self-service API operations, user data from the userInfo endpoint, and + // third-party APIs. Scope values include phone , email , openid , and profile . + // The aws.cognito.signin.user.admin scope authorizes user self-service + // operations. Custom scopes with resource servers authorize access to external + // APIs. + AllowedOAuthScopes []string + + // The user pool analytics configuration for collecting metrics and sending them + // to your Amazon Pinpoint campaign. + // + // In Amazon Web Services Regions where Amazon Pinpoint isn't available, user + // pools might not have access to analytics or might be configurable with campaigns + // in the US East (N. Virginia) Region. For more information, see [Using Amazon Pinpoint analytics]. + // + // [Using Amazon Pinpoint analytics]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html + AnalyticsConfiguration *types.AnalyticsConfigurationType + + // Amazon Cognito creates a session token for each API request in an + // authentication flow. AuthSessionValidity is the duration, in minutes, of that + // session token. Your user pool native user must respond to each authentication + // challenge before the session expires. + AuthSessionValidity *int32 + + // A list of allowed redirect, or callback, URLs for managed login authentication. + // These URLs are the paths where you want to send your users' browsers after they + // complete authentication with managed login or a third-party IdP. Typically, + // callback URLs are the home of an application that uses OAuth or OIDC libraries + // to process authentication outcomes. + // + // A redirect URI must meet the following requirements: + // + // - Be an absolute URI. + // + // - Be registered with the authorization server. Amazon Cognito doesn't accept + // authorization requests with redirect_uri values that aren't in the list of + // CallbackURLs that you provide in this parameter. + // + // - Not include a fragment component. + // + // See [OAuth 2.0 - Redirection Endpoint]. + // + // Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing + // purposes only. + // + // App callback URLs such as myapp://example are also supported. + // + // [OAuth 2.0 - Redirection Endpoint]: https://tools.ietf.org/html/rfc6749#section-3.1.2 + CallbackURLs []string + + // The default redirect URI. In app clients with one assigned IdP, replaces + // redirect_uri in authentication requests. Must be in the CallbackURLs list. + DefaultRedirectURI *string + + // When true , your application can include additional UserContextData in + // authentication requests. This data includes the IP address, and contributes to + // analysis by threat protection features. For more information about propagation + // of user context data, see [Adding session data to API requests]. If you don’t include this parameter, you can't send + // the source IP address to Amazon Cognito threat protection features. You can only + // activate EnablePropagateAdditionalUserContextData in an app client that has a + // client secret. + // + // [Adding session data to API requests]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-device-fingerprint + EnablePropagateAdditionalUserContextData *bool + + // Activates or deactivates [token revocation] in the target app client. + // + // If you don't include this parameter, token revocation is automatically + // activated for the new user pool client. + // + // [token revocation]: https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html + EnableTokenRevocation *bool + + // The [authentication flows] that you want your user pool client to support. For each app client in + // your user pool, you can sign in your users with any combination of one or more + // flows, including with a user name and Secure Remote Password (SRP), a user name + // and password, or a custom authentication process that you define with Lambda + // functions. + // + // If you don't specify a value for ExplicitAuthFlows , your app client supports + // ALLOW_REFRESH_TOKEN_AUTH , ALLOW_USER_SRP_AUTH , and ALLOW_CUSTOM_AUTH . + // + // The values for authentication flow options include the following. + // + // - ALLOW_USER_AUTH : Enable selection-based sign-in with USER_AUTH . This + // setting covers username-password, secure remote password (SRP), passwordless, + // and passkey authentication. This authentiation flow can do username-password and + // SRP authentication without other ExplicitAuthFlows permitting them. For + // example users can complete an SRP challenge through USER_AUTH without the flow + // USER_SRP_AUTH being active for the app client. This flow doesn't include + // CUSTOM_AUTH . + // + // To activate this setting, your user pool must be in the [Essentials tier]or higher. + // + // - ALLOW_ADMIN_USER_PASSWORD_AUTH : Enable admin based user password + // authentication flow ADMIN_USER_PASSWORD_AUTH . This setting replaces the + // ADMIN_NO_SRP_AUTH setting. With this authentication flow, your app passes a + // user name and password to Amazon Cognito in the request, instead of using the + // Secure Remote Password (SRP) protocol to securely transmit the password. + // + // - ALLOW_CUSTOM_AUTH : Enable Lambda trigger based authentication. + // + // - ALLOW_USER_PASSWORD_AUTH : Enable user password-based authentication. In + // this flow, Amazon Cognito receives the password in the request instead of using + // the SRP protocol to verify passwords. + // + // - ALLOW_USER_SRP_AUTH : Enable SRP-based authentication. + // + // - ALLOW_REFRESH_TOKEN_AUTH : Enable authflow to refresh tokens. + // + // In some environments, you will see the values ADMIN_NO_SRP_AUTH , + // CUSTOM_AUTH_FLOW_ONLY , or USER_PASSWORD_AUTH . You can't assign these legacy + // ExplicitAuthFlows values to user pool clients at the same time as values that + // begin with ALLOW_ , like ALLOW_USER_SRP_AUTH . + // + // [authentication flows]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + ExplicitAuthFlows []types.ExplicitAuthFlowsType + + // When true , generates a client secret for the app client. Client secrets are + // used with server-side and machine-to-machine applications. Client secrets are + // automatically generated; you can't specify a secret value. For more information, + // see [App client types]. + // + // [App client types]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html#user-pool-settings-client-app-client-types + GenerateSecret bool + + // The ID token time limit. After this limit expires, your user can't use their ID + // token. To specify the time unit for IdTokenValidity as seconds , minutes , hours + // , or days , set a TokenValidityUnits value in your API request. + // + // For example, when you set IdTokenValidity as 10 and TokenValidityUnits as hours + // , your user can authenticate their session with their ID token for 10 hours. + // + // The default time unit for IdTokenValidity in an API request is hours. Valid + // range is displayed below in seconds. + // + // If you don't specify otherwise in the configuration of your app client, your ID + // tokens are valid for one hour. + IdTokenValidity *int32 + + // A list of allowed logout URLs for managed login authentication. When you pass + // logout_uri and client_id parameters to /logout , Amazon Cognito signs out your + // user and redirects them to the logout URL. This parameter describes the URLs + // that you want to be the permitted targets of logout_uri . A typical use of these + // URLs is when a user selects "Sign out" and you redirect them to your public + // homepage. For more information, see [Logout endpoint]. + // + // [Logout endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html + LogoutURLs []string + + // When ENABLED , suppresses messages that might indicate a valid user exists when + // someone attempts sign-in. This parameters sets your preference for the errors + // and responses that you want Amazon Cognito APIs to return during authentication, + // account confirmation, and password recovery when the user doesn't exist in the + // user pool. When set to ENABLED and the user doesn't exist, authentication + // returns an error indicating either the username or password was incorrect. + // Account confirmation and password recovery return a response indicating a code + // was sent to a simulated destination. When set to LEGACY , those APIs return a + // UserNotFoundException exception if the user doesn't exist in the user pool. + // + // Defaults to LEGACY . + PreventUserExistenceErrors types.PreventUserExistenceErrorTypes + + // The list of user attributes that you want your app client to have read access + // to. After your user authenticates in your app, their access token authorizes + // them to read their own attribute value for any attribute in this list. + // + // When you don't specify the ReadAttributes for your app client, your app can + // read the values of email_verified , phone_number_verified , and the standard + // attributes of your user pool. When your user pool app client has read access to + // these default attributes, ReadAttributes doesn't return any information. Amazon + // Cognito only populates ReadAttributes in the API response if you have specified + // your own custom set of read attributes. + ReadAttributes []string + + // The configuration of your app client for refresh token rotation. When enabled, + // your app client issues new ID, access, and refresh tokens when users renew their + // sessions with refresh tokens. When disabled, token refresh issues only ID and + // access tokens. + RefreshTokenRotation *types.RefreshTokenRotationType + + // The refresh token time limit. After this limit expires, your user can't use + // their refresh token. To specify the time unit for RefreshTokenValidity as + // seconds , minutes , hours , or days , set a TokenValidityUnits value in your + // API request. + // + // For example, when you set RefreshTokenValidity as 10 and TokenValidityUnits as + // days , your user can refresh their session and retrieve new access and ID tokens + // for 10 days. + // + // The default time unit for RefreshTokenValidity in an API request is days. You + // can't set RefreshTokenValidity to 0. If you do, Amazon Cognito overrides the + // value with the default value of 30 days. Valid range is displayed below in + // seconds. + // + // If you don't specify otherwise in the configuration of your app client, your + // refresh tokens are valid for 30 days. + RefreshTokenValidity int32 + + // A list of provider names for the identity providers (IdPs) that are supported + // on this client. The following are supported: COGNITO , Facebook , Google , + // SignInWithApple , and LoginWithAmazon . You can also specify the names that you + // configured for the SAML and OIDC IdPs in your user pool, for example MySAMLIdP + // or MyOIDCIdP . + // + // This parameter sets the IdPs that [managed login] will display on the login page for your app + // client. The removal of COGNITO from this list doesn't prevent authentication + // operations for local users with the user pools API in an Amazon Web Services + // SDK. The only way to prevent SDK-based authentication is to block access with a [WAF rule] + // . + // + // [WAF rule]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-waf.html + // [managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html + SupportedIdentityProviders []string + + // The units that validity times are represented in. The default unit for refresh + // tokens is days, and the default for ID and access tokens are hours. + TokenValidityUnits *types.TokenValidityUnitsType + + // The list of user attributes that you want your app client to have write access + // to. After your user authenticates in your app, their access token authorizes + // them to set or modify their own attribute value for any attribute in this list. + // + // When you don't specify the WriteAttributes for your app client, your app can + // write the values of the Standard attributes of your user pool. When your user + // pool has write access to these default attributes, WriteAttributes doesn't + // return any information. Amazon Cognito only populates WriteAttributes in the + // API response if you have specified your own custom set of write attributes. + // + // If your app client allows users to sign in through an IdP, this array must + // include all attributes that you have mapped to IdP attributes. Amazon Cognito + // updates mapped attributes when users sign in to your application through an IdP. + // If your app client does not have write access to a mapped attribute, Amazon + // Cognito throws an error when it tries to update the attribute. For more + // information, see [Specifying IdP Attribute Mappings for Your user pool]. + // + // [Specifying IdP Attribute Mappings for Your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html + WriteAttributes []string + + noSmithyDocumentSerde +} + +// Represents the response from the server to create a user pool client. +type CreateUserPoolClientOutput struct { + + // The details of the new app client. + UserPoolClient *types.UserPoolClientType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateUserPoolClientMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateUserPoolClient{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateUserPoolClient{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateUserPoolClient"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateUserPoolClientValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateUserPoolClient(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateUserPoolClient(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateUserPoolClient", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolDomain.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolDomain.go new file mode 100644 index 00000000..145c6631 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_CreateUserPoolDomain.go @@ -0,0 +1,229 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// A user pool domain hosts managed login, an authorization server and web server +// for authentication in your application. This operation creates a new user pool +// prefix domain or custom domain and sets the managed login branding version. Set +// the branding version to 1 for hosted UI (classic) or 2 for managed login. When +// you choose a custom domain, you must provide an SSL certificate in the US East +// (N. Virginia) Amazon Web Services Region in your request. +// +// Your prefix domain might take up to one minute to take effect. Your custom +// domain is online within five minutes, but it can take up to one hour to +// distribute your SSL certificate. +// +// For more information about adding a custom domain to your user pool, see [Configuring a user pool domain]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Configuring a user pool domain]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-add-custom-domain.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) CreateUserPoolDomain(ctx context.Context, params *CreateUserPoolDomainInput, optFns ...func(*Options)) (*CreateUserPoolDomainOutput, error) { + if params == nil { + params = &CreateUserPoolDomainInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateUserPoolDomain", params, optFns, c.addOperationCreateUserPoolDomainMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateUserPoolDomainOutput) + out.ResultMetadata = metadata + return out, nil +} + +type CreateUserPoolDomainInput struct { + + // The domain string. For custom domains, this is the fully-qualified domain name, + // such as auth.example.com . For prefix domains, this is the prefix alone, such as + // myprefix . A prefix value of myprefix for a user pool in the us-east-1 Region + // results in a domain of myprefix.auth.us-east-1.amazoncognito.com . + // + // This member is required. + Domain *string + + // The ID of the user pool where you want to add a domain. + // + // This member is required. + UserPoolId *string + + // The configuration for a custom domain. Configures your domain with an + // Certificate Manager certificate in the us-east-1 Region. + // + // Provide this parameter only if you want to use a [custom domain] for your user pool. + // Otherwise, you can omit this parameter and use a [prefix domain]instead. + // + // When you create a custom domain, the passkey RP ID defaults to the custom + // domain. If you had a prefix domain active, this will cause passkey integration + // for your prefix domain to stop working due to a mismatch in RP ID. To keep the + // prefix domain passkey integration working, you can explicitly set RP ID to the + // prefix domain. + // + // [custom domain]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-add-custom-domain.html + // [prefix domain]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain-prefix.html + CustomDomainConfig *types.CustomDomainConfigType + + // The version of managed login branding that you want to apply to your domain. A + // value of 1 indicates hosted UI (classic) and a version of 2 indicates managed + // login. + // + // Managed login requires that your user pool be configured for any [feature plan] other than + // Lite . + // + // [feature plan]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sign-in-feature-plans.html + ManagedLoginVersion *int32 + + noSmithyDocumentSerde +} + +type CreateUserPoolDomainOutput struct { + + // The fully-qualified domain name (FQDN) of the Amazon CloudFront distribution + // that hosts your managed login or classic hosted UI pages. Your domain-name + // authority must have an alias record that points requests for your custom domain + // to this FQDN. Amazon Cognito returns this value if you set a custom domain with + // CustomDomainConfig . If you set an Amazon Cognito prefix domain, this parameter + // returns null. + CloudFrontDomain *string + + // The version of managed login branding applied your domain. A value of 1 + // indicates hosted UI (classic) and a version of 2 indicates managed login. + ManagedLoginVersion *int32 + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateUserPoolDomainMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateUserPoolDomain"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateUserPoolDomainValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateUserPoolDomain(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateUserPoolDomain(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateUserPoolDomain", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteGroup.go new file mode 100644 index 00000000..0cee2743 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteGroup.go @@ -0,0 +1,178 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a group from the specified user pool. When you delete a group, that +// group no longer contributes to users' cognito:preferred_group or cognito:groups +// claims, and no longer influence access-control decision that are based on group +// membership. For more information about user pool groups, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DeleteGroup(ctx context.Context, params *DeleteGroupInput, optFns ...func(*Options)) (*DeleteGroupOutput, error) { + if params == nil { + params = &DeleteGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteGroup", params, optFns, c.addOperationDeleteGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteGroupInput struct { + + // The name of the group that you want to delete. + // + // This member is required. + GroupName *string + + // The ID of the user pool where you want to delete the group. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteGroupOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteIdentityProvider.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteIdentityProvider.go new file mode 100644 index 00000000..8db2a757 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteIdentityProvider.go @@ -0,0 +1,177 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a user pool identity provider (IdP). After you delete an IdP, users can +// no longer sign in to your user pool through that IdP. For more information about +// user pool IdPs, see [Third-party IdP sign-in]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Third-party IdP sign-in]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DeleteIdentityProvider(ctx context.Context, params *DeleteIdentityProviderInput, optFns ...func(*Options)) (*DeleteIdentityProviderOutput, error) { + if params == nil { + params = &DeleteIdentityProviderInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteIdentityProvider", params, optFns, c.addOperationDeleteIdentityProviderMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteIdentityProviderOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteIdentityProviderInput struct { + + // The name of the IdP that you want to delete. + // + // This member is required. + ProviderName *string + + // The ID of the user pool where you want to delete the identity provider. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteIdentityProviderOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteIdentityProviderMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteIdentityProvider{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteIdentityProvider{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteIdentityProvider"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteIdentityProviderValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteIdentityProvider(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteIdentityProvider(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteIdentityProvider", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteManagedLoginBranding.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteManagedLoginBranding.go new file mode 100644 index 00000000..388f2144 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteManagedLoginBranding.go @@ -0,0 +1,178 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a managed login branding style. When you delete a style, you delete the +// branding association for an app client. When an app client doesn't have a style +// assigned, your managed login pages for that app client are nonfunctional until +// you create a new style or switch the domain branding version. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DeleteManagedLoginBranding(ctx context.Context, params *DeleteManagedLoginBrandingInput, optFns ...func(*Options)) (*DeleteManagedLoginBrandingOutput, error) { + if params == nil { + params = &DeleteManagedLoginBrandingInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteManagedLoginBranding", params, optFns, c.addOperationDeleteManagedLoginBrandingMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteManagedLoginBrandingOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteManagedLoginBrandingInput struct { + + // The ID of the managed login branding style that you want to delete. + // + // This member is required. + ManagedLoginBrandingId *string + + // The ID of the user pool that contains the managed login branding style that you + // want to delete. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteManagedLoginBrandingOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteManagedLoginBrandingMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteManagedLoginBranding"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteManagedLoginBrandingValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteManagedLoginBranding(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteManagedLoginBranding(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteManagedLoginBranding", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteResourceServer.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteResourceServer.go new file mode 100644 index 00000000..aa2c1a74 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteResourceServer.go @@ -0,0 +1,180 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a resource server. After you delete a resource server, users can no +// longer generate access tokens with scopes that are associate with that resource +// server. +// +// Resource servers are associated with custom scopes and machine-to-machine (M2M) +// authorization. For more information, see [Access control with resource servers]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Access control with resource servers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DeleteResourceServer(ctx context.Context, params *DeleteResourceServerInput, optFns ...func(*Options)) (*DeleteResourceServerOutput, error) { + if params == nil { + params = &DeleteResourceServerInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteResourceServer", params, optFns, c.addOperationDeleteResourceServerMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteResourceServerOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteResourceServerInput struct { + + // The identifier of the resource server that you want to delete. + // + // This member is required. + Identifier *string + + // The ID of the user pool where you want to delete the resource server. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteResourceServerOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteResourceServerMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteResourceServer{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteResourceServer{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteResourceServer"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteResourceServerValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteResourceServer(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteResourceServer(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteResourceServer", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUser.go new file mode 100644 index 00000000..b997aa83 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUser.go @@ -0,0 +1,166 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes the profile of the currently signed-in user. A deleted user profile can +// no longer be used to sign in and can't be restored. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) DeleteUser(ctx context.Context, params *DeleteUserInput, optFns ...func(*Options)) (*DeleteUserOutput, error) { + if params == nil { + params = &DeleteUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteUser", params, optFns, c.addOperationDeleteUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to delete a user. +type DeleteUserInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + noSmithyDocumentSerde +} + +type DeleteUserOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserAttributes.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserAttributes.go new file mode 100644 index 00000000..0d8d2b08 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserAttributes.go @@ -0,0 +1,176 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes attributes from the currently signed-in user. For example, your +// application can submit a request to this operation when a user wants to remove +// their birthdate attribute value. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) DeleteUserAttributes(ctx context.Context, params *DeleteUserAttributesInput, optFns ...func(*Options)) (*DeleteUserAttributesOutput, error) { + if params == nil { + params = &DeleteUserAttributesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteUserAttributes", params, optFns, c.addOperationDeleteUserAttributesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteUserAttributesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to delete user attributes. +type DeleteUserAttributesInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // An array of strings representing the user attribute names you want to delete. + // + // For custom attributes, you must prepend the custom: prefix to the attribute + // name, for example custom:department . + // + // This member is required. + UserAttributeNames []string + + noSmithyDocumentSerde +} + +// Represents the response from the server to delete user attributes. +type DeleteUserAttributesOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteUserAttributesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteUserAttributes{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteUserAttributes{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteUserAttributes"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteUserAttributesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteUserAttributes(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteUserAttributes(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteUserAttributes", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPool.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPool.go new file mode 100644 index 00000000..f1c711e8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPool.go @@ -0,0 +1,167 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a user pool. After you delete a user pool, users can no longer sign in +// to any associated applications. +// +// When you delete a user pool, it's no longer visible or operational in your +// Amazon Web Services account. Amazon Cognito retains deleted user pools in an +// inactive state for 14 days, then begins a cleanup process that fully removes +// them from Amazon Web Services systems. In case of accidental deletion, contact +// Amazon Web ServicesSupport within 14 days for restoration assistance. +// +// Amazon Cognito begins full deletion of all resources from deleted user pools +// after 14 days. In the case of large user pools, the cleanup process might take +// significant additional time before all user data is permanently deleted. +func (c *Client) DeleteUserPool(ctx context.Context, params *DeleteUserPoolInput, optFns ...func(*Options)) (*DeleteUserPoolOutput, error) { + if params == nil { + params = &DeleteUserPoolInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteUserPool", params, optFns, c.addOperationDeleteUserPoolMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteUserPoolOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to delete a user pool. +type DeleteUserPoolInput struct { + + // The ID of the user pool that you want to delete. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteUserPoolOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteUserPoolMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteUserPool{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteUserPool{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteUserPool"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteUserPoolValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteUserPool(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteUserPool(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteUserPool", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolClient.go new file mode 100644 index 00000000..3e3df0fb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolClient.go @@ -0,0 +1,162 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a user pool app client. After you delete an app client, users can no +// longer sign in to the associated application. +func (c *Client) DeleteUserPoolClient(ctx context.Context, params *DeleteUserPoolClientInput, optFns ...func(*Options)) (*DeleteUserPoolClientOutput, error) { + if params == nil { + params = &DeleteUserPoolClientInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteUserPoolClient", params, optFns, c.addOperationDeleteUserPoolClientMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteUserPoolClientOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to delete a user pool client. +type DeleteUserPoolClientInput struct { + + // The ID of the user pool app client that you want to delete. + // + // This member is required. + ClientId *string + + // The ID of the user pool where you want to delete the client. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteUserPoolClientOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteUserPoolClientMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteUserPoolClient{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteUserPoolClient{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteUserPoolClient"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteUserPoolClientValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteUserPoolClient(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteUserPoolClient(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteUserPoolClient", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolDomain.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolDomain.go new file mode 100644 index 00000000..1ac971b0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteUserPoolDomain.go @@ -0,0 +1,164 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID and domain identifier, deletes a user pool domain. After +// you delete a user pool domain, your managed login pages and authorization server +// are no longer available. +func (c *Client) DeleteUserPoolDomain(ctx context.Context, params *DeleteUserPoolDomainInput, optFns ...func(*Options)) (*DeleteUserPoolDomainOutput, error) { + if params == nil { + params = &DeleteUserPoolDomainInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteUserPoolDomain", params, optFns, c.addOperationDeleteUserPoolDomainMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteUserPoolDomainOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteUserPoolDomainInput struct { + + // The domain that you want to delete. For custom domains, this is the + // fully-qualified domain name like auth.example.com . For Amazon Cognito prefix + // domains, this is the prefix alone, like myprefix . + // + // This member is required. + Domain *string + + // The ID of the user pool where you want to delete the domain. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DeleteUserPoolDomainOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteUserPoolDomainMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteUserPoolDomain"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteUserPoolDomainValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteUserPoolDomain(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteUserPoolDomain(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteUserPoolDomain", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteWebAuthnCredential.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteWebAuthnCredential.go new file mode 100644 index 00000000..5a1596c8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DeleteWebAuthnCredential.go @@ -0,0 +1,170 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Deletes a registered passkey, or WebAuthn, authenticator for the currently +// signed-in user. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) DeleteWebAuthnCredential(ctx context.Context, params *DeleteWebAuthnCredentialInput, optFns ...func(*Options)) (*DeleteWebAuthnCredentialOutput, error) { + if params == nil { + params = &DeleteWebAuthnCredentialInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DeleteWebAuthnCredential", params, optFns, c.addOperationDeleteWebAuthnCredentialMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DeleteWebAuthnCredentialOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DeleteWebAuthnCredentialInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The unique identifier of the passkey that you want to delete. + // + // This member is required. + CredentialId *string + + noSmithyDocumentSerde +} + +type DeleteWebAuthnCredentialOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDeleteWebAuthnCredentialMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteWebAuthnCredential{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteWebAuthnCredential{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteWebAuthnCredential"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDeleteWebAuthnCredentialValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteWebAuthnCredential(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDeleteWebAuthnCredential(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DeleteWebAuthnCredential", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeIdentityProvider.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeIdentityProvider.go new file mode 100644 index 00000000..2d577a84 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeIdentityProvider.go @@ -0,0 +1,168 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID and identity provider (IdP) name, returns details about +// the IdP. +func (c *Client) DescribeIdentityProvider(ctx context.Context, params *DescribeIdentityProviderInput, optFns ...func(*Options)) (*DescribeIdentityProviderOutput, error) { + if params == nil { + params = &DescribeIdentityProviderInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeIdentityProvider", params, optFns, c.addOperationDescribeIdentityProviderMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeIdentityProviderOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeIdentityProviderInput struct { + + // The name of the IdP that you want to describe. + // + // This member is required. + ProviderName *string + + // The ID of the user pool that has the IdP that you want to describe.. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DescribeIdentityProviderOutput struct { + + // The details of the requested IdP. + // + // This member is required. + IdentityProvider *types.IdentityProviderType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeIdentityProviderMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeIdentityProvider{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeIdentityProvider{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeIdentityProvider"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeIdentityProviderValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeIdentityProvider(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeIdentityProvider(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeIdentityProvider", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBranding.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBranding.go new file mode 100644 index 00000000..6bcbbf51 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBranding.go @@ -0,0 +1,173 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given the ID of a managed login branding style, returns detailed information +// about the style. +func (c *Client) DescribeManagedLoginBranding(ctx context.Context, params *DescribeManagedLoginBrandingInput, optFns ...func(*Options)) (*DescribeManagedLoginBrandingOutput, error) { + if params == nil { + params = &DescribeManagedLoginBrandingInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeManagedLoginBranding", params, optFns, c.addOperationDescribeManagedLoginBrandingMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeManagedLoginBrandingOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeManagedLoginBrandingInput struct { + + // The ID of the managed login branding style that you want to get more + // information about. + // + // This member is required. + ManagedLoginBrandingId *string + + // The ID of the user pool that contains the managed login branding style that you + // want to get information about. + // + // This member is required. + UserPoolId *string + + // When true , returns values for branding options that are unchanged from Amazon + // Cognito defaults. When false or when you omit this parameter, returns only + // values that you customized in your branding style. + ReturnMergedResources bool + + noSmithyDocumentSerde +} + +type DescribeManagedLoginBrandingOutput struct { + + // The details of the requested branding style. + ManagedLoginBranding *types.ManagedLoginBrandingType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeManagedLoginBrandingMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeManagedLoginBranding"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeManagedLoginBrandingValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeManagedLoginBranding(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeManagedLoginBranding(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeManagedLoginBranding", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBrandingByClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBrandingByClient.go new file mode 100644 index 00000000..361e59c6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeManagedLoginBrandingByClient.go @@ -0,0 +1,173 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given the ID of a user pool app client, returns detailed information about the +// style assigned to the app client. +func (c *Client) DescribeManagedLoginBrandingByClient(ctx context.Context, params *DescribeManagedLoginBrandingByClientInput, optFns ...func(*Options)) (*DescribeManagedLoginBrandingByClientOutput, error) { + if params == nil { + params = &DescribeManagedLoginBrandingByClientInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeManagedLoginBrandingByClient", params, optFns, c.addOperationDescribeManagedLoginBrandingByClientMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeManagedLoginBrandingByClientOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeManagedLoginBrandingByClientInput struct { + + // The app client that's assigned to the branding style that you want more + // information about. + // + // This member is required. + ClientId *string + + // The ID of the user pool that contains the app client where you want more + // information about the managed login branding style. + // + // This member is required. + UserPoolId *string + + // When true , returns values for branding options that are unchanged from Amazon + // Cognito defaults. When false or when you omit this parameter, returns only + // values that you customized in your branding style. + ReturnMergedResources bool + + noSmithyDocumentSerde +} + +type DescribeManagedLoginBrandingByClientOutput struct { + + // The details of the requested branding style. + ManagedLoginBranding *types.ManagedLoginBrandingType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeManagedLoginBrandingByClientMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeManagedLoginBrandingByClient{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeManagedLoginBrandingByClient{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeManagedLoginBrandingByClient"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeManagedLoginBrandingByClientValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeManagedLoginBrandingByClient(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeManagedLoginBrandingByClient(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeManagedLoginBrandingByClient", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeResourceServer.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeResourceServer.go new file mode 100644 index 00000000..9865b4aa --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeResourceServer.go @@ -0,0 +1,175 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Describes a resource server. For more information about resource servers, see [Access control with resource servers]. +// +// [Access control with resource servers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html +func (c *Client) DescribeResourceServer(ctx context.Context, params *DescribeResourceServerInput, optFns ...func(*Options)) (*DescribeResourceServerOutput, error) { + if params == nil { + params = &DescribeResourceServerInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeResourceServer", params, optFns, c.addOperationDescribeResourceServerMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeResourceServerOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeResourceServerInput struct { + + // A unique resource server identifier for the resource server. The identifier can + // be an API friendly name like solar-system-data . You can also set an API URL + // like https://solar-system-data-api.example.com as your identifier. + // + // Amazon Cognito represents scopes in the access token in the format + // $resource-server-identifier/$scope . Longer scope-identifier strings increase + // the size of your access tokens. + // + // This member is required. + Identifier *string + + // The ID of the user pool that hosts the resource server. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type DescribeResourceServerOutput struct { + + // The details of the requested resource server. + // + // This member is required. + ResourceServer *types.ResourceServerType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeResourceServerMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeResourceServer{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeResourceServer{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeResourceServer"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeResourceServerValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeResourceServer(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeResourceServer(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeResourceServer", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeRiskConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeRiskConfiguration.go new file mode 100644 index 00000000..a6c6ca70 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeRiskConfiguration.go @@ -0,0 +1,178 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given an app client or user pool ID where threat protection is configured, +// describes the risk configuration. This operation returns details about adaptive +// authentication, compromised credentials, and IP-address allow- and denylists. +// For more information about threat protection, see [Threat protection]. +// +// [Threat protection]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-threat-protection.html +func (c *Client) DescribeRiskConfiguration(ctx context.Context, params *DescribeRiskConfigurationInput, optFns ...func(*Options)) (*DescribeRiskConfigurationOutput, error) { + if params == nil { + params = &DescribeRiskConfigurationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeRiskConfiguration", params, optFns, c.addOperationDescribeRiskConfigurationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeRiskConfigurationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeRiskConfigurationInput struct { + + // The ID of the user pool with the risk configuration that you want to inspect. + // You can apply default risk configuration at the user pool level and further + // customize it from user pool defaults at the app-client level. Specify ClientId + // to inspect client-level configuration, or UserPoolId to inspect pool-level + // configuration. + // + // This member is required. + UserPoolId *string + + // The ID of the app client with the risk configuration that you want to inspect. + // You can apply default risk configuration at the user pool level and further + // customize it from user pool defaults at the app-client level. Specify ClientId + // to inspect client-level configuration, or UserPoolId to inspect pool-level + // configuration. + ClientId *string + + noSmithyDocumentSerde +} + +type DescribeRiskConfigurationOutput struct { + + // The details of the requested risk configuration. + // + // This member is required. + RiskConfiguration *types.RiskConfigurationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeRiskConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeRiskConfiguration{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeRiskConfiguration{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeRiskConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeRiskConfigurationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeRiskConfiguration(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeRiskConfiguration(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeRiskConfiguration", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserImportJob.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserImportJob.go new file mode 100644 index 00000000..c49785b7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserImportJob.go @@ -0,0 +1,171 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Describes a user import job. For more information about user CSV import, see [Importing users from a CSV file]. +// +// [Importing users from a CSV file]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html +func (c *Client) DescribeUserImportJob(ctx context.Context, params *DescribeUserImportJobInput, optFns ...func(*Options)) (*DescribeUserImportJobOutput, error) { + if params == nil { + params = &DescribeUserImportJobInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeUserImportJob", params, optFns, c.addOperationDescribeUserImportJobMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeUserImportJobOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to describe the user import job. +type DescribeUserImportJobInput struct { + + // The Id of the user import job that you want to describe. + // + // This member is required. + JobId *string + + // The ID of the user pool that's associated with the import job. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to describe the user +// import job. +type DescribeUserImportJobOutput struct { + + // The details of the user import job. Includes logging destination, status, and + // the Amazon S3 pre-signed URL for CSV upload. + UserImportJob *types.UserImportJobType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeUserImportJobMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeUserImportJob{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeUserImportJob{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeUserImportJob"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeUserImportJobValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeUserImportJob(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeUserImportJob(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeUserImportJob", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPool.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPool.go new file mode 100644 index 00000000..ecf2cdb1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPool.go @@ -0,0 +1,178 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns configuration information. This operation is +// useful when you want to inspect an existing user pool and programmatically +// replicate the configuration to another user pool. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DescribeUserPool(ctx context.Context, params *DescribeUserPoolInput, optFns ...func(*Options)) (*DescribeUserPoolOutput, error) { + if params == nil { + params = &DescribeUserPoolInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeUserPool", params, optFns, c.addOperationDescribeUserPoolMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeUserPoolOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to describe the user pool. +type DescribeUserPoolInput struct { + + // The ID of the user pool you want to describe. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response to describe the user pool. +type DescribeUserPoolOutput struct { + + // The details of the requested user pool. + UserPool *types.UserPoolType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeUserPoolMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeUserPool{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeUserPool{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeUserPool"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeUserPoolValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeUserPool(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeUserPool(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeUserPool", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolClient.go new file mode 100644 index 00000000..49324b59 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolClient.go @@ -0,0 +1,186 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given an app client ID, returns configuration information. This operation is +// useful when you want to inspect an existing app client and programmatically +// replicate the configuration to another app client. For more information about +// app clients, see [App clients]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [App clients]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DescribeUserPoolClient(ctx context.Context, params *DescribeUserPoolClientInput, optFns ...func(*Options)) (*DescribeUserPoolClientOutput, error) { + if params == nil { + params = &DescribeUserPoolClientInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeUserPoolClient", params, optFns, c.addOperationDescribeUserPoolClientMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeUserPoolClientOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to describe a user pool client. +type DescribeUserPoolClientInput struct { + + // The ID of the app client that you want to describe. + // + // This member is required. + ClientId *string + + // The ID of the user pool that contains the app client you want to describe. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server from a request to describe the user +// pool client. +type DescribeUserPoolClientOutput struct { + + // The details of the request app client. + UserPoolClient *types.UserPoolClientType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeUserPoolClientMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeUserPoolClient{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeUserPoolClient{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeUserPoolClient"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeUserPoolClientValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeUserPoolClient(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeUserPoolClient(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeUserPoolClient", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolDomain.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolDomain.go new file mode 100644 index 00000000..28892daa --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_DescribeUserPoolDomain.go @@ -0,0 +1,177 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool domain name, returns information about the domain +// configuration. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) DescribeUserPoolDomain(ctx context.Context, params *DescribeUserPoolDomainInput, optFns ...func(*Options)) (*DescribeUserPoolDomainOutput, error) { + if params == nil { + params = &DescribeUserPoolDomainInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "DescribeUserPoolDomain", params, optFns, c.addOperationDescribeUserPoolDomainMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*DescribeUserPoolDomainOutput) + out.ResultMetadata = metadata + return out, nil +} + +type DescribeUserPoolDomainInput struct { + + // The domain that you want to describe. For custom domains, this is the + // fully-qualified domain name, such as auth.example.com . For Amazon Cognito + // prefix domains, this is the prefix alone, such as auth . + // + // This member is required. + Domain *string + + noSmithyDocumentSerde +} + +type DescribeUserPoolDomainOutput struct { + + // The details of the requested user pool domain. + DomainDescription *types.DomainDescriptionType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationDescribeUserPoolDomainMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeUserPoolDomain"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpDescribeUserPoolDomainValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeUserPoolDomain(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opDescribeUserPoolDomain(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "DescribeUserPoolDomain", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgetDevice.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgetDevice.go new file mode 100644 index 00000000..bd7da50e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgetDevice.go @@ -0,0 +1,171 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a device key, deletes a remembered device as the currently signed-in +// user. For more information about device authentication, see [Working with user devices in your user pool]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +func (c *Client) ForgetDevice(ctx context.Context, params *ForgetDeviceInput, optFns ...func(*Options)) (*ForgetDeviceOutput, error) { + if params == nil { + params = &ForgetDeviceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ForgetDevice", params, optFns, c.addOperationForgetDeviceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ForgetDeviceOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to forget the device. +type ForgetDeviceInput struct { + + // The unique identifier, or device key, of the device that the user wants to + // forget. + // + // This member is required. + DeviceKey *string + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + AccessToken *string + + noSmithyDocumentSerde +} + +type ForgetDeviceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationForgetDeviceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpForgetDevice{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpForgetDevice{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ForgetDevice"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpForgetDeviceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opForgetDevice(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opForgetDevice(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ForgetDevice", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgotPassword.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgotPassword.go new file mode 100644 index 00000000..5070cf36 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ForgotPassword.go @@ -0,0 +1,256 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Sends a password-reset confirmation code for the currently signed-in user. +// +// For the Username parameter, you can use the username or user alias. +// +// If neither a verified phone number nor a verified email exists, Amazon Cognito +// responds with an InvalidParameterException error . If your app client has a +// client secret and you don't provide a SECRET_HASH parameter, this API returns +// NotAuthorizedException . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) ForgotPassword(ctx context.Context, params *ForgotPasswordInput, optFns ...func(*Options)) (*ForgotPasswordOutput, error) { + if params == nil { + params = &ForgotPasswordInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ForgotPassword", params, optFns, c.addOperationForgotPasswordMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ForgotPasswordOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to reset a user's password. +type ForgotPasswordInput struct { + + // The ID of the user pool app client associated with the current signed-in user. + // + // This member is required. + ClientId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the ForgotPassword API action, Amazon Cognito invokes any + // functions that are assigned to the following triggers: pre sign-up, custom + // message, and user migration. When Amazon Cognito invokes any of these functions, + // it passes a JSON payload, which the function receives as input. This payload + // contains a clientMetadata attribute, which provides the data that you assigned + // to the ClientMetadata parameter in your ForgotPassword request. In your function + // code in Lambda, you can process the clientMetadata value to enhance your + // workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // A keyed-hash message authentication code (HMAC) calculated using the secret key + // of a user pool client and username plus the client ID in the message. For more + // information about SecretHash , see [Computing secret hash values]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + SecretHash *string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + noSmithyDocumentSerde +} + +// The response from Amazon Cognito to a request to reset a password. +type ForgotPasswordOutput struct { + + // Information about the phone number or email address that Amazon Cognito sent + // the password-recovery code to. + CodeDeliveryDetails *types.CodeDeliveryDetailsType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationForgotPasswordMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpForgotPassword{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpForgotPassword{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ForgotPassword"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpForgotPasswordValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opForgotPassword(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opForgotPassword(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ForgotPassword", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetCSVHeader.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetCSVHeader.go new file mode 100644 index 00000000..eefba858 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetCSVHeader.go @@ -0,0 +1,188 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, generates a comma-separated value (CSV) list populated +// with available user attributes in the user pool. This list is the header for the +// CSV file that determines the users in a user import job. Save the content of +// CSVHeader in the response as a .csv file and populate it with the usernames and +// attributes of users that you want to import. For more information about CSV user +// import, see [Importing users from a CSV file]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Importing users from a CSV file]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) GetCSVHeader(ctx context.Context, params *GetCSVHeaderInput, optFns ...func(*Options)) (*GetCSVHeaderOutput, error) { + if params == nil { + params = &GetCSVHeaderInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetCSVHeader", params, optFns, c.addOperationGetCSVHeaderMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetCSVHeaderOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to get the header information of the CSV file for the +// user import job. +type GetCSVHeaderInput struct { + + // The ID of the user pool that you want to import users into. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to get the header +// information of the CSV file for the user import job. +type GetCSVHeaderOutput struct { + + // A comma-separated list of attributes from your user pool. Save this output to a + // .csv file and populate it with the attributes of the users that you want to + // import. + CSVHeader []string + + // The ID of the requested user pool. + UserPoolId *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetCSVHeaderMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetCSVHeader{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetCSVHeader{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetCSVHeader"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetCSVHeaderValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetCSVHeader(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetCSVHeader(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetCSVHeader", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetDevice.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetDevice.go new file mode 100644 index 00000000..3142b234 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetDevice.go @@ -0,0 +1,179 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a device key, returns information about a remembered device for the +// current user. For more information about device authentication, see [Working with user devices in your user pool]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +func (c *Client) GetDevice(ctx context.Context, params *GetDeviceInput, optFns ...func(*Options)) (*GetDeviceOutput, error) { + if params == nil { + params = &GetDeviceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetDevice", params, optFns, c.addOperationGetDeviceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetDeviceOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to get the device. +type GetDeviceInput struct { + + // The key of the device that you want to get information about. + // + // This member is required. + DeviceKey *string + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + AccessToken *string + + noSmithyDocumentSerde +} + +// Gets the device response. +type GetDeviceOutput struct { + + // Details of the requested device. Includes device information, last-accessed and + // created dates, and the device key. + // + // This member is required. + Device *types.DeviceType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetDeviceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDevice{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetDevice{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetDevice"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetDeviceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDevice(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetDevice(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetDevice", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetGroup.go new file mode 100644 index 00000000..b9d5ed38 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetGroup.go @@ -0,0 +1,183 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID and a group name, returns information about the user group. +// +// For more information about user pool groups, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) GetGroup(ctx context.Context, params *GetGroupInput, optFns ...func(*Options)) (*GetGroupOutput, error) { + if params == nil { + params = &GetGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetGroup", params, optFns, c.addOperationGetGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetGroupInput struct { + + // The name of the group that you want to get information about. + // + // This member is required. + GroupName *string + + // The ID of the user pool that contains the group that you want to query. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type GetGroupOutput struct { + + // A container for the requested group. Includes description, precedence, and IAM + // role values. + Group *types.GroupType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetIdentityProviderByIdentifier.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetIdentityProviderByIdentifier.go new file mode 100644 index 00000000..45e24c53 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetIdentityProviderByIdentifier.go @@ -0,0 +1,176 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given the identifier of an identity provider (IdP), for example examplecorp , +// returns information about the user pool configuration for that IdP. For more +// information about IdPs, see [Third-party IdP sign-in]. +// +// [Third-party IdP sign-in]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html +func (c *Client) GetIdentityProviderByIdentifier(ctx context.Context, params *GetIdentityProviderByIdentifierInput, optFns ...func(*Options)) (*GetIdentityProviderByIdentifierOutput, error) { + if params == nil { + params = &GetIdentityProviderByIdentifierInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetIdentityProviderByIdentifier", params, optFns, c.addOperationGetIdentityProviderByIdentifierMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetIdentityProviderByIdentifierOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetIdentityProviderByIdentifierInput struct { + + // The identifier that you assigned to your user pool. The identifier is an + // alternative name for an IdP that is distinct from the IdP name. For example, an + // IdP with a name of MyIdP might have an identifier of the email domain + // example.com . + // + // This member is required. + IdpIdentifier *string + + // The ID of the user pool where you want to get information about the IdP. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type GetIdentityProviderByIdentifierOutput struct { + + // The configuration of the IdP in your user pool. Includes additional + // identifiers, the IdP name and type, and trust-relationship details like the + // issuer URL. + // + // This member is required. + IdentityProvider *types.IdentityProviderType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetIdentityProviderByIdentifierMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetIdentityProviderByIdentifier{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetIdentityProviderByIdentifier{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetIdentityProviderByIdentifier"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetIdentityProviderByIdentifierValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetIdentityProviderByIdentifier(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetIdentityProviderByIdentifier(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetIdentityProviderByIdentifier", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetLogDeliveryConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetLogDeliveryConfiguration.go new file mode 100644 index 00000000..44b7a3df --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetLogDeliveryConfiguration.go @@ -0,0 +1,179 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns the logging configuration. User pools can export +// message-delivery error and threat-protection activity logs to external Amazon +// Web Services services. For more information, see [Exporting user pool logs]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Exporting user pool logs]: https://docs.aws.amazon.com/cognito/latest/developerguide/exporting-quotas-and-usage.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) GetLogDeliveryConfiguration(ctx context.Context, params *GetLogDeliveryConfigurationInput, optFns ...func(*Options)) (*GetLogDeliveryConfigurationOutput, error) { + if params == nil { + params = &GetLogDeliveryConfigurationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetLogDeliveryConfiguration", params, optFns, c.addOperationGetLogDeliveryConfigurationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetLogDeliveryConfigurationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetLogDeliveryConfigurationInput struct { + + // The ID of the user pool that has the logging configuration that you want to + // view. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type GetLogDeliveryConfigurationOutput struct { + + // The logging configuration of the requested user pool. Includes types of logs + // configured and their destinations. + LogDeliveryConfiguration *types.LogDeliveryConfigurationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetLogDeliveryConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetLogDeliveryConfiguration{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetLogDeliveryConfiguration{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetLogDeliveryConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetLogDeliveryConfigurationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetLogDeliveryConfiguration(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetLogDeliveryConfiguration(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetLogDeliveryConfiguration", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetSigningCertificate.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetSigningCertificate.go new file mode 100644 index 00000000..4a486100 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetSigningCertificate.go @@ -0,0 +1,184 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns the signing certificate for SAML 2.0 federation. +// +// Issued certificates are valid for 10 years from the date of issue. Amazon +// Cognito issues and assigns a new signing certificate annually. This renewal +// process returns a new value in the response to GetSigningCertificate , but +// doesn't invalidate the original certificate. +// +// For more information, see [Signing SAML requests]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing SAML requests]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-SAML-signing-encryption.html#cognito-user-pools-SAML-signing +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) GetSigningCertificate(ctx context.Context, params *GetSigningCertificateInput, optFns ...func(*Options)) (*GetSigningCertificateOutput, error) { + if params == nil { + params = &GetSigningCertificateInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetSigningCertificate", params, optFns, c.addOperationGetSigningCertificateMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetSigningCertificateOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Request to get a signing certificate from Amazon Cognito. +type GetSigningCertificateInput struct { + + // The ID of the user pool where you want to view the signing certificate. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Response from Amazon Cognito for a signing certificate request. +type GetSigningCertificateOutput struct { + + // The x.509 certificate that signs SAML 2.0 authentication requests for your user + // pool. + Certificate *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetSigningCertificateMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetSigningCertificate{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetSigningCertificate{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetSigningCertificate"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetSigningCertificateValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetSigningCertificate(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetSigningCertificate(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetSigningCertificate", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetTokensFromRefreshToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetTokensFromRefreshToken.go new file mode 100644 index 00000000..0333eb84 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetTokensFromRefreshToken.go @@ -0,0 +1,214 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a refresh token, issues new ID, access, and optionally refresh tokens for +// the user who owns the submitted token. This operation issues a new refresh token +// and invalidates the original refresh token after an optional grace period when +// refresh token rotation is enabled. If refresh token rotation is disabled, issues +// new ID and access tokens only. +func (c *Client) GetTokensFromRefreshToken(ctx context.Context, params *GetTokensFromRefreshTokenInput, optFns ...func(*Options)) (*GetTokensFromRefreshTokenOutput, error) { + if params == nil { + params = &GetTokensFromRefreshTokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetTokensFromRefreshToken", params, optFns, c.addOperationGetTokensFromRefreshTokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetTokensFromRefreshTokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetTokensFromRefreshTokenInput struct { + + // The app client that issued the refresh token to the user who wants to request + // new tokens. + // + // This member is required. + ClientId *string + + // A valid refresh token that can authorize the request for new tokens. When + // refresh token rotation is active in the requested app client, this token is + // invalidated after the request is complete. + // + // This member is required. + RefreshToken *string + + // A map of custom key-value pairs that you can provide as input for certain + // custom workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the GetTokensFromRefreshToken API action, Amazon Cognito + // invokes the Lambda function the pre token generation trigger. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // The client secret of the requested app client, if the client has a secret. + ClientSecret *string + + // When you enable device remembering, Amazon Cognito issues a device key that you + // can use for device authentication that bypasses multi-factor authentication + // (MFA). To implement GetTokensFromRefreshToken in a user pool with device + // remembering, you must capture the device key from the initial authentication + // request. If your application doesn't provide the key of a registered device, + // Amazon Cognito issues a new one. You must provide the confirmed device key in + // this request if device remembering is enabled in your user pool. + // + // For more information about device remembering, see [Working with devices]. + // + // [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + DeviceKey *string + + noSmithyDocumentSerde +} + +type GetTokensFromRefreshTokenOutput struct { + + // The object that your application receives after authentication. Contains tokens + // and information for device authentication. + AuthenticationResult *types.AuthenticationResultType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetTokensFromRefreshTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetTokensFromRefreshToken{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetTokensFromRefreshToken{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetTokensFromRefreshToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetTokensFromRefreshTokenValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetTokensFromRefreshToken(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetTokensFromRefreshToken(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetTokensFromRefreshToken", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUICustomization.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUICustomization.go new file mode 100644 index 00000000..7dc05344 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUICustomization.go @@ -0,0 +1,172 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID or app client, returns information about classic hosted UI +// branding that you applied, if any. Returns user-pool level branding information +// if no app client branding is applied, or if you don't specify an app client ID. +// Returns an empty object if you haven't applied hosted UI branding to either the +// client or the user pool. For more information, see [Hosted UI (classic) branding]. +// +// [Hosted UI (classic) branding]: https://docs.aws.amazon.com/cognito/latest/developerguide/hosted-ui-classic-branding.html +func (c *Client) GetUICustomization(ctx context.Context, params *GetUICustomizationInput, optFns ...func(*Options)) (*GetUICustomizationOutput, error) { + if params == nil { + params = &GetUICustomizationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetUICustomization", params, optFns, c.addOperationGetUICustomizationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetUICustomizationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetUICustomizationInput struct { + + // The ID of the user pool that you want to query for branding settings. + // + // This member is required. + UserPoolId *string + + // The ID of the app client that you want to query for branding settings. + ClientId *string + + noSmithyDocumentSerde +} + +type GetUICustomizationOutput struct { + + // Information about the classic hosted UI custom CSS and logo-image branding that + // you applied to the user pool or app client. + // + // This member is required. + UICustomization *types.UICustomizationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetUICustomizationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetUICustomization{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetUICustomization{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetUICustomization"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetUICustomizationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetUICustomization(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetUICustomization(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetUICustomization", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUser.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUser.go new file mode 100644 index 00000000..1ecb5959 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUser.go @@ -0,0 +1,196 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Gets user attributes and and MFA settings for the currently signed-in user. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) GetUser(ctx context.Context, params *GetUserInput, optFns ...func(*Options)) (*GetUserOutput, error) { + if params == nil { + params = &GetUserInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetUser", params, optFns, c.addOperationGetUserMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetUserOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to get information about the user. +type GetUserInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + noSmithyDocumentSerde +} + +// Represents the response from the server from the request to get information +// about the user. +type GetUserOutput struct { + + // An array of name-value pairs representing user attributes. + // + // Custom attributes are prepended with the custom: prefix. + // + // This member is required. + UserAttributes []types.AttributeType + + // The name of the user that you requested. + // + // This member is required. + Username *string + + // This response parameter is no longer supported. It provides information only + // about SMS MFA configurations. It doesn't provide information about time-based + // one-time password (TOTP) software token MFA configurations. To look up + // information about either type of MFA configuration, use UserMFASettingList + // instead. + MFAOptions []types.MFAOptionType + + // The user's preferred MFA. Users can prefer SMS message, email message, or TOTP + // MFA. + PreferredMfaSetting *string + + // The MFA options that are activated for the user. The possible values in this + // list are SMS_MFA , EMAIL_OTP , and SOFTWARE_TOKEN_MFA . + UserMFASettingList []string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetUserMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetUser{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetUser{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetUser"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetUserValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetUser(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetUser(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetUser", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAttributeVerificationCode.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAttributeVerificationCode.go new file mode 100644 index 00000000..6a83adb4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAttributeVerificationCode.go @@ -0,0 +1,228 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given an attribute name, sends a user attribute verification code for the +// specified attribute name to the currently signed-in user. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) GetUserAttributeVerificationCode(ctx context.Context, params *GetUserAttributeVerificationCodeInput, optFns ...func(*Options)) (*GetUserAttributeVerificationCodeOutput, error) { + if params == nil { + params = &GetUserAttributeVerificationCodeInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetUserAttributeVerificationCode", params, optFns, c.addOperationGetUserAttributeVerificationCodeMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetUserAttributeVerificationCodeOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to get user attribute verification. +type GetUserAttributeVerificationCodeInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The name of the attribute that the user wants to verify, for example email . + // + // This member is required. + AttributeName *string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the GetUserAttributeVerificationCode API action, Amazon + // Cognito invokes the function that is assigned to the custom message trigger. + // When Amazon Cognito invokes this function, it passes a JSON payload, which the + // function receives as input. This payload contains a clientMetadata attribute, + // which provides the data that you assigned to the ClientMetadata parameter in + // your GetUserAttributeVerificationCode request. In your function code in Lambda, + // you can process the clientMetadata value to enhance your workflow for your + // specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + noSmithyDocumentSerde +} + +// The verification code response returned by the server response to get the user +// attribute verification code. +type GetUserAttributeVerificationCodeOutput struct { + + // Information about the delivery destination of the user attribute verification + // code. + CodeDeliveryDetails *types.CodeDeliveryDetailsType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetUserAttributeVerificationCodeMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetUserAttributeVerificationCode{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetUserAttributeVerificationCode{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetUserAttributeVerificationCode"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetUserAttributeVerificationCodeValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetUserAttributeVerificationCode(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetUserAttributeVerificationCode(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetUserAttributeVerificationCode", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAuthFactors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAuthFactors.go new file mode 100644 index 00000000..14614ec6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserAuthFactors.go @@ -0,0 +1,189 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists the authentication options for the currently signed-in user. Returns the +// following: +// +// - The user's multi-factor authentication (MFA) preferences. +// +// - The user's options for choice-based authentication with the USER_AUTH flow. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) GetUserAuthFactors(ctx context.Context, params *GetUserAuthFactorsInput, optFns ...func(*Options)) (*GetUserAuthFactorsOutput, error) { + if params == nil { + params = &GetUserAuthFactorsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetUserAuthFactors", params, optFns, c.addOperationGetUserAuthFactorsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetUserAuthFactorsOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetUserAuthFactorsInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + noSmithyDocumentSerde +} + +type GetUserAuthFactorsOutput struct { + + // The name of the user who is eligible for the authentication factors in the + // response. + // + // This member is required. + Username *string + + // The authentication types that are available to the user with USER_AUTH sign-in, + // for example ["PASSWORD", "WEB_AUTHN"] . + ConfiguredUserAuthFactors []types.AuthFactorType + + // The challenge method that Amazon Cognito returns to the user in response to + // sign-in requests. Users can prefer SMS message, email message, or TOTP MFA. + PreferredMfaSetting *string + + // The MFA options that are activated for the user. The possible values in this + // list are SMS_MFA , EMAIL_OTP , and SOFTWARE_TOKEN_MFA . + UserMFASettingList []string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetUserAuthFactorsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetUserAuthFactors{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetUserAuthFactors{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetUserAuthFactors"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetUserAuthFactorsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetUserAuthFactors(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetUserAuthFactors(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetUserAuthFactors", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserPoolMfaConfig.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserPoolMfaConfig.go new file mode 100644 index 00000000..9048cfd2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GetUserPoolMfaConfig.go @@ -0,0 +1,216 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns configuration for sign-in with WebAuthn +// authenticators and for multi-factor authentication (MFA). This operation +// describes the following: +// +// - The WebAuthn relying party (RP) ID and user-verification settings. +// +// - The required, optional, or disabled state of MFA for all user pool users. +// +// - The message templates for email and SMS MFA. +// +// - The enabled or disabled state of time-based one-time password (TOTP) MFA. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) GetUserPoolMfaConfig(ctx context.Context, params *GetUserPoolMfaConfigInput, optFns ...func(*Options)) (*GetUserPoolMfaConfigOutput, error) { + if params == nil { + params = &GetUserPoolMfaConfigInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetUserPoolMfaConfig", params, optFns, c.addOperationGetUserPoolMfaConfigMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetUserPoolMfaConfigOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetUserPoolMfaConfigInput struct { + + // The ID of the user pool where you want to query WebAuthn and MFA configuration. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type GetUserPoolMfaConfigOutput struct { + + // Shows configuration for user pool email message MFA and sign-in with one-time + // passwords (OTPs). Includes the subject and body of the email message template + // for sign-in and MFA messages. To activate this setting, your user pool must be + // in the [Essentials tier]or higher. + // + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + EmailMfaConfiguration *types.EmailMfaConfigType + + // Displays the state of multi-factor authentication (MFA) as on, off, or + // optional. When ON , all users must set up MFA before they can sign in. When + // OPTIONAL , your application must make a client-side determination of whether a + // user wants to register an MFA device. For user pools with adaptive + // authentication with threat protection, choose OPTIONAL . + // + // When MfaConfiguration is OPTIONAL , managed login doesn't automatically prompt + // users to set up MFA. Amazon Cognito generates MFA prompts in API responses and + // in managed login for users who have chosen and configured a preferred MFA + // factor. + MfaConfiguration types.UserPoolMfaType + + // Shows user pool configuration for SMS message MFA. Includes the message + // template and the SMS message sending configuration for Amazon SNS. + SmsMfaConfiguration *types.SmsMfaConfigType + + // Shows user pool configuration for time-based one-time password (TOTP) MFA. + // Includes TOTP enabled or disabled state. + SoftwareTokenMfaConfiguration *types.SoftwareTokenMfaConfigType + + // Shows user pool configuration for sign-in with passkey authenticators like + // biometric devices and security keys. Passkeys are not eligible MFA factors. They + // are instead an eligible primary sign-in factor for [choice-based authentication], or the USER_AUTH flow. + // + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + WebAuthnConfiguration *types.WebAuthnConfigurationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetUserPoolMfaConfigMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetUserPoolMfaConfig{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetUserPoolMfaConfig{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetUserPoolMfaConfig"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetUserPoolMfaConfigValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetUserPoolMfaConfig(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetUserPoolMfaConfig(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetUserPoolMfaConfig", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GlobalSignOut.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GlobalSignOut.go new file mode 100644 index 00000000..af81c07a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_GlobalSignOut.go @@ -0,0 +1,193 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Invalidates the identity, access, and refresh tokens that Amazon Cognito issued +// to a user. Call this operation when your user signs out of your app. This +// results in the following behavior. +// +// - Amazon Cognito no longer accepts token-authorized user operations that you +// authorize with a signed-out user's access tokens. For more information, see [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// Amazon Cognito returns an Access Token has been revoked error when your app +// +// attempts to authorize a user pools API request with a revoked access token that +// contains the scope aws.cognito.signin.user.admin . +// +// - Amazon Cognito no longer accepts a signed-out user's ID token in a [GetId]request +// to an identity pool with ServerSideTokenCheck enabled for its user pool IdP +// configuration in [CognitoIdentityProvider]. +// +// - Amazon Cognito no longer accepts a signed-out user's refresh tokens in +// refresh requests. +// +// Other requests might be valid until your user's token expires. This operation +// doesn't clear the [managed login]session cookie. To clear the session for a user who signed in +// with managed login or the classic hosted UI, direct their browser session to the +// [logout endpoint]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [logout endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html +// +// [CognitoIdentityProvider]: https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_CognitoIdentityProvider.html +// [GetId]: https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html +func (c *Client) GlobalSignOut(ctx context.Context, params *GlobalSignOutInput, optFns ...func(*Options)) (*GlobalSignOutOutput, error) { + if params == nil { + params = &GlobalSignOutInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GlobalSignOut", params, optFns, c.addOperationGlobalSignOutMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GlobalSignOutOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to sign out all devices. +type GlobalSignOutInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + noSmithyDocumentSerde +} + +// The response to the request to sign out all devices. +type GlobalSignOutOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGlobalSignOutMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpGlobalSignOut{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGlobalSignOut{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GlobalSignOut"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGlobalSignOutValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGlobalSignOut(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGlobalSignOut(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GlobalSignOut", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_InitiateAuth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_InitiateAuth.go new file mode 100644 index 00000000..d4e934fd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_InitiateAuth.go @@ -0,0 +1,439 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Declares an authentication flow and initiates sign-in for a user in the Amazon +// Cognito user directory. Amazon Cognito might respond with an additional +// challenge or an AuthenticationResult that contains the outcome of a successful +// authentication. You can't sign in a user with a federated IdP with InitiateAuth +// . For more information, see [Authentication]. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) InitiateAuth(ctx context.Context, params *InitiateAuthInput, optFns ...func(*Options)) (*InitiateAuthOutput, error) { + if params == nil { + params = &InitiateAuthInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "InitiateAuth", params, optFns, c.addOperationInitiateAuthMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*InitiateAuthOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Initiates the authentication request. +type InitiateAuthInput struct { + + // The authentication flow that you want to initiate. Each AuthFlow has linked + // AuthParameters that you must submit. The following are some example flows. + // + // USER_AUTH The entry point for [choice-based authentication] with passwords, one-time passwords, and WebAuthn + // authenticators. Request a preferred authentication type or review available + // authentication types. From the offered authentication types, select one in a + // challenge response and then authenticate with that method in an additional + // challenge response. To activate this setting, your user pool must be in the [Essentials tier]or + // higher. + // + // USER_SRP_AUTH Username-password authentication with the Secure Remote Password + // (SRP) protocol. For more information, see [Use SRP password verification in custom authentication flow]. + // + // REFRESH_TOKEN_AUTH and REFRESH_TOKEN Receive new ID and access tokens when you + // pass a REFRESH_TOKEN parameter with a valid refresh token as the value. For + // more information, see [Using the refresh token]. + // + // CUSTOM_AUTH Custom authentication with Lambda triggers. For more information, + // see [Custom authentication challenge Lambda triggers]. + // + // USER_PASSWORD_AUTH Client-side username-password authentication with the + // password sent directly in the request. For more information about client-side + // and server-side authentication, see [SDK authorization models]. + // + // ADMIN_USER_PASSWORD_AUTH is a flow type of AdminInitiateAuth and isn't valid + // for InitiateAuth. ADMIN_NO_SRP_AUTH is a legacy server-side username-password + // flow and isn't valid for InitiateAuth. + // + // [SDK authorization models]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-public-server-side.html + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + // [Use SRP password verification in custom authentication flow]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#Using-SRP-password-verification-in-custom-authentication-flow + // [Using the refresh token]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + // [Custom authentication challenge Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html + // + // This member is required. + AuthFlow types.AuthFlowType + + // The ID of the app client that your user wants to sign in to. + // + // This member is required. + ClientId *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // The authentication parameters. These are inputs corresponding to the AuthFlow + // that you're invoking. + // + // The required values are specific to the InitiateAuthRequest$AuthFlow. + // + // The following are some authentication flows and their parameters. Add a + // SECRET_HASH parameter if your app client has a client secret. + // + // - USER_AUTH : USERNAME (required), PREFERRED_CHALLENGE . If you don't provide + // a value for PREFERRED_CHALLENGE , Amazon Cognito responds with the + // AvailableChallenges parameter that specifies the available sign-in methods. + // + // - USER_SRP_AUTH : USERNAME (required), SRP_A (required), DEVICE_KEY . + // + // - USER_PASSWORD_AUTH : USERNAME (required), PASSWORD (required), DEVICE_KEY . + // + // - REFRESH_TOKEN_AUTH/REFRESH_TOKEN : REFRESH_TOKEN (required), DEVICE_KEY . + // + // - CUSTOM_AUTH : USERNAME (required), SECRET_HASH (if app client is configured + // with client secret), DEVICE_KEY . To start the authentication flow with + // password verification, include ChallengeName: SRP_A and SRP_A: (The SRP_A + // Value) . + // + // For more information about SECRET_HASH , see [Computing secret hash values]. For information about DEVICE_KEY + // , see [Working with user devices in your user pool]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + // [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + AuthParameters map[string]string + + // A map of custom key-value pairs that you can provide as input for certain + // custom workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you send an InitiateAuth request, Amazon Cognito invokes the + // Lambda functions that are specified for various triggers. The ClientMetadata + // value is passed as input to the functions for only the following triggers. + // + // - Pre sign-up + // + // - Pre authentication + // + // - User migration + // + // When Amazon Cognito invokes the functions for these triggers, it passes a JSON + // payload as input to the function. This payload contains a validationData + // attribute with the data that you assigned to the ClientMetadata parameter in + // your InitiateAuth request. In your function, validationData can contribute to + // operations that require data that isn't in the default payload. + // + // InitiateAuth requests invokes the following triggers without ClientMetadata as + // input. + // + // - Post authentication + // + // - Custom message + // + // - Pre token generation + // + // - Create auth challenge + // + // - Define auth challenge + // + // - Custom email sender + // + // - Custom SMS sender + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // The optional session ID from a ConfirmSignUp API request. You can sign in a + // user directly from the sign-up process with the USER_AUTH authentication flow. + // When you pass the session ID to InitiateAuth , Amazon Cognito assumes the SMS or + // email message one-time verification password from ConfirmSignUp as the primary + // authentication factor. You're not required to submit this code a second time. + // This option is only valid for users who have confirmed their sign-up and are + // signing in for the first time within the authentication flow session duration of + // the session ID. + Session *string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + noSmithyDocumentSerde +} + +// Initiates the authentication response. +type InitiateAuthOutput struct { + + // The result of a successful and complete authentication request. This result is + // only returned if the user doesn't need to pass another challenge. If they must + // pass another challenge before they get tokens, Amazon Cognito returns a + // challenge in ChallengeName , ChallengeParameters , and Session response + // parameters. + AuthenticationResult *types.AuthenticationResultType + + // This response parameter lists the available authentication challenges that + // users can select from in [choice-based authentication]. For example, they might be able to choose between + // passkey authentication, a one-time password from an SMS message, and a + // traditional password. + // + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + AvailableChallenges []types.ChallengeNameType + + // The name of an additional authentication challenge that you must respond to. + // + // Possible challenges include the following: + // + // All of the following challenges require USERNAME and, when the app client has a + // client secret, SECRET_HASH in the parameters. + // + // - WEB_AUTHN : Respond to the challenge with the results of a successful + // authentication with a WebAuthn authenticator, or passkey. Examples of WebAuthn + // authenticators include biometric devices and security keys. + // + // - PASSWORD : Respond with USER_PASSWORD_AUTH parameters: USERNAME (required), + // PASSWORD (required), SECRET_HASH (required if the app client is configured + // with a client secret), DEVICE_KEY . + // + // - PASSWORD_SRP : Respond with USER_SRP_AUTH parameters: USERNAME (required), + // SRP_A (required), SECRET_HASH (required if the app client is configured with a + // client secret), DEVICE_KEY . + // + // - SELECT_CHALLENGE : Respond to the challenge with USERNAME and an ANSWER that + // matches one of the challenge types in the AvailableChallenges response + // parameter. + // + // - SMS_MFA : Respond with an SMS_MFA_CODE that your user pool delivered in an + // SMS message. + // + // - EMAIL_OTP : Respond with an EMAIL_OTP_CODE that your user pool delivered in + // an email message. + // + // - PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP calculations. + // + // - CUSTOM_CHALLENGE : This is returned if your custom authentication flow + // determines that the user should pass another challenge before tokens are issued. + // The parameters of the challenge are determined by your Lambda function. + // + // - DEVICE_SRP_AUTH : Respond with the initial parameters of device SRP + // authentication. For more information, see [Signing in with a device]. + // + // - DEVICE_PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP + // calculations. For more information, see [Signing in with a device]. + // + // - NEW_PASSWORD_REQUIRED : For users who are required to change their passwords + // after successful first login. Respond to this challenge with NEW_PASSWORD and + // any required attributes that Amazon Cognito returned in the requiredAttributes + // parameter. You can also set values for attributes that aren't required by your + // user pool and that your app client can write. + // + // Amazon Cognito only returns this challenge for users who have temporary + // passwords. When you create passwordless users, you must provide values for all + // required attributes. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // - MFA_SETUP : For users who are required to setup an MFA factor before they + // can sign in. The MFA types activated for the user pool will be listed in the + // challenge parameters MFAS_CAN_SETUP value. + // + // To set up time-based one-time password (TOTP) MFA, use the session returned in + // this challenge from InitiateAuth or AdminInitiateAuth as an input to + // AssociateSoftwareToken . Then, use the session returned by VerifySoftwareToken + // as an input to RespondToAuthChallenge or AdminRespondToAuthChallenge with + // challenge name MFA_SETUP to complete sign-in. + // + // To set up SMS or email MFA, collect a phone_number or email attribute for the + // user. Then restart the authentication flow with an InitiateAuth or + // AdminInitiateAuth request. + // + // [Signing in with a device]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-signing-in-with-a-device + ChallengeName types.ChallengeNameType + + // The required parameters of the ChallengeName challenge. + // + // All challenges require USERNAME . They also require SECRET_HASH if your app + // client has a client secret. + ChallengeParameters map[string]string + + // The session identifier that links a challenge response to the initial + // authentication request. If the user must pass another challenge, Amazon Cognito + // returns a session ID and challenge parameters. + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationInitiateAuthMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpInitiateAuth{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpInitiateAuth{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "InitiateAuth"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpInitiateAuthValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opInitiateAuth(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opInitiateAuth(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "InitiateAuth", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListDevices.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListDevices.go new file mode 100644 index 00000000..edaea06d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListDevices.go @@ -0,0 +1,192 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists the devices that Amazon Cognito has registered to the currently signed-in +// user. For more information about device authentication, see [Working with user devices in your user pool]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +func (c *Client) ListDevices(ctx context.Context, params *ListDevicesInput, optFns ...func(*Options)) (*ListDevicesOutput, error) { + if params == nil { + params = &ListDevicesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListDevices", params, optFns, c.addOperationListDevicesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListDevicesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to list the devices. +type ListDevicesInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The maximum number of devices that you want Amazon Cognito to return in the + // response. + Limit *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + PaginationToken *string + + noSmithyDocumentSerde +} + +// Represents the response to list devices. +type ListDevicesOutput struct { + + // An array of devices and their details. Each entry that's returned includes + // device information, last-accessed and created dates, and the device key. + Devices []types.DeviceType + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + PaginationToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListDevicesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListDevices{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListDevices{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListDevices"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListDevicesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListDevices(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opListDevices(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListDevices", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListGroups.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListGroups.go new file mode 100644 index 00000000..3d7348d3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListGroups.go @@ -0,0 +1,286 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns user pool groups and their details. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListGroups(ctx context.Context, params *ListGroupsInput, optFns ...func(*Options)) (*ListGroupsOutput, error) { + if params == nil { + params = &ListGroupsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListGroups", params, optFns, c.addOperationListGroupsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListGroupsOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListGroupsInput struct { + + // The ID of the user pool where you want to list user groups. + // + // This member is required. + UserPoolId *string + + // The maximum number of groups that you want Amazon Cognito to return in the + // response. + Limit *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type ListGroupsOutput struct { + + // An array of groups and their details. Each entry that's returned includes + // description, precedence, and IAM role values. + Groups []types.GroupType + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListGroupsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListGroups{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListGroups{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListGroups"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListGroupsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListGroups(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListGroupsPaginatorOptions is the paginator options for ListGroups +type ListGroupsPaginatorOptions struct { + // The maximum number of groups that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListGroupsPaginator is a paginator for ListGroups +type ListGroupsPaginator struct { + options ListGroupsPaginatorOptions + client ListGroupsAPIClient + params *ListGroupsInput + nextToken *string + firstPage bool +} + +// NewListGroupsPaginator returns a new ListGroupsPaginator +func NewListGroupsPaginator(client ListGroupsAPIClient, params *ListGroupsInput, optFns ...func(*ListGroupsPaginatorOptions)) *ListGroupsPaginator { + if params == nil { + params = &ListGroupsInput{} + } + + options := ListGroupsPaginatorOptions{} + if params.Limit != nil { + options.Limit = *params.Limit + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListGroupsPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListGroupsPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListGroups page. +func (p *ListGroupsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListGroupsOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.Limit = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListGroups(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListGroupsAPIClient is a client that implements the ListGroups operation. +type ListGroupsAPIClient interface { + ListGroups(context.Context, *ListGroupsInput, ...func(*Options)) (*ListGroupsOutput, error) +} + +var _ ListGroupsAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListGroups(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListGroups", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListIdentityProviders.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListIdentityProviders.go new file mode 100644 index 00000000..4d15b519 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListIdentityProviders.go @@ -0,0 +1,293 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns information about configured identity providers +// (IdPs). For more information about IdPs, see [Third-party IdP sign-in]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Third-party IdP sign-in]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListIdentityProviders(ctx context.Context, params *ListIdentityProvidersInput, optFns ...func(*Options)) (*ListIdentityProvidersOutput, error) { + if params == nil { + params = &ListIdentityProvidersInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListIdentityProviders", params, optFns, c.addOperationListIdentityProvidersMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListIdentityProvidersOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListIdentityProvidersInput struct { + + // The ID of the user pool where you want to list IdPs. + // + // This member is required. + UserPoolId *string + + // The maximum number of IdPs that you want Amazon Cognito to return in the + // response. + MaxResults *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type ListIdentityProvidersOutput struct { + + // An array of the IdPs in your user pool. For each, the response includes + // identifiers, the IdP name and type, and trust-relationship details like the + // issuer URL. + // + // This member is required. + Providers []types.ProviderDescription + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListIdentityProvidersMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListIdentityProviders{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListIdentityProviders{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListIdentityProviders"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListIdentityProvidersValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListIdentityProviders(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListIdentityProvidersPaginatorOptions is the paginator options for +// ListIdentityProviders +type ListIdentityProvidersPaginatorOptions struct { + // The maximum number of IdPs that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListIdentityProvidersPaginator is a paginator for ListIdentityProviders +type ListIdentityProvidersPaginator struct { + options ListIdentityProvidersPaginatorOptions + client ListIdentityProvidersAPIClient + params *ListIdentityProvidersInput + nextToken *string + firstPage bool +} + +// NewListIdentityProvidersPaginator returns a new ListIdentityProvidersPaginator +func NewListIdentityProvidersPaginator(client ListIdentityProvidersAPIClient, params *ListIdentityProvidersInput, optFns ...func(*ListIdentityProvidersPaginatorOptions)) *ListIdentityProvidersPaginator { + if params == nil { + params = &ListIdentityProvidersInput{} + } + + options := ListIdentityProvidersPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListIdentityProvidersPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListIdentityProvidersPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListIdentityProviders page. +func (p *ListIdentityProvidersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListIdentityProvidersOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListIdentityProviders(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListIdentityProvidersAPIClient is a client that implements the +// ListIdentityProviders operation. +type ListIdentityProvidersAPIClient interface { + ListIdentityProviders(context.Context, *ListIdentityProvidersInput, ...func(*Options)) (*ListIdentityProvidersOutput, error) +} + +var _ ListIdentityProvidersAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListIdentityProviders(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListIdentityProviders", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListResourceServers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListResourceServers.go new file mode 100644 index 00000000..0349c127 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListResourceServers.go @@ -0,0 +1,292 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns all resource servers and their details. For more +// information about resource servers, see [Access control with resource servers]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Access control with resource servers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListResourceServers(ctx context.Context, params *ListResourceServersInput, optFns ...func(*Options)) (*ListResourceServersOutput, error) { + if params == nil { + params = &ListResourceServersInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListResourceServers", params, optFns, c.addOperationListResourceServersMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListResourceServersOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListResourceServersInput struct { + + // The ID of the user pool where you want to list resource servers. + // + // This member is required. + UserPoolId *string + + // The maximum number of resource servers that you want Amazon Cognito to return + // in the response. + MaxResults *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type ListResourceServersOutput struct { + + // An array of resource servers and the details of their configuration. For each, + // the response includes names, identifiers, and custom scopes. + // + // This member is required. + ResourceServers []types.ResourceServerType + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListResourceServersMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListResourceServers{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListResourceServers{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListResourceServers"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListResourceServersValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListResourceServers(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListResourceServersPaginatorOptions is the paginator options for +// ListResourceServers +type ListResourceServersPaginatorOptions struct { + // The maximum number of resource servers that you want Amazon Cognito to return + // in the response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListResourceServersPaginator is a paginator for ListResourceServers +type ListResourceServersPaginator struct { + options ListResourceServersPaginatorOptions + client ListResourceServersAPIClient + params *ListResourceServersInput + nextToken *string + firstPage bool +} + +// NewListResourceServersPaginator returns a new ListResourceServersPaginator +func NewListResourceServersPaginator(client ListResourceServersAPIClient, params *ListResourceServersInput, optFns ...func(*ListResourceServersPaginatorOptions)) *ListResourceServersPaginator { + if params == nil { + params = &ListResourceServersInput{} + } + + options := ListResourceServersPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListResourceServersPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListResourceServersPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListResourceServers page. +func (p *ListResourceServersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListResourceServersOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListResourceServers(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListResourceServersAPIClient is a client that implements the +// ListResourceServers operation. +type ListResourceServersAPIClient interface { + ListResourceServers(context.Context, *ListResourceServersInput, ...func(*Options)) (*ListResourceServersOutput, error) +} + +var _ ListResourceServersAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListResourceServers(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListResourceServers", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListTagsForResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListTagsForResource.go new file mode 100644 index 00000000..da9fc40f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListTagsForResource.go @@ -0,0 +1,162 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists the tags that are assigned to an Amazon Cognito user pool. For more +// information, see [Tagging resources]. +// +// [Tagging resources]: https://docs.aws.amazon.com/cognito/latest/developerguide/tagging.html +func (c *Client) ListTagsForResource(ctx context.Context, params *ListTagsForResourceInput, optFns ...func(*Options)) (*ListTagsForResourceOutput, error) { + if params == nil { + params = &ListTagsForResourceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListTagsForResource", params, optFns, c.addOperationListTagsForResourceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListTagsForResourceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListTagsForResourceInput struct { + + // The Amazon Resource Name (ARN) of the user pool that the tags are assigned to. + // + // This member is required. + ResourceArn *string + + noSmithyDocumentSerde +} + +type ListTagsForResourceOutput struct { + + // The tags that are assigned to the user pool. + Tags map[string]string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListTagsForResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListTagsForResource{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListTagsForResource{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListTagsForResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListTagsForResourceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListTagsForResource(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opListTagsForResource(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListTagsForResource", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserImportJobs.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserImportJobs.go new file mode 100644 index 00000000..fae5a84a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserImportJobs.go @@ -0,0 +1,202 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns user import jobs and their details. Import jobs +// are retained in user pool configuration so that you can stage, stop, start, +// review, and delete them. For more information about user import, see [Importing users from a CSV file]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Importing users from a CSV file]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListUserImportJobs(ctx context.Context, params *ListUserImportJobsInput, optFns ...func(*Options)) (*ListUserImportJobsOutput, error) { + if params == nil { + params = &ListUserImportJobsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListUserImportJobs", params, optFns, c.addOperationListUserImportJobsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListUserImportJobsOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to list the user import jobs. +type ListUserImportJobsInput struct { + + // The maximum number of import jobs that you want Amazon Cognito to return in the + // response. + // + // This member is required. + MaxResults *int32 + + // The ID of the user pool where you want to list import jobs. + // + // This member is required. + UserPoolId *string + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + PaginationToken *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to list the user import +// jobs. +type ListUserImportJobsOutput struct { + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + PaginationToken *string + + // An array of user import jobs from the requested user pool. For each, the + // response includes logging destination, status, and the Amazon S3 pre-signed URL + // for CSV upload. + UserImportJobs []types.UserImportJobType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListUserImportJobsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListUserImportJobs{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListUserImportJobs{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListUserImportJobs"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListUserImportJobsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListUserImportJobs(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opListUserImportJobs(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListUserImportJobs", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPoolClients.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPoolClients.go new file mode 100644 index 00000000..64947c69 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPoolClients.go @@ -0,0 +1,292 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, lists app clients. App clients are sets of rules for the +// access that you want a user pool to grant to one application. For more +// information, see [App clients]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [App clients]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListUserPoolClients(ctx context.Context, params *ListUserPoolClientsInput, optFns ...func(*Options)) (*ListUserPoolClientsOutput, error) { + if params == nil { + params = &ListUserPoolClientsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListUserPoolClients", params, optFns, c.addOperationListUserPoolClientsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListUserPoolClientsOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to list the user pool clients. +type ListUserPoolClientsInput struct { + + // The ID of the user pool where you want to list user pool clients. + // + // This member is required. + UserPoolId *string + + // The maximum number of app clients that you want Amazon Cognito to return in the + // response. + MaxResults *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +// Represents the response from the server that lists user pool clients. +type ListUserPoolClientsOutput struct { + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // An array of app clients and their details. Includes app client ID and name. + UserPoolClients []types.UserPoolClientDescription + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListUserPoolClientsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListUserPoolClients{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListUserPoolClients{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListUserPoolClients"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListUserPoolClientsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListUserPoolClients(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListUserPoolClientsPaginatorOptions is the paginator options for +// ListUserPoolClients +type ListUserPoolClientsPaginatorOptions struct { + // The maximum number of app clients that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListUserPoolClientsPaginator is a paginator for ListUserPoolClients +type ListUserPoolClientsPaginator struct { + options ListUserPoolClientsPaginatorOptions + client ListUserPoolClientsAPIClient + params *ListUserPoolClientsInput + nextToken *string + firstPage bool +} + +// NewListUserPoolClientsPaginator returns a new ListUserPoolClientsPaginator +func NewListUserPoolClientsPaginator(client ListUserPoolClientsAPIClient, params *ListUserPoolClientsInput, optFns ...func(*ListUserPoolClientsPaginatorOptions)) *ListUserPoolClientsPaginator { + if params == nil { + params = &ListUserPoolClientsInput{} + } + + options := ListUserPoolClientsPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListUserPoolClientsPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListUserPoolClientsPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListUserPoolClients page. +func (p *ListUserPoolClientsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListUserPoolClientsOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListUserPoolClients(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListUserPoolClientsAPIClient is a client that implements the +// ListUserPoolClients operation. +type ListUserPoolClientsAPIClient interface { + ListUserPoolClients(context.Context, *ListUserPoolClientsInput, ...func(*Options)) (*ListUserPoolClientsOutput, error) +} + +var _ ListUserPoolClientsAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListUserPoolClients(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListUserPoolClients", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPools.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPools.go new file mode 100644 index 00000000..5a441751 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUserPools.go @@ -0,0 +1,284 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Lists user pools and their details in the current Amazon Web Services account. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListUserPools(ctx context.Context, params *ListUserPoolsInput, optFns ...func(*Options)) (*ListUserPoolsOutput, error) { + if params == nil { + params = &ListUserPoolsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListUserPools", params, optFns, c.addOperationListUserPoolsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListUserPoolsOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to list user pools. +type ListUserPoolsInput struct { + + // The maximum number of user pools that you want Amazon Cognito to return in the + // response. + // + // This member is required. + MaxResults *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +// Represents the response to list user pools. +type ListUserPoolsOutput struct { + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // An array of user pools and their configuration details. + UserPools []types.UserPoolDescriptionType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListUserPoolsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListUserPools{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListUserPools{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListUserPools"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListUserPoolsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListUserPools(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListUserPoolsPaginatorOptions is the paginator options for ListUserPools +type ListUserPoolsPaginatorOptions struct { + // The maximum number of user pools that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListUserPoolsPaginator is a paginator for ListUserPools +type ListUserPoolsPaginator struct { + options ListUserPoolsPaginatorOptions + client ListUserPoolsAPIClient + params *ListUserPoolsInput + nextToken *string + firstPage bool +} + +// NewListUserPoolsPaginator returns a new ListUserPoolsPaginator +func NewListUserPoolsPaginator(client ListUserPoolsAPIClient, params *ListUserPoolsInput, optFns ...func(*ListUserPoolsPaginatorOptions)) *ListUserPoolsPaginator { + if params == nil { + params = &ListUserPoolsInput{} + } + + options := ListUserPoolsPaginatorOptions{} + if params.MaxResults != nil { + options.Limit = *params.MaxResults + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListUserPoolsPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListUserPoolsPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListUserPools page. +func (p *ListUserPoolsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListUserPoolsOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.MaxResults = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListUserPools(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListUserPoolsAPIClient is a client that implements the ListUserPools operation. +type ListUserPoolsAPIClient interface { + ListUserPools(context.Context, *ListUserPoolsInput, ...func(*Options)) (*ListUserPoolsOutput, error) +} + +var _ ListUserPoolsAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListUserPools(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListUserPools", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsers.go new file mode 100644 index 00000000..77ac1b10 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsers.go @@ -0,0 +1,357 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID, returns a list of users and their basic details in a user +// pool. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListUsers(ctx context.Context, params *ListUsersInput, optFns ...func(*Options)) (*ListUsersOutput, error) { + if params == nil { + params = &ListUsersInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListUsers", params, optFns, c.addOperationListUsersMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListUsersOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to list users. +type ListUsersInput struct { + + // The ID of the user pool where you want to display or search for users. + // + // This member is required. + UserPoolId *string + + // A JSON array of user attribute names, for example given_name , that you want + // Amazon Cognito to include in the response for each user. When you don't provide + // an AttributesToGet parameter, Amazon Cognito returns all attributes for each + // user. + // + // Use AttributesToGet with required attributes in your user pool, or in + // conjunction with Filter . Amazon Cognito returns an error if not all users in + // the results have set a value for the attribute you request. Attributes that you + // can't filter on, including custom attributes, must have a value set in every + // user profile before an AttributesToGet parameter returns results. + AttributesToGet []string + + // A filter string of the form "AttributeName Filter-Type "AttributeValue" . + // Quotation marks within the filter string must be escaped using the backslash ( \ + // ) character. For example, "family_name = \"Reddy\"" . + // + // - AttributeName: The name of the attribute to search for. You can only search + // for one attribute at a time. + // + // - Filter-Type: For an exact match, use = , for example, " given_name = \"Jon\" + // ". For a prefix ("starts with") match, use ^= , for example, " given_name ^= + // \"Jon\" ". + // + // - AttributeValue: The attribute value that must be matched for each user. + // + // If the filter string is empty, ListUsers returns all users in the user pool. + // + // You can only search for the following standard attributes: + // + // - username (case-sensitive) + // + // - email + // + // - phone_number + // + // - name + // + // - given_name + // + // - family_name + // + // - preferred_username + // + // - cognito:user_status (called Status in the Console) (case-insensitive) + // + // - status (called Enabled in the Console) (case-sensitive) + // + // - sub + // + // Custom attributes aren't searchable. + // + // You can also list users with a client-side filter. The server-side filter + // matches no more than one attribute. For an advanced search, use a client-side + // filter with the --query parameter of the list-users action in the CLI. When you + // use a client-side filter, ListUsers returns a paginated list of zero or more + // users. You can receive multiple pages in a row with zero results. Repeat the + // query with each pagination token that is returned until you receive a null + // pagination token value, and then review the combined result. + // + // For more information about server-side and client-side filtering, see [FilteringCLI output] in the [Command Line Interface User Guide]. + // + // For more information, see [Searching for Users Using the ListUsers API] and [Examples of Using the ListUsers API] in the Amazon Cognito Developer Guide. + // + // [Command Line Interface User Guide]: https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html + // [Searching for Users Using the ListUsers API]: https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-manage-user-accounts.html#cognito-user-pools-searching-for-users-using-listusers-api + // [FilteringCLI output]: https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html + // [Examples of Using the ListUsers API]: https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-manage-user-accounts.html#cognito-user-pools-searching-for-users-listusers-api-examples + Filter *string + + // The maximum number of users that you want Amazon Cognito to return in the + // response. + Limit *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + PaginationToken *string + + noSmithyDocumentSerde +} + +// The response from the request to list users. +type ListUsersOutput struct { + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + PaginationToken *string + + // An array of user pool users who match your query, and their attributes. + Users []types.UserType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListUsersMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListUsers{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListUsers{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListUsers"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListUsersValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListUsers(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListUsersPaginatorOptions is the paginator options for ListUsers +type ListUsersPaginatorOptions struct { + // The maximum number of users that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListUsersPaginator is a paginator for ListUsers +type ListUsersPaginator struct { + options ListUsersPaginatorOptions + client ListUsersAPIClient + params *ListUsersInput + nextToken *string + firstPage bool +} + +// NewListUsersPaginator returns a new ListUsersPaginator +func NewListUsersPaginator(client ListUsersAPIClient, params *ListUsersInput, optFns ...func(*ListUsersPaginatorOptions)) *ListUsersPaginator { + if params == nil { + params = &ListUsersInput{} + } + + options := ListUsersPaginatorOptions{} + if params.Limit != nil { + options.Limit = *params.Limit + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListUsersPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.PaginationToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListUsersPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListUsers page. +func (p *ListUsersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListUsersOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.PaginationToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.Limit = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListUsers(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.PaginationToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListUsersAPIClient is a client that implements the ListUsers operation. +type ListUsersAPIClient interface { + ListUsers(context.Context, *ListUsersInput, ...func(*Options)) (*ListUsersOutput, error) +} + +var _ ListUsersAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListUsers(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListUsers", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsersInGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsersInGroup.go new file mode 100644 index 00000000..25734ca0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListUsersInGroup.go @@ -0,0 +1,294 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool ID and a group name, returns a list of users in the group. +// For more information about user pool groups, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) ListUsersInGroup(ctx context.Context, params *ListUsersInGroupInput, optFns ...func(*Options)) (*ListUsersInGroupOutput, error) { + if params == nil { + params = &ListUsersInGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListUsersInGroup", params, optFns, c.addOperationListUsersInGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListUsersInGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListUsersInGroupInput struct { + + // The name of the group that you want to query for user membership. + // + // This member is required. + GroupName *string + + // The ID of the user pool where you want to view the membership of the requested + // group. + // + // This member is required. + UserPoolId *string + + // The maximum number of groups that you want Amazon Cognito to return in the + // response. + Limit *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type ListUsersInGroupOutput struct { + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // An array of users who are members in the group, and their attributes. + Users []types.UserType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListUsersInGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListUsersInGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListUsersInGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListUsersInGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListUsersInGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListUsersInGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +// ListUsersInGroupPaginatorOptions is the paginator options for ListUsersInGroup +type ListUsersInGroupPaginatorOptions struct { + // The maximum number of groups that you want Amazon Cognito to return in the + // response. + Limit int32 + + // Set to true if pagination should stop if the service returns a pagination token + // that matches the most recent token provided to the service. + StopOnDuplicateToken bool +} + +// ListUsersInGroupPaginator is a paginator for ListUsersInGroup +type ListUsersInGroupPaginator struct { + options ListUsersInGroupPaginatorOptions + client ListUsersInGroupAPIClient + params *ListUsersInGroupInput + nextToken *string + firstPage bool +} + +// NewListUsersInGroupPaginator returns a new ListUsersInGroupPaginator +func NewListUsersInGroupPaginator(client ListUsersInGroupAPIClient, params *ListUsersInGroupInput, optFns ...func(*ListUsersInGroupPaginatorOptions)) *ListUsersInGroupPaginator { + if params == nil { + params = &ListUsersInGroupInput{} + } + + options := ListUsersInGroupPaginatorOptions{} + if params.Limit != nil { + options.Limit = *params.Limit + } + + for _, fn := range optFns { + fn(&options) + } + + return &ListUsersInGroupPaginator{ + options: options, + client: client, + params: params, + firstPage: true, + nextToken: params.NextToken, + } +} + +// HasMorePages returns a boolean indicating whether more pages are available +func (p *ListUsersInGroupPaginator) HasMorePages() bool { + return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) +} + +// NextPage retrieves the next ListUsersInGroup page. +func (p *ListUsersInGroupPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListUsersInGroupOutput, error) { + if !p.HasMorePages() { + return nil, fmt.Errorf("no more pages available") + } + + params := *p.params + params.NextToken = p.nextToken + + var limit *int32 + if p.options.Limit > 0 { + limit = &p.options.Limit + } + params.Limit = limit + + optFns = append([]func(*Options){ + addIsPaginatorUserAgent, + }, optFns...) + result, err := p.client.ListUsersInGroup(ctx, ¶ms, optFns...) + if err != nil { + return nil, err + } + p.firstPage = false + + prevToken := p.nextToken + p.nextToken = result.NextToken + + if p.options.StopOnDuplicateToken && + prevToken != nil && + p.nextToken != nil && + *prevToken == *p.nextToken { + p.nextToken = nil + } + + return result, nil +} + +// ListUsersInGroupAPIClient is a client that implements the ListUsersInGroup +// operation. +type ListUsersInGroupAPIClient interface { + ListUsersInGroup(context.Context, *ListUsersInGroupInput, ...func(*Options)) (*ListUsersInGroupOutput, error) +} + +var _ ListUsersInGroupAPIClient = (*Client)(nil) + +func newServiceMetadataMiddleware_opListUsersInGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListUsersInGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListWebAuthnCredentials.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListWebAuthnCredentials.go new file mode 100644 index 00000000..c9a07cba --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ListWebAuthnCredentials.go @@ -0,0 +1,189 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Generates a list of the currently signed-in user's registered passkey, or +// WebAuthn, credentials. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) ListWebAuthnCredentials(ctx context.Context, params *ListWebAuthnCredentialsInput, optFns ...func(*Options)) (*ListWebAuthnCredentialsOutput, error) { + if params == nil { + params = &ListWebAuthnCredentialsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ListWebAuthnCredentials", params, optFns, c.addOperationListWebAuthnCredentialsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ListWebAuthnCredentialsOutput) + out.ResultMetadata = metadata + return out, nil +} + +type ListWebAuthnCredentialsInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The maximum number of the user's passkey credentials that you want to return. + MaxResults *int32 + + // This API operation returns a limited number of results. The pagination token is + // an identifier that you can present in an additional API request with the same + // parameters. When you include the pagination token, Amazon Cognito returns the + // next set of items after the current list. Subsequent requests return a new + // pagination token. By use of this token, you can paginate through the full list + // of items. + NextToken *string + + noSmithyDocumentSerde +} + +type ListWebAuthnCredentialsOutput struct { + + // A list of registered passkeys for a user. + // + // This member is required. + Credentials []types.WebAuthnCredentialDescription + + // The identifier that Amazon Cognito returned with the previous request to this + // operation. When you include a pagination token in your request, Amazon Cognito + // returns the next set of items in the list. By use of this token, you can + // paginate through the full list of items. + NextToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationListWebAuthnCredentialsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpListWebAuthnCredentials{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListWebAuthnCredentials{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ListWebAuthnCredentials"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpListWebAuthnCredentialsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListWebAuthnCredentials(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opListWebAuthnCredentials(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ListWebAuthnCredentials", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ResendConfirmationCode.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ResendConfirmationCode.go new file mode 100644 index 00000000..efbc626f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_ResendConfirmationCode.go @@ -0,0 +1,253 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Resends the code that confirms a new account for a user who has signed up in +// your user pool. Amazon Cognito sends confirmation codes to the user attribute in +// the AutoVerifiedAttributes property of your user pool. When you prompt new +// users for the confirmation code, include a "Resend code" option that generates a +// call to this API operation. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) ResendConfirmationCode(ctx context.Context, params *ResendConfirmationCodeInput, optFns ...func(*Options)) (*ResendConfirmationCodeOutput, error) { + if params == nil { + params = &ResendConfirmationCodeInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "ResendConfirmationCode", params, optFns, c.addOperationResendConfirmationCodeMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*ResendConfirmationCodeOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to resend the confirmation code. +type ResendConfirmationCodeInput struct { + + // The ID of the user pool app client where the user signed up. + // + // This member is required. + ClientId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the ResendConfirmationCode API action, Amazon Cognito + // invokes the function that is assigned to the custom message trigger. When Amazon + // Cognito invokes this function, it passes a JSON payload, which the function + // receives as input. This payload contains a clientMetadata attribute, which + // provides the data that you assigned to the ClientMetadata parameter in your + // ResendConfirmationCode request. In your function code in Lambda, you can process + // the clientMetadata value to enhance your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // A keyed-hash message authentication code (HMAC) calculated using the secret key + // of a user pool client and username plus the client ID in the message. For more + // information about SecretHash , see [Computing secret hash values]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + SecretHash *string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + noSmithyDocumentSerde +} + +// The response from the server when Amazon Cognito makes the request to resend a +// confirmation code. +type ResendConfirmationCodeOutput struct { + + // Information about the phone number or email address that Amazon Cognito sent + // the confirmation code to. + CodeDeliveryDetails *types.CodeDeliveryDetailsType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationResendConfirmationCodeMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpResendConfirmationCode{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpResendConfirmationCode{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "ResendConfirmationCode"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpResendConfirmationCodeValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opResendConfirmationCode(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opResendConfirmationCode(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "ResendConfirmationCode", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RespondToAuthChallenge.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RespondToAuthChallenge.go new file mode 100644 index 00000000..24fed865 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RespondToAuthChallenge.go @@ -0,0 +1,522 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Some API operations in a user pool generate a challenge, like a prompt for an +// MFA code, for device authentication that bypasses MFA, or for a custom +// authentication challenge. A RespondToAuthChallenge API request provides the +// answer to that challenge, like a code or a secure remote password (SRP). The +// parameters of a response to an authentication challenge vary with the type of +// challenge. +// +// For more information about custom authentication challenges, see [Custom authentication challenge Lambda triggers]. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Custom authentication challenge Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) RespondToAuthChallenge(ctx context.Context, params *RespondToAuthChallengeInput, optFns ...func(*Options)) (*RespondToAuthChallengeOutput, error) { + if params == nil { + params = &RespondToAuthChallengeInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "RespondToAuthChallenge", params, optFns, c.addOperationRespondToAuthChallengeMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*RespondToAuthChallengeOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The request to respond to an authentication challenge. +type RespondToAuthChallengeInput struct { + + // The name of the challenge that you are responding to. + // + // You can't respond to an ADMIN_NO_SRP_AUTH challenge with this operation. + // + // Possible challenges include the following: + // + // All of the following challenges require USERNAME and, when the app client has a + // client secret, SECRET_HASH in the parameters. + // + // - WEB_AUTHN : Respond to the challenge with the results of a successful + // authentication with a WebAuthn authenticator, or passkey. Examples of WebAuthn + // authenticators include biometric devices and security keys. + // + // - PASSWORD : Respond with USER_PASSWORD_AUTH parameters: USERNAME (required), + // PASSWORD (required), SECRET_HASH (required if the app client is configured + // with a client secret), DEVICE_KEY . + // + // - PASSWORD_SRP : Respond with USER_SRP_AUTH parameters: USERNAME (required), + // SRP_A (required), SECRET_HASH (required if the app client is configured with a + // client secret), DEVICE_KEY . + // + // - SELECT_CHALLENGE : Respond to the challenge with USERNAME and an ANSWER that + // matches one of the challenge types in the AvailableChallenges response + // parameter. + // + // - SMS_MFA : Respond with an SMS_MFA_CODE that your user pool delivered in an + // SMS message. + // + // - EMAIL_OTP : Respond with an EMAIL_OTP_CODE that your user pool delivered in + // an email message. + // + // - PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP calculations. + // + // - CUSTOM_CHALLENGE : This is returned if your custom authentication flow + // determines that the user should pass another challenge before tokens are issued. + // The parameters of the challenge are determined by your Lambda function. + // + // - DEVICE_SRP_AUTH : Respond with the initial parameters of device SRP + // authentication. For more information, see [Signing in with a device]. + // + // - DEVICE_PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP + // calculations. For more information, see [Signing in with a device]. + // + // - NEW_PASSWORD_REQUIRED : For users who are required to change their passwords + // after successful first login. Respond to this challenge with NEW_PASSWORD and + // any required attributes that Amazon Cognito returned in the requiredAttributes + // parameter. You can also set values for attributes that aren't required by your + // user pool and that your app client can write. + // + // Amazon Cognito only returns this challenge for users who have temporary + // passwords. When you create passwordless users, you must provide values for all + // required attributes. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // - MFA_SETUP : For users who are required to setup an MFA factor before they + // can sign in. The MFA types activated for the user pool will be listed in the + // challenge parameters MFAS_CAN_SETUP value. + // + // To set up time-based one-time password (TOTP) MFA, use the session returned in + // this challenge from InitiateAuth or AdminInitiateAuth as an input to + // AssociateSoftwareToken . Then, use the session returned by VerifySoftwareToken + // as an input to RespondToAuthChallenge or AdminRespondToAuthChallenge with + // challenge name MFA_SETUP to complete sign-in. + // + // To set up SMS or email MFA, collect a phone_number or email attribute for the + // user. Then restart the authentication flow with an InitiateAuth or + // AdminInitiateAuth request. + // + // [Signing in with a device]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-signing-in-with-a-device + // + // This member is required. + ChallengeName types.ChallengeNameType + + // The ID of the app client where the user is signing in. + // + // This member is required. + ClientId *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // The responses to the challenge that you received in the previous request. Each + // challenge has its own required response parameters. The following examples are + // partial JSON request bodies that highlight challenge-response parameters. + // + // You must provide a SECRET_HASH parameter in all challenge responses to an app + // client that has a client secret. Include a DEVICE_KEY for device authentication. + // + // SELECT_CHALLENGE "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { + // "USERNAME": "[username]", "ANSWER": "[Challenge name]"} + // + // Available challenges are PASSWORD , PASSWORD_SRP , EMAIL_OTP , SMS_OTP , and + // WEB_AUTHN . + // + // Complete authentication in the SELECT_CHALLENGE response for PASSWORD , + // PASSWORD_SRP , and WEB_AUTHN : + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "WEB_AUTHN", "USERNAME": "[username]", "CREDENTIAL": + // "[AuthenticationResponseJSON]"} + // + // See [AuthenticationResponseJSON]. + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "PASSWORD", "USERNAME": "[username]", "PASSWORD": "[password]"} + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "PASSWORD_SRP", "USERNAME": "[username]", "SRP_A": "[SRP_A]"} + // + // For SMS_OTP and EMAIL_OTP , respond with the username and answer. Your user pool + // will send a code for the user to submit in the next challenge response. + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "SMS_OTP", "USERNAME": "[username]"} + // + // - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": + // "EMAIL_OTP", "USERNAME": "[username]"} + // + // SMS_OTP "ChallengeName": "SMS_OTP", "ChallengeResponses": {"SMS_OTP_CODE": + // "[code]", "USERNAME": "[username]"} + // + // EMAIL_OTP "ChallengeName": "EMAIL_OTP", "ChallengeResponses": + // {"EMAIL_OTP_CODE": "[code]", "USERNAME": "[username]"} + // + // SMS_MFA "ChallengeName": "SMS_MFA", "ChallengeResponses": {"SMS_MFA_CODE": + // "[code]", "USERNAME": "[username]"} + // + // PASSWORD_VERIFIER This challenge response is part of the SRP flow. Amazon + // Cognito requires that your application respond to this challenge within a few + // seconds. When the response time exceeds this period, your user pool returns a + // NotAuthorizedException error. + // + // "ChallengeName": "PASSWORD_VERIFIER", "ChallengeResponses": + // {"PASSWORD_CLAIM_SIGNATURE": "[claim_signature]", "PASSWORD_CLAIM_SECRET_BLOCK": + // "[secret_block]", "TIMESTAMP": [timestamp], "USERNAME": "[username]"} + // + // Add "DEVICE_KEY" when you sign in with a remembered device. + // + // CUSTOM_CHALLENGE "ChallengeName": "CUSTOM_CHALLENGE", "ChallengeResponses": + // {"USERNAME": "[username]", "ANSWER": "[challenge_answer]"} + // + // Add "DEVICE_KEY" when you sign in with a remembered device. + // + // NEW_PASSWORD_REQUIRED "ChallengeName": "NEW_PASSWORD_REQUIRED", + // "ChallengeResponses": {"NEW_PASSWORD": "[new_password]", "USERNAME": + // "[username]"} + // + // To set any required attributes that InitiateAuth returned in an + // requiredAttributes parameter, add "userAttributes.[attribute_name]": + // "[attribute_value]" . This parameter can also set values for writable attributes + // that aren't required by your user pool. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // SOFTWARE_TOKEN_MFA "ChallengeName": "SOFTWARE_TOKEN_MFA", "ChallengeResponses": + // {"USERNAME": "[username]", "SOFTWARE_TOKEN_MFA_CODE": [authenticator_code]} + // + // DEVICE_SRP_AUTH "ChallengeName": "DEVICE_SRP_AUTH", "ChallengeResponses": + // {"USERNAME": "[username]", "DEVICE_KEY": "[device_key]", "SRP_A": "[srp_a]"} + // + // DEVICE_PASSWORD_VERIFIER "ChallengeName": "DEVICE_PASSWORD_VERIFIER", + // "ChallengeResponses": {"DEVICE_KEY": "[device_key]", "PASSWORD_CLAIM_SIGNATURE": + // "[claim_signature]", "PASSWORD_CLAIM_SECRET_BLOCK": "[secret_block]", + // "TIMESTAMP": [timestamp], "USERNAME": "[username]"} + // + // MFA_SETUP "ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": + // "[username]"}, "SESSION": "[Session ID from VerifySoftwareToken]" + // + // SELECT_MFA_TYPE "ChallengeName": "SELECT_MFA_TYPE", "ChallengeResponses": + // {"USERNAME": "[username]", "ANSWER": "[SMS_MFA or SOFTWARE_TOKEN_MFA]"} + // + // For more information about SECRET_HASH , see [Computing secret hash values]. For information about DEVICE_KEY + // , see [Working with user devices in your user pool]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + // [AuthenticationResponseJSON]: https://www.w3.org/TR/WebAuthn-3/#dictdef-authenticationresponsejson + // [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + ChallengeResponses map[string]string + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the RespondToAuthChallenge API action, Amazon Cognito + // invokes any functions that are assigned to the following triggers: post + // authentication, pre token generation, define auth challenge, create auth + // challenge, and verify auth challenge. When Amazon Cognito invokes any of these + // functions, it passes a JSON payload, which the function receives as input. This + // payload contains a clientMetadata attribute, which provides the data that you + // assigned to the ClientMetadata parameter in your RespondToAuthChallenge request. + // In your function code in Lambda, you can process the clientMetadata value to + // enhance your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // The session identifier that maintains the state of authentication requests and + // challenge responses. If an AdminInitiateAuth or AdminRespondToAuthChallenge API + // request results in a determination that your application must pass another + // challenge, Amazon Cognito returns a session with other challenge parameters. + // Send this session identifier, unmodified, to the next + // AdminRespondToAuthChallenge request. + Session *string + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + noSmithyDocumentSerde +} + +// The response to respond to the authentication challenge. +type RespondToAuthChallengeOutput struct { + + // The outcome of a successful authentication process. After your application has + // passed all challenges, Amazon Cognito returns an AuthenticationResult with the + // JSON web tokens (JWTs) that indicate successful sign-in. + AuthenticationResult *types.AuthenticationResultType + + // The name of the next challenge that you must respond to. + // + // Possible challenges include the following: + // + // All of the following challenges require USERNAME and, when the app client has a + // client secret, SECRET_HASH in the parameters. + // + // - WEB_AUTHN : Respond to the challenge with the results of a successful + // authentication with a WebAuthn authenticator, or passkey. Examples of WebAuthn + // authenticators include biometric devices and security keys. + // + // - PASSWORD : Respond with USER_PASSWORD_AUTH parameters: USERNAME (required), + // PASSWORD (required), SECRET_HASH (required if the app client is configured + // with a client secret), DEVICE_KEY . + // + // - PASSWORD_SRP : Respond with USER_SRP_AUTH parameters: USERNAME (required), + // SRP_A (required), SECRET_HASH (required if the app client is configured with a + // client secret), DEVICE_KEY . + // + // - SELECT_CHALLENGE : Respond to the challenge with USERNAME and an ANSWER that + // matches one of the challenge types in the AvailableChallenges response + // parameter. + // + // - SMS_MFA : Respond with an SMS_MFA_CODE that your user pool delivered in an + // SMS message. + // + // - EMAIL_OTP : Respond with an EMAIL_OTP_CODE that your user pool delivered in + // an email message. + // + // - PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP calculations. + // + // - CUSTOM_CHALLENGE : This is returned if your custom authentication flow + // determines that the user should pass another challenge before tokens are issued. + // The parameters of the challenge are determined by your Lambda function. + // + // - DEVICE_SRP_AUTH : Respond with the initial parameters of device SRP + // authentication. For more information, see [Signing in with a device]. + // + // - DEVICE_PASSWORD_VERIFIER : Respond with PASSWORD_CLAIM_SIGNATURE , + // PASSWORD_CLAIM_SECRET_BLOCK , and TIMESTAMP after client-side SRP + // calculations. For more information, see [Signing in with a device]. + // + // - NEW_PASSWORD_REQUIRED : For users who are required to change their passwords + // after successful first login. Respond to this challenge with NEW_PASSWORD and + // any required attributes that Amazon Cognito returned in the requiredAttributes + // parameter. You can also set values for attributes that aren't required by your + // user pool and that your app client can write. + // + // Amazon Cognito only returns this challenge for users who have temporary + // passwords. When you create passwordless users, you must provide values for all + // required attributes. + // + // In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required + // attribute that already has a value. In AdminRespondToAuthChallenge or + // RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned + // in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or + // UpdateUserAttributes API operation to modify the value of any additional + // attributes. + // + // - MFA_SETUP : For users who are required to setup an MFA factor before they + // can sign in. The MFA types activated for the user pool will be listed in the + // challenge parameters MFAS_CAN_SETUP value. + // + // To set up time-based one-time password (TOTP) MFA, use the session returned in + // this challenge from InitiateAuth or AdminInitiateAuth as an input to + // AssociateSoftwareToken . Then, use the session returned by VerifySoftwareToken + // as an input to RespondToAuthChallenge or AdminRespondToAuthChallenge with + // challenge name MFA_SETUP to complete sign-in. + // + // To set up SMS or email MFA, collect a phone_number or email attribute for the + // user. Then restart the authentication flow with an InitiateAuth or + // AdminInitiateAuth request. + // + // [Signing in with a device]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-signing-in-with-a-device + ChallengeName types.ChallengeNameType + + // The parameters that define your response to the next challenge. + ChallengeParameters map[string]string + + // The session identifier that maintains the state of authentication requests and + // challenge responses. If an InitiateAuth or RespondToAuthChallenge API request + // results in a determination that your application must pass another challenge, + // Amazon Cognito returns a session with other challenge parameters. Send this + // session identifier, unmodified, to the next RespondToAuthChallenge request. + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationRespondToAuthChallengeMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpRespondToAuthChallenge{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRespondToAuthChallenge{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "RespondToAuthChallenge"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpRespondToAuthChallengeValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRespondToAuthChallenge(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opRespondToAuthChallenge(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "RespondToAuthChallenge", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RevokeToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RevokeToken.go new file mode 100644 index 00000000..af16915d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_RevokeToken.go @@ -0,0 +1,171 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Revokes all of the access tokens generated by, and at the same time as, the +// specified refresh token. After a token is revoked, you can't use the revoked +// token to access Amazon Cognito user APIs, or to authorize access to your +// resource server. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) RevokeToken(ctx context.Context, params *RevokeTokenInput, optFns ...func(*Options)) (*RevokeTokenOutput, error) { + if params == nil { + params = &RevokeTokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "RevokeToken", params, optFns, c.addOperationRevokeTokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*RevokeTokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +type RevokeTokenInput struct { + + // The ID of the app client where the token that you want to revoke was issued. + // + // This member is required. + ClientId *string + + // The refresh token that you want to revoke. + // + // This member is required. + Token *string + + // The client secret of the requested app client, if the client has a secret. + ClientSecret *string + + noSmithyDocumentSerde +} + +type RevokeTokenOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationRevokeTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpRevokeToken{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRevokeToken{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "RevokeToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpRevokeTokenValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRevokeToken(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opRevokeToken(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "RevokeToken", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetLogDeliveryConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetLogDeliveryConfiguration.go new file mode 100644 index 00000000..5196fd1e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetLogDeliveryConfiguration.go @@ -0,0 +1,169 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Sets up or modifies the logging configuration of a user pool. User pools can +// export user notification logs and, when threat protection is active, +// user-activity logs. For more information, see [Exporting user pool logs]. +// +// [Exporting user pool logs]: https://docs.aws.amazon.com/cognito/latest/developerguide/exporting-quotas-and-usage.html +func (c *Client) SetLogDeliveryConfiguration(ctx context.Context, params *SetLogDeliveryConfigurationInput, optFns ...func(*Options)) (*SetLogDeliveryConfigurationOutput, error) { + if params == nil { + params = &SetLogDeliveryConfigurationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SetLogDeliveryConfiguration", params, optFns, c.addOperationSetLogDeliveryConfigurationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SetLogDeliveryConfigurationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type SetLogDeliveryConfigurationInput struct { + + // A collection of the logging configurations for a user pool. + // + // This member is required. + LogConfigurations []types.LogConfigurationType + + // The ID of the user pool where you want to configure logging. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +type SetLogDeliveryConfigurationOutput struct { + + // The logging configuration that you applied to the requested user pool. + LogDeliveryConfiguration *types.LogDeliveryConfigurationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSetLogDeliveryConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetLogDeliveryConfiguration{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSetLogDeliveryConfiguration{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetLogDeliveryConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSetLogDeliveryConfigurationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetLogDeliveryConfiguration(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSetLogDeliveryConfiguration(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SetLogDeliveryConfiguration", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetRiskConfiguration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetRiskConfiguration.go new file mode 100644 index 00000000..1108232a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetRiskConfiguration.go @@ -0,0 +1,208 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Configures threat protection for a user pool or app client. Sets configuration +// for the following. +// +// - Responses to risks with adaptive authentication +// +// - Responses to vulnerable passwords with compromised-credentials detection +// +// - Notifications to users who have had risky activity detected +// +// - IP-address denylist and allowlist +// +// To set the risk configuration for the user pool to defaults, send this request +// with only the UserPoolId parameter. To reset the threat protection settings of +// an app client to be inherited from the user pool, send UserPoolId and ClientId +// parameters only. To change threat protection to audit-only or off, update the +// value of UserPoolAddOns in an UpdateUserPool request. To activate this setting, +// your user pool must be on the [Plus tier]. +// +// [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html +func (c *Client) SetRiskConfiguration(ctx context.Context, params *SetRiskConfigurationInput, optFns ...func(*Options)) (*SetRiskConfigurationOutput, error) { + if params == nil { + params = &SetRiskConfigurationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SetRiskConfiguration", params, optFns, c.addOperationSetRiskConfigurationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SetRiskConfigurationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type SetRiskConfigurationInput struct { + + // The ID of the user pool where you want to set a risk configuration. If you + // include UserPoolId in your request, don't include ClientId . When the client ID + // is null, the same risk configuration is applied to all the clients in the + // userPool. When you include both ClientId and UserPoolId , Amazon Cognito maps + // the configuration to the app client only. + // + // This member is required. + UserPoolId *string + + // The settings for automated responses and notification templates for adaptive + // authentication with threat protection. + AccountTakeoverRiskConfiguration *types.AccountTakeoverRiskConfigurationType + + // The ID of the app client where you want to set a risk configuration. If ClientId + // is null, then the risk configuration is mapped to UserPoolId . When the client + // ID is null, the same risk configuration is applied to all the clients in the + // userPool. + // + // When you include a ClientId parameter, Amazon Cognito maps the configuration to + // the app client. When you include both ClientId and UserPoolId , Amazon Cognito + // maps the configuration to the app client only. + ClientId *string + + // The configuration of automated reactions to detected compromised credentials. + // Includes settings for blocking future sign-in requests and for the types of + // password-submission events you want to monitor. + CompromisedCredentialsRiskConfiguration *types.CompromisedCredentialsRiskConfigurationType + + // A set of IP-address overrides to threat protection. You can set up IP-address + // always-block and always-allow lists. + RiskExceptionConfiguration *types.RiskExceptionConfigurationType + + noSmithyDocumentSerde +} + +type SetRiskConfigurationOutput struct { + + // The API response that contains the risk configuration that you set and the + // timestamp of the most recent change. + // + // This member is required. + RiskConfiguration *types.RiskConfigurationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSetRiskConfigurationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetRiskConfiguration{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSetRiskConfiguration{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetRiskConfiguration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSetRiskConfigurationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetRiskConfiguration(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSetRiskConfiguration(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SetRiskConfiguration", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUICustomization.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUICustomization.go new file mode 100644 index 00000000..c8a13f28 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUICustomization.go @@ -0,0 +1,197 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Configures UI branding settings for domains with the hosted UI (classic) +// branding version. Your user pool must have a domain. Configure a domain with . +// +// Set the default configuration for all clients with a ClientId of ALL . When the +// ClientId value is an app client ID, the settings you pass in this request apply +// to that app client and override the default ALL configuration. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) SetUICustomization(ctx context.Context, params *SetUICustomizationInput, optFns ...func(*Options)) (*SetUICustomizationOutput, error) { + if params == nil { + params = &SetUICustomizationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SetUICustomization", params, optFns, c.addOperationSetUICustomizationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SetUICustomizationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type SetUICustomizationInput struct { + + // The ID of the user pool where you want to apply branding to the classic hosted + // UI. + // + // This member is required. + UserPoolId *string + + // A plaintext CSS file that contains the custom fields that you want to apply to + // your user pool or app client. To download a template, go to the Amazon Cognito + // console. Navigate to your user pool App clients tab, select Login pages, edit + // Hosted UI (classic) style, and select the link to CSS template.css . + CSS *string + + // The ID of the app client that you want to customize. To apply a default style + // to all app clients not configured with client-level branding, set this parameter + // value to ALL . + ClientId *string + + // The image that you want to set as your login in the classic hosted UI, as a + // Base64-formatted binary object. + ImageFile []byte + + noSmithyDocumentSerde +} + +type SetUICustomizationOutput struct { + + // Information about the hosted UI branding that you applied. + // + // This member is required. + UICustomization *types.UICustomizationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSetUICustomizationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetUICustomization{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSetUICustomization{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetUICustomization"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSetUICustomizationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetUICustomization(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSetUICustomization(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SetUICustomization", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserMFAPreference.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserMFAPreference.go new file mode 100644 index 00000000..9d48453d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserMFAPreference.go @@ -0,0 +1,191 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Set the user's multi-factor authentication (MFA) method preference, including +// which MFA factors are activated and if any are preferred. Only one factor can be +// set as preferred. The preferred MFA factor will be used to authenticate a user +// if multiple factors are activated. If multiple options are activated and no +// preference is set, a challenge to choose an MFA option will be returned during +// sign-in. If an MFA type is activated for a user, the user will be prompted for +// MFA during all sign-in attempts unless device tracking is turned on and the +// device has been trusted. If you want MFA to be applied selectively based on the +// assessed risk level of sign-in attempts, deactivate MFA for users and turn on +// Adaptive Authentication for the user pool. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) SetUserMFAPreference(ctx context.Context, params *SetUserMFAPreferenceInput, optFns ...func(*Options)) (*SetUserMFAPreferenceOutput, error) { + if params == nil { + params = &SetUserMFAPreferenceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SetUserMFAPreference", params, optFns, c.addOperationSetUserMFAPreferenceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SetUserMFAPreferenceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type SetUserMFAPreferenceInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // User preferences for email message MFA. Activates or deactivates email MFA and + // sets it as the preferred MFA method when multiple methods are available. To + // activate this setting, your user pool must be in the [Essentials tier]or higher. + // + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + EmailMfaSettings *types.EmailMfaSettingsType + + // User preferences for SMS message MFA. Activates or deactivates SMS MFA and sets + // it as the preferred MFA method when multiple methods are available. + SMSMfaSettings *types.SMSMfaSettingsType + + // User preferences for time-based one-time password (TOTP) MFA. Activates or + // deactivates TOTP MFA and sets it as the preferred MFA method when multiple + // methods are available. Users must register a TOTP authenticator before they set + // this as their preferred MFA method. + SoftwareTokenMfaSettings *types.SoftwareTokenMfaSettingsType + + noSmithyDocumentSerde +} + +type SetUserMFAPreferenceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSetUserMFAPreferenceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetUserMFAPreference{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSetUserMFAPreference{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetUserMFAPreference"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSetUserMFAPreferenceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetUserMFAPreference(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSetUserMFAPreference(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SetUserMFAPreference", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserPoolMfaConfig.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserPoolMfaConfig.go new file mode 100644 index 00000000..21ccd077 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserPoolMfaConfig.go @@ -0,0 +1,247 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Sets user pool multi-factor authentication (MFA) and passkey configuration. For +// more information about user pool MFA, see [Adding MFA]. For more information about WebAuthn +// passkeys see [Authentication flows]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Adding MFA]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Authentication flows]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html#amazon-cognito-user-pools-authentication-flow-methods-passkey +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) SetUserPoolMfaConfig(ctx context.Context, params *SetUserPoolMfaConfigInput, optFns ...func(*Options)) (*SetUserPoolMfaConfigOutput, error) { + if params == nil { + params = &SetUserPoolMfaConfigInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SetUserPoolMfaConfig", params, optFns, c.addOperationSetUserPoolMfaConfigMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SetUserPoolMfaConfigOutput) + out.ResultMetadata = metadata + return out, nil +} + +type SetUserPoolMfaConfigInput struct { + + // The user pool ID. + // + // This member is required. + UserPoolId *string + + // Sets configuration for user pool email message MFA and sign-in with one-time + // passwords (OTPs). Includes the subject and body of the email message template + // for sign-in and MFA messages. To activate this setting, your user pool must be + // in the [Essentials tier]or higher. + // + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + EmailMfaConfiguration *types.EmailMfaConfigType + + // Sets multi-factor authentication (MFA) to be on, off, or optional. When ON , all + // users must set up MFA before they can sign in. When OPTIONAL , your application + // must make a client-side determination of whether a user wants to register an MFA + // device. For user pools with adaptive authentication with threat protection, + // choose OPTIONAL . + // + // When MfaConfiguration is OPTIONAL , managed login doesn't automatically prompt + // users to set up MFA. Amazon Cognito generates MFA prompts in API responses and + // in managed login for users who have chosen and configured a preferred MFA + // factor. + MfaConfiguration types.UserPoolMfaType + + // Configures user pool SMS messages for MFA. Sets the message template and the + // SMS message sending configuration for Amazon SNS. + SmsMfaConfiguration *types.SmsMfaConfigType + + // Configures a user pool for time-based one-time password (TOTP) MFA. Enables or + // disables TOTP. + SoftwareTokenMfaConfiguration *types.SoftwareTokenMfaConfigType + + // The configuration of your user pool for passkey, or WebAuthn, authentication + // and registration. You can set this configuration independent of the MFA + // configuration options in this operation. + WebAuthnConfiguration *types.WebAuthnConfigurationType + + noSmithyDocumentSerde +} + +type SetUserPoolMfaConfigOutput struct { + + // Shows configuration for user pool email message MFA and sign-in with one-time + // passwords (OTPs). Includes the subject and body of the email message template + // for sign-in and MFA messages. To activate this setting, your user pool must be + // in the [Essentials tier]or higher. + // + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + EmailMfaConfiguration *types.EmailMfaConfigType + + // Displays multi-factor authentication (MFA) as on, off, or optional. When ON , + // all users must set up MFA before they can sign in. When OPTIONAL , your + // application must make a client-side determination of whether a user wants to + // register an MFA device. For user pools with adaptive authentication with threat + // protection, choose OPTIONAL . + // + // When MfaConfiguration is OPTIONAL , managed login doesn't automatically prompt + // users to set up MFA. Amazon Cognito generates MFA prompts in API responses and + // in managed login for users who have chosen and configured a preferred MFA + // factor. + MfaConfiguration types.UserPoolMfaType + + // Shows user pool SMS message configuration for MFA and sign-in with SMS-message + // OTPs. Includes the message template and the SMS message sending configuration + // for Amazon SNS. + SmsMfaConfiguration *types.SmsMfaConfigType + + // Shows user pool configuration for time-based one-time password (TOTP) MFA. + // Includes TOTP enabled or disabled state. + SoftwareTokenMfaConfiguration *types.SoftwareTokenMfaConfigType + + // The configuration of your user pool for passkey, or WebAuthn, sign-in with + // authenticators like biometric and security-key devices. Includes relying-party + // configuration and settings for user-verification requirements. + WebAuthnConfiguration *types.WebAuthnConfigurationType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSetUserPoolMfaConfigMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetUserPoolMfaConfig{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSetUserPoolMfaConfig{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetUserPoolMfaConfig"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSetUserPoolMfaConfigValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetUserPoolMfaConfig(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSetUserPoolMfaConfig(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SetUserPoolMfaConfig", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserSettings.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserSettings.go new file mode 100644 index 00000000..e675a8fc --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SetUserSettings.go @@ -0,0 +1,176 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// This action is no longer supported. You can use it to configure only SMS MFA. +// +// You can't use it to configure time-based one-time password (TOTP) software token +// or email MFA. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) SetUserSettings(ctx context.Context, params *SetUserSettingsInput, optFns ...func(*Options)) (*SetUserSettingsOutput, error) { + if params == nil { + params = &SetUserSettingsInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SetUserSettings", params, optFns, c.addOperationSetUserSettingsMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SetUserSettingsOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to set user settings. +type SetUserSettingsInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // You can use this parameter only to set an SMS configuration that uses SMS for + // delivery. + // + // This member is required. + MFAOptions []types.MFAOptionType + + noSmithyDocumentSerde +} + +// The response from the server for a set user settings request. +type SetUserSettingsOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSetUserSettingsMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSetUserSettings{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSetUserSettings{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SetUserSettings"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSetUserSettingsValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSetUserSettings(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSetUserSettings(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SetUserSettings", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SignUp.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SignUp.go new file mode 100644 index 00000000..ca4f6e88 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_SignUp.go @@ -0,0 +1,304 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Registers a user with an app client and requests a user name, password, and +// user attributes in the user pool. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// You might receive a LimitExceeded exception in response to this request if you +// have exceeded a rate quota for email or SMS messages, and if your user pool +// automatically verifies email addresses or phone numbers. When you get this +// exception in the response, the user is successfully created and is in an +// UNCONFIRMED state. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) SignUp(ctx context.Context, params *SignUpInput, optFns ...func(*Options)) (*SignUpOutput, error) { + if params == nil { + params = &SignUpInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "SignUp", params, optFns, c.addOperationSignUpMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*SignUpOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to register a user. +type SignUpInput struct { + + // The ID of the app client where the user wants to sign up. + // + // This member is required. + ClientId *string + + // The username of the user that you want to sign up. The value of this parameter + // is typically a username, but can be any alias attribute in your user pool. + // + // This member is required. + Username *string + + // Information that supports analytics outcomes with Amazon Pinpoint, including + // the user's endpoint ID. The endpoint ID is a destination for Amazon Pinpoint + // push notifications, for example a device identifier, email address, or phone + // number. + AnalyticsMetadata *types.AnalyticsMetadataType + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action triggers. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the SignUp API action, Amazon Cognito invokes any + // functions that are assigned to the following triggers: pre sign-up, custom + // message, and post confirmation. When Amazon Cognito invokes any of these + // functions, it passes a JSON payload, which the function receives as input. This + // payload contains a clientMetadata attribute, which provides the data that you + // assigned to the ClientMetadata parameter in your SignUp request. In your + // function code in Lambda, you can process the clientMetadata value to enhance + // your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + // The user's proposed password. The password must comply with the [password requirements] of your user + // pool. + // + // Users can sign up without a password when your user pool supports passwordless + // sign-in with email or SMS OTPs. To create a user with no password, omit this + // parameter or submit a blank value. You can only create a passwordless user when + // passwordless sign-in is available. + // + // [password requirements]: https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users-passwords.html + Password *string + + // A keyed-hash message authentication code (HMAC) calculated using the secret key + // of a user pool client and username plus the client ID in the message. For more + // information about SecretHash , see [Computing secret hash values]. + // + // [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash + SecretHash *string + + // An array of name-value pairs representing user attributes. + // + // For custom attributes, include a custom: prefix in the attribute name, for + // example custom:department . + UserAttributes []types.AttributeType + + // Contextual data about your user session like the device fingerprint, IP + // address, or location. Amazon Cognito threat protection evaluates the risk of an + // authentication event based on the context that your app generates and passes to + // Amazon Cognito when it makes API requests. + // + // For more information, see [Collecting data for threat protection in applications]. + // + // [Collecting data for threat protection in applications]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-viewing-threat-protection-app.html + UserContextData *types.UserContextDataType + + // Temporary user attributes that contribute to the outcomes of your pre sign-up + // Lambda trigger. This set of key-value pairs are for custom validation of + // information that you collect from your users but don't need to retain. + // + // Your Lambda function can analyze this additional data and act on it. Your + // function can automatically confirm and verify select users or perform external + // API operations like logging user attributes and validation data to Amazon + // CloudWatch Logs. + // + // For more information about the pre sign-up Lambda trigger, see [Pre sign-up Lambda trigger]. + // + // [Pre sign-up Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html + ValidationData []types.AttributeType + + noSmithyDocumentSerde +} + +// The response from the server for a registration request. +type SignUpOutput struct { + + // Indicates whether the user was automatically confirmed. You can auto-confirm + // users with a [pre sign-up Lambda trigger]. + // + // [pre sign-up Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html + // + // This member is required. + UserConfirmed bool + + // The unique identifier of the new user, for example + // a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 . + // + // This member is required. + UserSub *string + + // In user pools that automatically verify and confirm new users, Amazon Cognito + // sends users a message with a code or link that confirms ownership of the phone + // number or email address that they entered. The CodeDeliveryDetails object is + // information about the delivery destination for that link or code. + CodeDeliveryDetails *types.CodeDeliveryDetailsType + + // A session Id that you can pass to ConfirmSignUp when you want to immediately + // sign in your user with the USER_AUTH flow after they complete sign-up. + Session *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationSignUpMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpSignUp{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSignUp{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "SignUp"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpSignUpValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSignUp(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opSignUp(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "SignUp", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartUserImportJob.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartUserImportJob.go new file mode 100644 index 00000000..6d179b03 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartUserImportJob.go @@ -0,0 +1,173 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Instructs your user pool to start importing users from a CSV file that contains +// their usernames and attributes. For more information about importing users from +// a CSV file, see [Importing users from a CSV file]. +// +// [Importing users from a CSV file]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html +func (c *Client) StartUserImportJob(ctx context.Context, params *StartUserImportJobInput, optFns ...func(*Options)) (*StartUserImportJobOutput, error) { + if params == nil { + params = &StartUserImportJobInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StartUserImportJob", params, optFns, c.addOperationStartUserImportJobMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StartUserImportJobOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to start the user import job. +type StartUserImportJobInput struct { + + // The ID of a user import job that you previously created. + // + // This member is required. + JobId *string + + // The ID of the user pool that you want to start importing users into. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to start the user import +// job. +type StartUserImportJobOutput struct { + + // The details of the user import job. Includes logging destination, status, and + // the Amazon S3 pre-signed URL for CSV upload. + UserImportJob *types.UserImportJobType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStartUserImportJobMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartUserImportJob{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartUserImportJob{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartUserImportJob"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStartUserImportJobValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartUserImportJob(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStartUserImportJob(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StartUserImportJob", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartWebAuthnRegistration.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartWebAuthnRegistration.go new file mode 100644 index 00000000..3b1b4b3f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StartWebAuthnRegistration.go @@ -0,0 +1,167 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Requests credential creation options from your user pool for the currently +// signed-in user. Returns information about the user pool, the user profile, and +// authentication requirements. Users must provide this information in their +// request to enroll your application with their passkey provider. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +func (c *Client) StartWebAuthnRegistration(ctx context.Context, params *StartWebAuthnRegistrationInput, optFns ...func(*Options)) (*StartWebAuthnRegistrationOutput, error) { + if params == nil { + params = &StartWebAuthnRegistrationInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StartWebAuthnRegistration", params, optFns, c.addOperationStartWebAuthnRegistrationMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StartWebAuthnRegistrationOutput) + out.ResultMetadata = metadata + return out, nil +} + +type StartWebAuthnRegistrationInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + noSmithyDocumentSerde +} + +type StartWebAuthnRegistrationOutput struct { + + // The information that a user can provide in their request to register with their + // passkey provider. + // + // This member is required. + CredentialCreationOptions document.Interface + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStartWebAuthnRegistrationMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartWebAuthnRegistration{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartWebAuthnRegistration{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StartWebAuthnRegistration"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStartWebAuthnRegistrationValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartWebAuthnRegistration(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStartWebAuthnRegistration(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StartWebAuthnRegistration", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StopUserImportJob.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StopUserImportJob.go new file mode 100644 index 00000000..bca0b8e1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_StopUserImportJob.go @@ -0,0 +1,173 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Instructs your user pool to stop a running job that's importing users from a +// CSV file that contains their usernames and attributes. For more information +// about importing users from a CSV file, see [Importing users from a CSV file]. +// +// [Importing users from a CSV file]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html +func (c *Client) StopUserImportJob(ctx context.Context, params *StopUserImportJobInput, optFns ...func(*Options)) (*StopUserImportJobOutput, error) { + if params == nil { + params = &StopUserImportJobInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "StopUserImportJob", params, optFns, c.addOperationStopUserImportJobMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*StopUserImportJobOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to stop the user import job. +type StopUserImportJobInput struct { + + // The ID of a running user import job. + // + // This member is required. + JobId *string + + // The ID of the user pool that you want to stop. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to stop the user import +// job. +type StopUserImportJobOutput struct { + + // The details of the user import job. Includes logging destination, status, and + // the Amazon S3 pre-signed URL for CSV upload. + UserImportJob *types.UserImportJobType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationStopUserImportJobMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpStopUserImportJob{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStopUserImportJob{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "StopUserImportJob"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpStopUserImportJobValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStopUserImportJob(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opStopUserImportJob(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "StopUserImportJob", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_TagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_TagResource.go new file mode 100644 index 00000000..c474a580 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_TagResource.go @@ -0,0 +1,177 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Assigns a set of tags to an Amazon Cognito user pool. A tag is a label that you +// can use to categorize and manage user pools in different ways, such as by +// purpose, owner, environment, or other criteria. +// +// Each tag consists of a key and value, both of which you define. A key is a +// general category for more specific values. For example, if you have two versions +// of a user pool, one for testing and another for production, you might assign an +// Environment tag key to both user pools. The value of this key might be Test for +// one user pool, and Production for the other. +// +// Tags are useful for cost tracking and access control. You can activate your +// tags so that they appear on the Billing and Cost Management console, where you +// can track the costs associated with your user pools. In an Identity and Access +// Management policy, you can constrain permissions for user pools based on +// specific tags or tag values. +// +// You can use this action up to 5 times per second, per account. A user pool can +// have as many as 50 tags. +func (c *Client) TagResource(ctx context.Context, params *TagResourceInput, optFns ...func(*Options)) (*TagResourceOutput, error) { + if params == nil { + params = &TagResourceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "TagResource", params, optFns, c.addOperationTagResourceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*TagResourceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type TagResourceInput struct { + + // The Amazon Resource Name (ARN) of the user pool to assign the tags to. + // + // This member is required. + ResourceArn *string + + // An array of tag keys and values that you want to assign to the user pool. + // + // This member is required. + Tags map[string]string + + noSmithyDocumentSerde +} + +type TagResourceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationTagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpTagResource{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpTagResource{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "TagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpTagResourceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "TagResource", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UntagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UntagResource.go new file mode 100644 index 00000000..636711f5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UntagResource.go @@ -0,0 +1,160 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given tag IDs that you previously assigned to a user pool, removes them. +func (c *Client) UntagResource(ctx context.Context, params *UntagResourceInput, optFns ...func(*Options)) (*UntagResourceOutput, error) { + if params == nil { + params = &UntagResourceInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UntagResource", params, optFns, c.addOperationUntagResourceMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UntagResourceOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UntagResourceInput struct { + + // The Amazon Resource Name (ARN) of the user pool that the tags are assigned to. + // + // This member is required. + ResourceArn *string + + // An array of tag keys that you want to remove from the user pool. + // + // This member is required. + TagKeys []string + + noSmithyDocumentSerde +} + +type UntagResourceOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUntagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUntagResource{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUntagResource{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UntagResource"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUntagResourceValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUntagResource(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUntagResource(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UntagResource", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateAuthEventFeedback.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateAuthEventFeedback.go new file mode 100644 index 00000000..b0102b8e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateAuthEventFeedback.go @@ -0,0 +1,205 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Provides the feedback for an authentication event generated by threat +// protection features. The user's response indicates that you think that the event +// either was from a valid user or was an unwanted authentication attempt. This +// feedback improves the risk evaluation decision for the user pool as part of +// Amazon Cognito threat protection. To activate this setting, your user pool must +// be on the [Plus tier]. +// +// This operation requires a FeedbackToken that Amazon Cognito generates and adds +// to notification emails when users have potentially suspicious authentication +// events. Users invoke this operation when they select the link that corresponds +// to {one-click-link-valid} or {one-click-link-invalid} in your notification +// template. Because FeedbackToken is a required parameter, you can' make requests +// to UpdateAuthEventFeedback without the contents of the notification email +// message. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html +func (c *Client) UpdateAuthEventFeedback(ctx context.Context, params *UpdateAuthEventFeedbackInput, optFns ...func(*Options)) (*UpdateAuthEventFeedbackOutput, error) { + if params == nil { + params = &UpdateAuthEventFeedbackInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateAuthEventFeedback", params, optFns, c.addOperationUpdateAuthEventFeedbackMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateAuthEventFeedbackOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateAuthEventFeedbackInput struct { + + // The ID of the authentication event that you want to submit feedback for. + // + // This member is required. + EventId *string + + // The feedback token, an encrypted object generated by Amazon Cognito and passed + // to your user in the notification email message from the event. + // + // This member is required. + FeedbackToken *string + + // Your feedback to the authentication event. When you provide a FeedbackValue + // value of valid , you tell Amazon Cognito that you trust a user session where + // Amazon Cognito has evaluated some level of risk. When you provide a + // FeedbackValue value of invalid , you tell Amazon Cognito that you don't trust a + // user session, or you don't believe that Amazon Cognito evaluated a high-enough + // risk level. + // + // This member is required. + FeedbackValue types.FeedbackValueType + + // The ID of the user pool where you want to update auth event feedback. + // + // This member is required. + UserPoolId *string + + // The name of the user that you want to query or modify. The value of this + // parameter is typically your user's username, but it can be any of their alias + // attributes. If username isn't an alias attribute in your user pool, this value + // must be the sub of a local user or the username of a user from a third-party + // IdP. + // + // This member is required. + Username *string + + noSmithyDocumentSerde +} + +type UpdateAuthEventFeedbackOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateAuthEventFeedbackMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateAuthEventFeedback{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateAuthEventFeedback{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateAuthEventFeedback"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateAuthEventFeedbackValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateAuthEventFeedback(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateAuthEventFeedback(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateAuthEventFeedback", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateDeviceStatus.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateDeviceStatus.go new file mode 100644 index 00000000..aaca78c1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateDeviceStatus.go @@ -0,0 +1,184 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates the status of a the currently signed-in user's device so that it is +// marked as remembered or not remembered for the purpose of device authentication. +// Device authentication is a "remember me" mechanism that silently completes +// sign-in from trusted devices with a device key instead of a user-provided MFA +// code. This operation changes the status of a device without deleting it, so you +// can enable it again later. For more information about device authentication, see +// [Working with devices]. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) UpdateDeviceStatus(ctx context.Context, params *UpdateDeviceStatusInput, optFns ...func(*Options)) (*UpdateDeviceStatusOutput, error) { + if params == nil { + params = &UpdateDeviceStatusInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateDeviceStatus", params, optFns, c.addOperationUpdateDeviceStatusMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateDeviceStatusOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to update the device status. +type UpdateDeviceStatusInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The device key of the device you want to update, for example + // us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 . + // + // This member is required. + DeviceKey *string + + // To enable device authentication with the specified device, set to remembered .To + // disable, set to not_remembered . + DeviceRememberedStatus types.DeviceRememberedStatusType + + noSmithyDocumentSerde +} + +// The response to the request to update the device status. +type UpdateDeviceStatusOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateDeviceStatusMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateDeviceStatus{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateDeviceStatus{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateDeviceStatus"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateDeviceStatusValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateDeviceStatus(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateDeviceStatus(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateDeviceStatus", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateGroup.go new file mode 100644 index 00000000..d0384440 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateGroup.go @@ -0,0 +1,208 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given the name of a user pool group, updates any of the properties for +// precedence, IAM role, or description. For more information about user pool +// groups, see [Adding groups to a user pool]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Adding groups to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) UpdateGroup(ctx context.Context, params *UpdateGroupInput, optFns ...func(*Options)) (*UpdateGroupOutput, error) { + if params == nil { + params = &UpdateGroupInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateGroup", params, optFns, c.addOperationUpdateGroupMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateGroupOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateGroupInput struct { + + // The name of the group that you want to update. + // + // This member is required. + GroupName *string + + // The ID of the user pool that contains the group you want to update. + // + // This member is required. + UserPoolId *string + + // A new description of the existing group. + Description *string + + // A non-negative integer value that specifies the precedence of this group + // relative to the other groups that a user can belong to in the user pool. Zero is + // the highest precedence value. Groups with lower Precedence values take + // precedence over groups with higher or null Precedence values. If a user belongs + // to two or more groups, it is the group with the lowest precedence value whose + // role ARN is given in the user's tokens for the cognito:roles and + // cognito:preferred_role claims. + // + // Two groups can have the same Precedence value. If this happens, neither group + // takes precedence over the other. If two groups with the same Precedence have + // the same role ARN, that role is used in the cognito:preferred_role claim in + // tokens for users in each group. If the two groups have different role ARNs, the + // cognito:preferred_role claim isn't set in users' tokens. + // + // The default Precedence value is null. The maximum Precedence value is 2^31-1 . + Precedence *int32 + + // The Amazon Resource Name (ARN) of an IAM role that you want to associate with + // the group. The role assignment contributes to the cognito:roles and + // cognito:preferred_role claims in group members' tokens. + RoleArn *string + + noSmithyDocumentSerde +} + +type UpdateGroupOutput struct { + + // Contains the updated details of the group, including precedence, IAM role, and + // description. + Group *types.GroupType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateGroup{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateGroup{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateGroup"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateGroupValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateGroup(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateGroup(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateGroup", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateIdentityProvider.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateIdentityProvider.go new file mode 100644 index 00000000..989b79c7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateIdentityProvider.go @@ -0,0 +1,298 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Modifies the configuration and trust relationship between a third-party +// identity provider (IdP) and a user pool. Amazon Cognito accepts sign-in with +// third-party identity providers through managed login and OIDC relying-party +// libraries. For more information, see [Third-party IdP sign-in]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Third-party IdP sign-in]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) UpdateIdentityProvider(ctx context.Context, params *UpdateIdentityProviderInput, optFns ...func(*Options)) (*UpdateIdentityProviderOutput, error) { + if params == nil { + params = &UpdateIdentityProviderInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateIdentityProvider", params, optFns, c.addOperationUpdateIdentityProviderMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateIdentityProviderOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateIdentityProviderInput struct { + + // The name of the IdP that you want to update. You can pass the identity provider + // name in the identity_provider query parameter of requests to the [Authorize endpoint] to silently + // redirect to sign-in with the associated IdP. + // + // [Authorize endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html + // + // This member is required. + ProviderName *string + + // The Id of the user pool where you want to update your IdP. + // + // This member is required. + UserPoolId *string + + // A mapping of IdP attributes to standard and custom user pool attributes. + // Specify a user pool attribute as the key of the key-value pair, and the IdP + // attribute claim name as the value. + AttributeMapping map[string]string + + // An array of IdP identifiers, for example "IdPIdentifiers": [ "MyIdP", "MyIdP2" ] + // . Identifiers are friendly names that you can pass in the idp_identifier query + // parameter of requests to the [Authorize endpoint]to silently redirect to sign-in with the + // associated IdP. Identifiers in a domain format also enable the use of [email-address matching with SAML providers]. + // + // [Authorize endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html + // [email-address matching with SAML providers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managing-saml-idp-naming.html + IdpIdentifiers []string + + // The scopes, URLs, and identifiers for your external identity provider. The + // following examples describe the provider detail keys for each IdP type. These + // values and their schema are subject to change. Social IdP authorize_scopes + // values must match the values listed here. + // + // OpenID Connect (OIDC) Amazon Cognito accepts the following elements when it + // can't discover endpoint URLs from oidc_issuer : attributes_url , authorize_url , + // jwks_uri , token_url . + // + // Create or update request: "ProviderDetails": { "attributes_request_method": + // "GET", "attributes_url": "https://auth.example.com/userInfo", + // "authorize_scopes": "openid profile email", "authorize_url": + // "https://auth.example.com/authorize", "client_id": "1example23456789", + // "client_secret": "provider-app-client-secret", "jwks_uri": + // "https://auth.example.com/.well-known/jwks.json", "oidc_issuer": + // "https://auth.example.com", "token_url": "https://example.com/token" } + // + // Describe response: "ProviderDetails": { "attributes_request_method": "GET", + // "attributes_url": "https://auth.example.com/userInfo", + // "attributes_url_add_attributes": "false", "authorize_scopes": "openid profile + // email", "authorize_url": "https://auth.example.com/authorize", "client_id": + // "1example23456789", "client_secret": "provider-app-client-secret", "jwks_uri": + // "https://auth.example.com/.well-known/jwks.json", "oidc_issuer": + // "https://auth.example.com", "token_url": "https://example.com/token" } + // + // SAML Create or update request with Metadata URL: "ProviderDetails": { + // "IDPInit": "true", "IDPSignout": "true", "EncryptedResponses" : "true", + // "MetadataURL": "https://auth.example.com/sso/saml/metadata", + // "RequestSigningAlgorithm": "rsa-sha256" } + // + // Create or update request with Metadata file: "ProviderDetails": { "IDPInit": + // "true", "IDPSignout": "true", "EncryptedResponses" : "true", "MetadataFile": + // "[metadata XML]", "RequestSigningAlgorithm": "rsa-sha256" } + // + // The value of MetadataFile must be the plaintext metadata document with all + // quote (") characters escaped by backslashes. + // + // Describe response: "ProviderDetails": { "IDPInit": "true", "IDPSignout": + // "true", "EncryptedResponses" : "true", "ActiveEncryptionCertificate": + // "[certificate]", "MetadataURL": "https://auth.example.com/sso/saml/metadata", + // "RequestSigningAlgorithm": "rsa-sha256", "SLORedirectBindingURI": + // "https://auth.example.com/slo/saml", "SSORedirectBindingURI": + // "https://auth.example.com/sso/saml" } + // + // LoginWithAmazon Create or update request: "ProviderDetails": { + // "authorize_scopes": "profile postal_code", "client_id": + // "amzn1.application-oa2-client.1example23456789", "client_secret": + // "provider-app-client-secret" + // + // Describe response: "ProviderDetails": { "attributes_url": + // "https://api.amazon.com/user/profile", "attributes_url_add_attributes": "false", + // "authorize_scopes": "profile postal_code", "authorize_url": + // "https://www.amazon.com/ap/oa", "client_id": + // "amzn1.application-oa2-client.1example23456789", "client_secret": + // "provider-app-client-secret", "token_request_method": "POST", "token_url": + // "https://api.amazon.com/auth/o2/token" } + // + // Google Create or update request: "ProviderDetails": { "authorize_scopes": + // "email profile openid", "client_id": + // "1example23456789.apps.googleusercontent.com", "client_secret": + // "provider-app-client-secret" } + // + // Describe response: "ProviderDetails": { "attributes_url": + // "https://people.googleapis.com/v1/people/me?personFields=", + // "attributes_url_add_attributes": "true", "authorize_scopes": "email profile + // openid", "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth", + // "client_id": "1example23456789.apps.googleusercontent.com", "client_secret": + // "provider-app-client-secret", "oidc_issuer": "https://accounts.google.com", + // "token_request_method": "POST", "token_url": + // "https://www.googleapis.com/oauth2/v4/token" } + // + // SignInWithApple Create or update request: "ProviderDetails": { + // "authorize_scopes": "email name", "client_id": "com.example.cognito", + // "private_key": "1EXAMPLE", "key_id": "2EXAMPLE", "team_id": "3EXAMPLE" } + // + // Describe response: "ProviderDetails": { "attributes_url_add_attributes": + // "false", "authorize_scopes": "email name", "authorize_url": + // "https://appleid.apple.com/auth/authorize", "client_id": "com.example.cognito", + // "key_id": "1EXAMPLE", "oidc_issuer": "https://appleid.apple.com", "team_id": + // "2EXAMPLE", "token_request_method": "POST", "token_url": + // "https://appleid.apple.com/auth/token" } + // + // Facebook Create or update request: "ProviderDetails": { "api_version": "v17.0", + // "authorize_scopes": "public_profile, email", "client_id": "1example23456789", + // "client_secret": "provider-app-client-secret" } + // + // Describe response: "ProviderDetails": { "api_version": "v17.0", + // "attributes_url": "https://graph.facebook.com/v17.0/me?fields=", + // "attributes_url_add_attributes": "true", "authorize_scopes": "public_profile, + // email", "authorize_url": "https://www.facebook.com/v17.0/dialog/oauth", + // "client_id": "1example23456789", "client_secret": "provider-app-client-secret", + // "token_request_method": "GET", "token_url": + // "https://graph.facebook.com/v17.0/oauth/access_token" } + ProviderDetails map[string]string + + noSmithyDocumentSerde +} + +type UpdateIdentityProviderOutput struct { + + // The identity provider details. + // + // This member is required. + IdentityProvider *types.IdentityProviderType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateIdentityProviderMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateIdentityProvider{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateIdentityProvider{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateIdentityProvider"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateIdentityProviderValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateIdentityProvider(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateIdentityProvider(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateIdentityProvider", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateManagedLoginBranding.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateManagedLoginBranding.go new file mode 100644 index 00000000..01cb5581 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateManagedLoginBranding.go @@ -0,0 +1,205 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Configures the branding settings for a user pool style. This operation is the +// programmatic option for the configuration of a style in the branding designer. +// +// Provides values for UI customization in a Settings JSON object and image files +// in an Assets array. +// +// This operation has a 2-megabyte request-size limit and include the CSS settings +// and image assets for your app client. Your branding settings might exceed 2MB in +// size. Amazon Cognito doesn't require that you pass all parameters in one request +// and preserves existing style settings that you don't specify. If your request is +// larger than 2MB, separate it into multiple requests, each with a size smaller +// than the limit. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) UpdateManagedLoginBranding(ctx context.Context, params *UpdateManagedLoginBrandingInput, optFns ...func(*Options)) (*UpdateManagedLoginBrandingOutput, error) { + if params == nil { + params = &UpdateManagedLoginBrandingInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateManagedLoginBranding", params, optFns, c.addOperationUpdateManagedLoginBrandingMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateManagedLoginBrandingOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateManagedLoginBrandingInput struct { + + // An array of image files that you want to apply to roles like backgrounds, + // logos, and icons. Each object must also indicate whether it is for dark mode, + // light mode, or browser-adaptive mode. + Assets []types.AssetType + + // The ID of the managed login branding style that you want to update. + ManagedLoginBrandingId *string + + // A JSON file, encoded as a Document type, with the the settings that you want to + // apply to your style. + Settings document.Interface + + // When true , applies the default branding style options. This option reverts to + // default style options that are managed by Amazon Cognito. You can modify them + // later in the branding designer. + // + // When you specify true for this option, you must also omit values for Settings + // and Assets in the request. + UseCognitoProvidedValues bool + + // The ID of the user pool that contains the managed login branding style that you + // want to update. + UserPoolId *string + + noSmithyDocumentSerde +} + +type UpdateManagedLoginBrandingOutput struct { + + // The details of the branding style that you updated. + ManagedLoginBranding *types.ManagedLoginBrandingType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateManagedLoginBrandingMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateManagedLoginBranding{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateManagedLoginBranding"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateManagedLoginBrandingValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateManagedLoginBranding(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateManagedLoginBranding(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateManagedLoginBranding", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateResourceServer.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateResourceServer.go new file mode 100644 index 00000000..51c6388f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateResourceServer.go @@ -0,0 +1,201 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates the name and scopes of a resource server. All other fields are +// read-only. For more information about resource servers, see [Access control with resource servers]. +// +// If you don't provide a value for an attribute, it is set to the default value. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Access control with resource servers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) UpdateResourceServer(ctx context.Context, params *UpdateResourceServerInput, optFns ...func(*Options)) (*UpdateResourceServerOutput, error) { + if params == nil { + params = &UpdateResourceServerInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateResourceServer", params, optFns, c.addOperationUpdateResourceServerMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateResourceServerOutput) + out.ResultMetadata = metadata + return out, nil +} + +type UpdateResourceServerInput struct { + + // A unique resource server identifier for the resource server. The identifier can + // be an API friendly name like solar-system-data . You can also set an API URL + // like https://solar-system-data-api.example.com as your identifier. + // + // Amazon Cognito represents scopes in the access token in the format + // $resource-server-identifier/$scope . Longer scope-identifier strings increase + // the size of your access tokens. + // + // This member is required. + Identifier *string + + // The updated name of the resource server. + // + // This member is required. + Name *string + + // The ID of the user pool that contains the resource server that you want to + // update. + // + // This member is required. + UserPoolId *string + + // An array of updated custom scope names and descriptions that you want to + // associate with your resource server. + Scopes []types.ResourceServerScopeType + + noSmithyDocumentSerde +} + +type UpdateResourceServerOutput struct { + + // The updated details of the requested resource server. + // + // This member is required. + ResourceServer *types.ResourceServerType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateResourceServerMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateResourceServer{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateResourceServer{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateResourceServer"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateResourceServerValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateResourceServer(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateResourceServer(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateResourceServer", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserAttributes.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserAttributes.go new file mode 100644 index 00000000..e691a744 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserAttributes.go @@ -0,0 +1,245 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates the currently signed-in user's attributes. To delete an attribute from +// the user, submit the attribute in your API request with a blank value. +// +// For custom attributes, you must add a custom: prefix to the attribute name, for +// example custom:department . +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) UpdateUserAttributes(ctx context.Context, params *UpdateUserAttributesInput, optFns ...func(*Options)) (*UpdateUserAttributesOutput, error) { + if params == nil { + params = &UpdateUserAttributesInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateUserAttributes", params, optFns, c.addOperationUpdateUserAttributesMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateUserAttributesOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to update user attributes. +type UpdateUserAttributesInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // An array of name-value pairs representing user attributes. + // + // For custom attributes, you must add a custom: prefix to the attribute name. + // + // If you have set an attribute to require verification before Amazon Cognito + // updates its value, this request doesn’t immediately update the value of that + // attribute. After your user receives and responds to a verification message to + // verify the new value, Amazon Cognito updates the attribute value. Your user can + // sign in and receive messages with the original attribute value until they verify + // the new value. + // + // This member is required. + UserAttributes []types.AttributeType + + // A map of custom key-value pairs that you can provide as input for any custom + // workflows that this action initiates. + // + // You create custom workflows by assigning Lambda functions to user pool + // triggers. When you use the UpdateUserAttributes API action, Amazon Cognito + // invokes the function that is assigned to the custom message trigger. When Amazon + // Cognito invokes this function, it passes a JSON payload, which the function + // receives as input. This payload contains a clientMetadata attribute, which + // provides the data that you assigned to the ClientMetadata parameter in your + // UpdateUserAttributes request. In your function code in Lambda, you can process + // the clientMetadata value to enhance your workflow for your specific needs. + // + // For more information, see [Using Lambda triggers] in the Amazon Cognito Developer Guide. + // + // When you use the ClientMetadata parameter, note that Amazon Cognito won't do + // the following: + // + // - Store the ClientMetadata value. This data is available only to Lambda + // triggers that are assigned to a user pool to support custom workflows. If your + // user pool configuration doesn't include triggers, the ClientMetadata parameter + // serves no purpose. + // + // - Validate the ClientMetadata value. + // + // - Encrypt the ClientMetadata value. Don't send sensitive information in this + // parameter. + // + // [Using Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html + ClientMetadata map[string]string + + noSmithyDocumentSerde +} + +// Represents the response from the server for the request to update user +// attributes. +type UpdateUserAttributesOutput struct { + + // When the attribute-update request includes an email address or phone number + // attribute, Amazon Cognito sends a message to users with a code that confirms + // ownership of the new value that they entered. The CodeDeliveryDetails object is + // information about the delivery destination for that link or code. This behavior + // happens in user pools configured to automatically verify changes to those + // attributes. For more information, see [Verifying when users change their email or phone number]. + // + // [Verifying when users change their email or phone number]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#verifying-when-users-change-their-email-or-phone-number + CodeDeliveryDetailsList []types.CodeDeliveryDetailsType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateUserAttributesMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateUserAttributes{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateUserAttributes{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateUserAttributes"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateUserAttributesValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateUserAttributes(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateUserAttributes(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateUserAttributes", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPool.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPool.go new file mode 100644 index 00000000..ceb36917 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPool.go @@ -0,0 +1,336 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Updates the configuration of a user pool. To avoid setting parameters to Amazon +// Cognito defaults, construct this API request to pass the existing configuration +// of your user pool, modified to include the changes that you want to make. +// +// If you don't provide a value for an attribute, Amazon Cognito sets it to its +// default value. +// +// This action might generate an SMS text message. Starting June 1, 2021, US +// telecom carriers require you to register an origination phone number before you +// can send SMS messages to US phone numbers. If you use SMS text messages in +// Amazon Cognito, you must register a phone number with [Amazon Pinpoint]. Amazon Cognito uses the +// registered number automatically. Otherwise, Amazon Cognito users who must +// receive SMS messages might not be able to sign up, activate their accounts, or +// sign in. +// +// If you have never used SMS text messages with Amazon Cognito or any other +// Amazon Web Services service, Amazon Simple Notification Service might place your +// account in the SMS sandbox. In [sandbox mode], you can send messages only to verified phone +// numbers. After you test your app while in the sandbox environment, you can move +// out of the sandbox and into production. For more information, see [SMS message settings for Amazon Cognito user pools]in the Amazon +// Cognito Developer Guide. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [sandbox mode]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +// [Amazon Pinpoint]: https://console.aws.amazon.com/pinpoint/home/ +func (c *Client) UpdateUserPool(ctx context.Context, params *UpdateUserPoolInput, optFns ...func(*Options)) (*UpdateUserPoolOutput, error) { + if params == nil { + params = &UpdateUserPoolInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateUserPool", params, optFns, c.addOperationUpdateUserPoolMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateUserPoolOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to update the user pool. +type UpdateUserPoolInput struct { + + // The ID of the user pool you want to update. + // + // This member is required. + UserPoolId *string + + // The available verified method a user can use to recover their password when + // they call ForgotPassword . You can use this setting to define a preferred method + // when a user has more than one method available. With this setting, SMS doesn't + // qualify for a valid password recovery mechanism if the user also has SMS + // multi-factor authentication (MFA) activated. In the absence of this setting, + // Amazon Cognito uses the legacy behavior to determine the recovery method where + // SMS is preferred through email. + AccountRecoverySetting *types.AccountRecoverySettingType + + // The configuration for administrative creation of users. Includes the template + // for the invitation message for new users, the duration of temporary passwords, + // and permitting self-service sign-up. + AdminCreateUserConfig *types.AdminCreateUserConfigType + + // The attributes that you want your user pool to automatically verify. Possible + // values: email, phone_number. For more information see [Verifying contact information at sign-up]. + // + // [Verifying contact information at sign-up]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#allowing-users-to-sign-up-and-confirm-themselves + AutoVerifiedAttributes []types.VerifiedAttributeType + + // When active, DeletionProtection prevents accidental deletion of your user pool. + // Before you can delete a user pool that you have protected against deletion, you + // must deactivate this feature. + // + // When you try to delete a protected user pool in a DeleteUserPool API request, + // Amazon Cognito returns an InvalidParameterException error. To delete a + // protected user pool, send a new DeleteUserPool request after you deactivate + // deletion protection in an UpdateUserPool API request. + DeletionProtection types.DeletionProtectionType + + // The device-remembering configuration for a user pool. Device remembering or + // device tracking is a "Remember me on this device" option for user pools that + // perform authentication with the device key of a trusted device in the back end, + // instead of a user-provided MFA code. For more information about device + // authentication, see [Working with user devices in your user pool]. A null value indicates that you have deactivated device + // remembering in your user pool. + // + // When you provide a value for any DeviceConfiguration field, you activate the + // Amazon Cognito device-remembering feature. For more information, see [Working with devices]. + // + // [Working with devices]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + // [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html + DeviceConfiguration *types.DeviceConfigurationType + + // The email configuration of your user pool. The email configuration type sets + // your preferred sending method, Amazon Web Services Region, and sender for email + // invitation and verification messages from your user pool. + EmailConfiguration *types.EmailConfigurationType + + // This parameter is no longer used. + EmailVerificationMessage *string + + // This parameter is no longer used. + EmailVerificationSubject *string + + // A collection of user pool Lambda triggers. Amazon Cognito invokes triggers at + // several possible stages of authentication operations. Triggers can modify the + // outcome of the operations that invoked them. + LambdaConfig *types.LambdaConfigType + + // Sets multi-factor authentication (MFA) to be on, off, or optional. When ON , all + // users must set up MFA before they can sign in. When OPTIONAL , your application + // must make a client-side determination of whether a user wants to register an MFA + // device. For user pools with adaptive authentication with threat protection, + // choose OPTIONAL . + // + // When MfaConfiguration is OPTIONAL , managed login doesn't automatically prompt + // users to set up MFA. Amazon Cognito generates MFA prompts in API responses and + // in managed login for users who have chosen and configured a preferred MFA + // factor. + MfaConfiguration types.UserPoolMfaType + + // The password policy and sign-in policy in the user pool. The password policy + // sets options like password complexity requirements and password history. The + // sign-in policy sets the options available to applications in [choice-based authentication]. + // + // [choice-based authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-selection-sdk.html#authentication-flows-selection-choice + Policies *types.UserPoolPolicyType + + // The updated name of your user pool. + PoolName *string + + // The contents of the SMS message that your user pool sends to users in SMS + // authentication. + SmsAuthenticationMessage *string + + // The SMS configuration with the settings for your Amazon Cognito user pool to + // send SMS message with Amazon Simple Notification Service. To send SMS messages + // with Amazon SNS in the Amazon Web Services Region that you want, the Amazon + // Cognito user pool uses an Identity and Access Management (IAM) role in your + // Amazon Web Services account. For more information see [SMS message settings]. + // + // [SMS message settings]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html + SmsConfiguration *types.SmsConfigurationType + + // This parameter is no longer used. + SmsVerificationMessage *string + + // The settings for updates to user attributes. These settings include the + // property AttributesRequireVerificationBeforeUpdate , a user-pool setting that + // tells Amazon Cognito how to handle changes to the value of your users' email + // address and phone number attributes. For more information, see [Verifying updates to email addresses and phone numbers]. + // + // [Verifying updates to email addresses and phone numbers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html#user-pool-settings-verifications-verify-attribute-updates + UserAttributeUpdateSettings *types.UserAttributeUpdateSettingsType + + // Contains settings for activation of threat protection, including the operating + // mode and additional authentication types. To log user security information but + // take no action, set to AUDIT . To configure automatic security responses to + // potentially unwanted traffic to your user pool, set to ENFORCED . + // + // For more information, see [Adding advanced security to a user pool]. To activate this setting, your user pool must be on + // the [Plus tier]. + // + // [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html + // [Adding advanced security to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-advanced-security.html + UserPoolAddOns *types.UserPoolAddOnsType + + // The tag keys and values to assign to the user pool. A tag is a label that you + // can use to categorize and manage user pools in different ways, such as by + // purpose, owner, environment, or other criteria. + UserPoolTags map[string]string + + // The user pool [feature plan], or tier. This parameter determines the eligibility of the user + // pool for features like managed login, access-token customization, and threat + // protection. Defaults to ESSENTIALS . + // + // [feature plan]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sign-in-feature-plans.html + UserPoolTier types.UserPoolTierType + + // The template for the verification message that your user pool delivers to users + // who set an email address or phone number attribute. + // + // Set the email message type that corresponds to your DefaultEmailOption + // selection. For CONFIRM_WITH_LINK , specify an EmailMessageByLink and leave + // EmailMessage blank. For CONFIRM_WITH_CODE , specify an EmailMessage and leave + // EmailMessageByLink blank. When you supply both parameters with either choice, + // Amazon Cognito returns an error. + VerificationMessageTemplate *types.VerificationMessageTemplateType + + noSmithyDocumentSerde +} + +// Represents the response from the server when you make a request to update the +// user pool. +type UpdateUserPoolOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateUserPoolMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateUserPool{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateUserPool{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateUserPool"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateUserPoolValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateUserPool(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateUserPool(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateUserPool", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolClient.go new file mode 100644 index 00000000..c183ffa0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolClient.go @@ -0,0 +1,478 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Given a user pool app client ID, updates the configuration. To avoid setting +// parameters to Amazon Cognito defaults, construct this API request to pass the +// existing configuration of your app client, modified to include the changes that +// you want to make. +// +// If you don't provide a value for an attribute, Amazon Cognito sets it to its +// default value. +// +// Unlike app clients created in the console, Amazon Cognito doesn't automatically +// assign a branding style to app clients that you configure with this API +// operation. Managed login and classic hosted UI pages aren't available for your +// client until after you apply a branding style. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) UpdateUserPoolClient(ctx context.Context, params *UpdateUserPoolClientInput, optFns ...func(*Options)) (*UpdateUserPoolClientOutput, error) { + if params == nil { + params = &UpdateUserPoolClientInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateUserPoolClient", params, optFns, c.addOperationUpdateUserPoolClientMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateUserPoolClientOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to update the user pool client. +type UpdateUserPoolClientInput struct { + + // The ID of the app client that you want to update. + // + // This member is required. + ClientId *string + + // The ID of the user pool where you want to update the app client. + // + // This member is required. + UserPoolId *string + + // The access token time limit. After this limit expires, your user can't use + // their access token. To specify the time unit for AccessTokenValidity as seconds + // , minutes , hours , or days , set a TokenValidityUnits value in your API + // request. + // + // For example, when you set AccessTokenValidity to 10 and TokenValidityUnits to + // hours , your user can authorize access with their access token for 10 hours. + // + // The default time unit for AccessTokenValidity in an API request is hours. Valid + // range is displayed below in seconds. + // + // If you don't specify otherwise in the configuration of your app client, your + // access tokens are valid for one hour. + AccessTokenValidity *int32 + + // The OAuth grant types that you want your app client to generate. To create an + // app client that generates client credentials grants, you must add + // client_credentials as the only allowed OAuth flow. + // + // code Use a code grant flow, which provides an authorization code as the + // response. This code can be exchanged for access tokens with the /oauth2/token + // endpoint. + // + // implicit Issue the access token (and, optionally, ID token, based on scopes) + // directly to your user. + // + // client_credentials Issue the access token from the /oauth2/token endpoint + // directly to a non-person user using a combination of the client ID and client + // secret. + AllowedOAuthFlows []types.OAuthFlowType + + // Set to true to use OAuth 2.0 authorization server features in your app client. + // + // This parameter must have a value of true before you can configure the following + // features in your app client. + // + // - CallBackURLs : Callback URLs. + // + // - LogoutURLs : Sign-out redirect URLs. + // + // - AllowedOAuthScopes : OAuth 2.0 scopes. + // + // - AllowedOAuthFlows : Support for authorization code, implicit, and client + // credentials OAuth 2.0 grants. + // + // To use authorization server features, configure one of these features in the + // Amazon Cognito console or set AllowedOAuthFlowsUserPoolClient to true in a + // CreateUserPoolClient or UpdateUserPoolClient API request. If you don't set a + // value for AllowedOAuthFlowsUserPoolClient in a request with the CLI or SDKs, it + // defaults to false . When false , only SDK-based API sign-in is permitted. + AllowedOAuthFlowsUserPoolClient bool + + // The OAuth, OpenID Connect (OIDC), and custom scopes that you want to permit + // your app client to authorize access with. Scopes govern access control to user + // pool self-service API operations, user data from the userInfo endpoint, and + // third-party APIs. Scope values include phone , email , openid , and profile . + // The aws.cognito.signin.user.admin scope authorizes user self-service + // operations. Custom scopes with resource servers authorize access to external + // APIs. + AllowedOAuthScopes []string + + // The user pool analytics configuration for collecting metrics and sending them + // to your Amazon Pinpoint campaign. + // + // In Amazon Web Services Regions where Amazon Pinpoint isn't available, user + // pools might not have access to analytics or might be configurable with campaigns + // in the US East (N. Virginia) Region. For more information, see [Using Amazon Pinpoint analytics]. + // + // [Using Amazon Pinpoint analytics]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html + AnalyticsConfiguration *types.AnalyticsConfigurationType + + // Amazon Cognito creates a session token for each API request in an + // authentication flow. AuthSessionValidity is the duration, in minutes, of that + // session token. Your user pool native user must respond to each authentication + // challenge before the session expires. + AuthSessionValidity *int32 + + // A list of allowed redirect, or callback, URLs for managed login authentication. + // These URLs are the paths where you want to send your users' browsers after they + // complete authentication with managed login or a third-party IdP. Typically, + // callback URLs are the home of an application that uses OAuth or OIDC libraries + // to process authentication outcomes. + // + // A redirect URI must meet the following requirements: + // + // - Be an absolute URI. + // + // - Be registered with the authorization server. Amazon Cognito doesn't accept + // authorization requests with redirect_uri values that aren't in the list of + // CallbackURLs that you provide in this parameter. + // + // - Not include a fragment component. + // + // See [OAuth 2.0 - Redirection Endpoint]. + // + // Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing + // purposes only. + // + // App callback URLs such as myapp://example are also supported. + // + // [OAuth 2.0 - Redirection Endpoint]: https://tools.ietf.org/html/rfc6749#section-3.1.2 + CallbackURLs []string + + // A friendly name for the app client. + ClientName *string + + // The default redirect URI. In app clients with one assigned IdP, replaces + // redirect_uri in authentication requests. Must be in the CallbackURLs list. + DefaultRedirectURI *string + + // When true , your application can include additional UserContextData in + // authentication requests. This data includes the IP address, and contributes to + // analysis by threat protection features. For more information about propagation + // of user context data, see [Adding session data to API requests]. If you don’t include this parameter, you can't send + // the source IP address to Amazon Cognito threat protection features. You can only + // activate EnablePropagateAdditionalUserContextData in an app client that has a + // client secret. + // + // [Adding session data to API requests]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-device-fingerprint + EnablePropagateAdditionalUserContextData *bool + + // Activates or deactivates [token revocation] in the target app client. + // + // [token revocation]: https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html + EnableTokenRevocation *bool + + // The [authentication flows] that you want your user pool client to support. For each app client in + // your user pool, you can sign in your users with any combination of one or more + // flows, including with a user name and Secure Remote Password (SRP), a user name + // and password, or a custom authentication process that you define with Lambda + // functions. + // + // If you don't specify a value for ExplicitAuthFlows , your app client supports + // ALLOW_REFRESH_TOKEN_AUTH , ALLOW_USER_SRP_AUTH , and ALLOW_CUSTOM_AUTH . + // + // The values for authentication flow options include the following. + // + // - ALLOW_USER_AUTH : Enable selection-based sign-in with USER_AUTH . This + // setting covers username-password, secure remote password (SRP), passwordless, + // and passkey authentication. This authentiation flow can do username-password and + // SRP authentication without other ExplicitAuthFlows permitting them. For + // example users can complete an SRP challenge through USER_AUTH without the flow + // USER_SRP_AUTH being active for the app client. This flow doesn't include + // CUSTOM_AUTH . + // + // To activate this setting, your user pool must be in the [Essentials tier]or higher. + // + // - ALLOW_ADMIN_USER_PASSWORD_AUTH : Enable admin based user password + // authentication flow ADMIN_USER_PASSWORD_AUTH . This setting replaces the + // ADMIN_NO_SRP_AUTH setting. With this authentication flow, your app passes a + // user name and password to Amazon Cognito in the request, instead of using the + // Secure Remote Password (SRP) protocol to securely transmit the password. + // + // - ALLOW_CUSTOM_AUTH : Enable Lambda trigger based authentication. + // + // - ALLOW_USER_PASSWORD_AUTH : Enable user password-based authentication. In + // this flow, Amazon Cognito receives the password in the request instead of using + // the SRP protocol to verify passwords. + // + // - ALLOW_USER_SRP_AUTH : Enable SRP-based authentication. + // + // - ALLOW_REFRESH_TOKEN_AUTH : Enable authflow to refresh tokens. + // + // In some environments, you will see the values ADMIN_NO_SRP_AUTH , + // CUSTOM_AUTH_FLOW_ONLY , or USER_PASSWORD_AUTH . You can't assign these legacy + // ExplicitAuthFlows values to user pool clients at the same time as values that + // begin with ALLOW_ , like ALLOW_USER_SRP_AUTH . + // + // [authentication flows]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + ExplicitAuthFlows []types.ExplicitAuthFlowsType + + // The ID token time limit. After this limit expires, your user can't use their ID + // token. To specify the time unit for IdTokenValidity as seconds , minutes , hours + // , or days , set a TokenValidityUnits value in your API request. + // + // For example, when you set IdTokenValidity as 10 and TokenValidityUnits as hours + // , your user can authenticate their session with their ID token for 10 hours. + // + // The default time unit for IdTokenValidity in an API request is hours. Valid + // range is displayed below in seconds. + // + // If you don't specify otherwise in the configuration of your app client, your ID + // tokens are valid for one hour. + IdTokenValidity *int32 + + // A list of allowed logout URLs for managed login authentication. When you pass + // logout_uri and client_id parameters to /logout , Amazon Cognito signs out your + // user and redirects them to the logout URL. This parameter describes the URLs + // that you want to be the permitted targets of logout_uri . A typical use of these + // URLs is when a user selects "Sign out" and you redirect them to your public + // homepage. For more information, see [Logout endpoint]. + // + // [Logout endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html + LogoutURLs []string + + // When ENABLED , suppresses messages that might indicate a valid user exists when + // someone attempts sign-in. This parameters sets your preference for the errors + // and responses that you want Amazon Cognito APIs to return during authentication, + // account confirmation, and password recovery when the user doesn't exist in the + // user pool. When set to ENABLED and the user doesn't exist, authentication + // returns an error indicating either the username or password was incorrect. + // Account confirmation and password recovery return a response indicating a code + // was sent to a simulated destination. When set to LEGACY , those APIs return a + // UserNotFoundException exception if the user doesn't exist in the user pool. + // + // Defaults to LEGACY . + PreventUserExistenceErrors types.PreventUserExistenceErrorTypes + + // The list of user attributes that you want your app client to have read access + // to. After your user authenticates in your app, their access token authorizes + // them to read their own attribute value for any attribute in this list. + // + // When you don't specify the ReadAttributes for your app client, your app can + // read the values of email_verified , phone_number_verified , and the standard + // attributes of your user pool. When your user pool app client has read access to + // these default attributes, ReadAttributes doesn't return any information. Amazon + // Cognito only populates ReadAttributes in the API response if you have specified + // your own custom set of read attributes. + ReadAttributes []string + + // The configuration of your app client for refresh token rotation. When enabled, + // your app client issues new ID, access, and refresh tokens when users renew their + // sessions with refresh tokens. When disabled, token refresh issues only ID and + // access tokens. + RefreshTokenRotation *types.RefreshTokenRotationType + + // The refresh token time limit. After this limit expires, your user can't use + // their refresh token. To specify the time unit for RefreshTokenValidity as + // seconds , minutes , hours , or days , set a TokenValidityUnits value in your + // API request. + // + // For example, when you set RefreshTokenValidity as 10 and TokenValidityUnits as + // days , your user can refresh their session and retrieve new access and ID tokens + // for 10 days. + // + // The default time unit for RefreshTokenValidity in an API request is days. You + // can't set RefreshTokenValidity to 0. If you do, Amazon Cognito overrides the + // value with the default value of 30 days. Valid range is displayed below in + // seconds. + // + // If you don't specify otherwise in the configuration of your app client, your + // refresh tokens are valid for 30 days. + RefreshTokenValidity int32 + + // A list of provider names for the identity providers (IdPs) that are supported + // on this client. The following are supported: COGNITO , Facebook , Google , + // SignInWithApple , and LoginWithAmazon . You can also specify the names that you + // configured for the SAML and OIDC IdPs in your user pool, for example MySAMLIdP + // or MyOIDCIdP . + // + // This parameter sets the IdPs that [managed login] will display on the login page for your app + // client. The removal of COGNITO from this list doesn't prevent authentication + // operations for local users with the user pools API in an Amazon Web Services + // SDK. The only way to prevent SDK-based authentication is to block access with a [WAF rule] + // . + // + // [WAF rule]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-waf.html + // [managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html + SupportedIdentityProviders []string + + // The units that validity times are represented in. The default unit for refresh + // tokens is days, and the default for ID and access tokens are hours. + TokenValidityUnits *types.TokenValidityUnitsType + + // The list of user attributes that you want your app client to have write access + // to. After your user authenticates in your app, their access token authorizes + // them to set or modify their own attribute value for any attribute in this list. + // + // When you don't specify the WriteAttributes for your app client, your app can + // write the values of the Standard attributes of your user pool. When your user + // pool has write access to these default attributes, WriteAttributes doesn't + // return any information. Amazon Cognito only populates WriteAttributes in the + // API response if you have specified your own custom set of write attributes. + // + // If your app client allows users to sign in through an IdP, this array must + // include all attributes that you have mapped to IdP attributes. Amazon Cognito + // updates mapped attributes when users sign in to your application through an IdP. + // If your app client does not have write access to a mapped attribute, Amazon + // Cognito throws an error when it tries to update the attribute. For more + // information, see [Specifying IdP Attribute Mappings for Your user pool]. + // + // [Specifying IdP Attribute Mappings for Your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html + WriteAttributes []string + + noSmithyDocumentSerde +} + +// Represents the response from the server to the request to update the user pool +// client. +type UpdateUserPoolClientOutput struct { + + // The updated details of your app client. + UserPoolClient *types.UserPoolClientType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateUserPoolClientMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateUserPoolClient{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateUserPoolClient{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateUserPoolClient"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateUserPoolClientValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateUserPoolClient(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateUserPoolClient(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateUserPoolClient", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolDomain.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolDomain.go new file mode 100644 index 00000000..94375fe4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_UpdateUserPoolDomain.go @@ -0,0 +1,237 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// A user pool domain hosts managed login, an authorization server and web server +// for authentication in your application. This operation updates the branding +// version for user pool domains between 1 for hosted UI (classic) and 2 for +// managed login. It also updates the SSL certificate for user pool custom domains. +// +// Changes to the domain branding version take up to one minute to take effect for +// a prefix domain and up to five minutes for a custom domain. +// +// This operation doesn't change the name of your user pool domain. To change your +// domain, delete it with DeleteUserPoolDomain and create a new domain with +// CreateUserPoolDomain . +// +// You can pass the ARN of a new Certificate Manager certificate in this request. +// Typically, ACM certificates automatically renew and you user pool can continue +// to use the same ARN. But if you generate a new certificate for your custom +// domain name, replace the original configuration with the new ARN in this +// request. +// +// ACM certificates for custom domains must be in the US East (N. Virginia) Amazon +// Web Services Region. After you submit your request, Amazon Cognito requires up +// to 1 hour to distribute your new certificate to your custom domain. +// +// For more information about adding a custom domain to your user pool, see [Configuring a user pool domain]. +// +// Amazon Cognito evaluates Identity and Access Management (IAM) policies in +// requests for this API operation. For this operation, you must use IAM +// credentials to authorize requests, and you must grant yourself the corresponding +// IAM permission in a policy. +// +// # Learn more +// +// [Signing Amazon Web Services API Requests] +// +// [Using the Amazon Cognito user pools API and user pool endpoints] +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +// [Configuring a user pool domain]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-add-custom-domain.html +// [Signing Amazon Web Services API Requests]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html +func (c *Client) UpdateUserPoolDomain(ctx context.Context, params *UpdateUserPoolDomainInput, optFns ...func(*Options)) (*UpdateUserPoolDomainOutput, error) { + if params == nil { + params = &UpdateUserPoolDomainInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "UpdateUserPoolDomain", params, optFns, c.addOperationUpdateUserPoolDomainMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*UpdateUserPoolDomainOutput) + out.ResultMetadata = metadata + return out, nil +} + +// The UpdateUserPoolDomain request input. +type UpdateUserPoolDomainInput struct { + + // The name of the domain that you want to update. For custom domains, this is the + // fully-qualified domain name, for example auth.example.com . For prefix domains, + // this is the prefix alone, such as myprefix . + // + // This member is required. + Domain *string + + // The ID of the user pool that is associated with the domain you're updating. + // + // This member is required. + UserPoolId *string + + // The configuration for a custom domain that hosts managed login for your + // application. In an UpdateUserPoolDomain request, this parameter specifies an + // SSL certificate for the managed login hosted webserver. The certificate must be + // an ACM ARN in us-east-1 . + // + // When you create a custom domain, the passkey RP ID defaults to the custom + // domain. If you had a prefix domain active, this will cause passkey integration + // for your prefix domain to stop working due to a mismatch in RP ID. To keep the + // prefix domain passkey integration working, you can explicitly set RP ID to the + // prefix domain. + CustomDomainConfig *types.CustomDomainConfigType + + // A version number that indicates the state of managed login for your domain. + // Version 1 is hosted UI (classic). Version 2 is the newer managed login with the + // branding designer. For more information, see [Managed login]. + // + // [Managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html + ManagedLoginVersion *int32 + + noSmithyDocumentSerde +} + +// The UpdateUserPoolDomain response output. +type UpdateUserPoolDomainOutput struct { + + // The fully-qualified domain name (FQDN) of the Amazon CloudFront distribution + // that hosts your managed login or classic hosted UI pages. You domain-name + // authority must have an alias record that points requests for your custom domain + // to this FQDN. Amazon Cognito returns this value if you set a custom domain with + // CustomDomainConfig . If you set an Amazon Cognito prefix domain, this operation + // returns a blank response. + CloudFrontDomain *string + + // A version number that indicates the state of managed login for your domain. + // Version 1 is hosted UI (classic). Version 2 is the newer managed login with the + // branding designer. For more information, see [Managed login]. + // + // [Managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html + ManagedLoginVersion *int32 + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationUpdateUserPoolDomainMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateUserPoolDomain{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateUserPoolDomain"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpUpdateUserPoolDomainValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateUserPoolDomain(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opUpdateUserPoolDomain(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "UpdateUserPoolDomain", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifySoftwareToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifySoftwareToken.go new file mode 100644 index 00000000..db281e11 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifySoftwareToken.go @@ -0,0 +1,186 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Registers the current user's time-based one-time password (TOTP) authenticator +// with a code generated in their authenticator app from a private key that's +// supplied by your user pool. Marks the user's software token MFA status as +// "verified" if successful. The request takes an access token or a session string, +// but not both. +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) VerifySoftwareToken(ctx context.Context, params *VerifySoftwareTokenInput, optFns ...func(*Options)) (*VerifySoftwareTokenOutput, error) { + if params == nil { + params = &VerifySoftwareTokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "VerifySoftwareToken", params, optFns, c.addOperationVerifySoftwareTokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*VerifySoftwareTokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +type VerifySoftwareTokenInput struct { + + // A TOTP that the user generated in their configured authenticator app. + // + // This member is required. + UserCode *string + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + AccessToken *string + + // A friendly name for the device that's running the TOTP authenticator. + FriendlyDeviceName *string + + // The session ID from an AssociateSoftwareToken request. + Session *string + + noSmithyDocumentSerde +} + +type VerifySoftwareTokenOutput struct { + + // This session ID satisfies an MFA_SETUP challenge. Supply the session ID in your + // challenge response. + Session *string + + // Amazon Cognito can accept or reject the code that you provide. This response + // parameter indicates the success of TOTP verification. Some reasons that this + // operation might return an error are clock skew on the user's device and + // excessive retries. + Status types.VerifySoftwareTokenResponseType + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationVerifySoftwareTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpVerifySoftwareToken{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpVerifySoftwareToken{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "VerifySoftwareToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpVerifySoftwareTokenValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opVerifySoftwareToken(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opVerifySoftwareToken(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "VerifySoftwareToken", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifyUserAttribute.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifyUserAttribute.go new file mode 100644 index 00000000..075a68de --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/api_op_VerifyUserAttribute.go @@ -0,0 +1,185 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Submits a verification code for a signed-in user who has added or changed a +// value of an auto-verified attribute. When successful, the user's attribute +// becomes verified and the attribute email_verified or phone_number_verified +// becomes true . +// +// If your user pool requires verification before Amazon Cognito updates the +// attribute value, this operation updates the affected attribute to its pending +// value. +// +// Authorize this action with a signed-in user's access token. It must include the +// scope aws.cognito.signin.user.admin . +// +// Amazon Cognito doesn't evaluate Identity and Access Management (IAM) policies +// in requests for this API operation. For this operation, you can't use IAM +// credentials to authorize requests, and you can't grant IAM permissions in +// policies. For more information about authorization models in Amazon Cognito, see +// [Using the Amazon Cognito user pools API and user pool endpoints]. +// +// [Using the Amazon Cognito user pools API and user pool endpoints]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html +func (c *Client) VerifyUserAttribute(ctx context.Context, params *VerifyUserAttributeInput, optFns ...func(*Options)) (*VerifyUserAttributeOutput, error) { + if params == nil { + params = &VerifyUserAttributeInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "VerifyUserAttribute", params, optFns, c.addOperationVerifyUserAttributeMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*VerifyUserAttributeOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Represents the request to verify user attributes. +type VerifyUserAttributeInput struct { + + // A valid access token that Amazon Cognito issued to the currently signed-in + // user. Must include a scope claim for aws.cognito.signin.user.admin . + // + // This member is required. + AccessToken *string + + // The name of the attribute that you want to verify. + // + // This member is required. + AttributeName *string + + // The verification code that your user pool sent to the added or changed + // attribute, for example the user's email address. + // + // This member is required. + Code *string + + noSmithyDocumentSerde +} + +// A container representing the response from the server from the request to +// verify user attributes. +type VerifyUserAttributeOutput struct { + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationVerifyUserAttributeMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsjson11_serializeOpVerifyUserAttribute{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpVerifyUserAttribute{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "VerifyUserAttribute"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpVerifyUserAttributeValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opVerifyUserAttribute(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addSpanInitializeStart(stack); err != nil { + return err + } + if err = addSpanInitializeEnd(stack); err != nil { + return err + } + if err = addSpanBuildRequestStart(stack); err != nil { + return err + } + if err = addSpanBuildRequestEnd(stack); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opVerifyUserAttribute(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "VerifyUserAttribute", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/auth.go new file mode 100644 index 00000000..1c5e3e8b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/auth.go @@ -0,0 +1,499 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { + params.Region = options.Region +} + +type setLegacyContextSigningOptionsMiddleware struct { +} + +func (*setLegacyContextSigningOptionsMiddleware) ID() string { + return "setLegacyContextSigningOptions" +} + +func (m *setLegacyContextSigningOptionsMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + rscheme := getResolvedAuthScheme(ctx) + schemeID := rscheme.Scheme.SchemeID() + + if sn := awsmiddleware.GetSigningName(ctx); sn != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningName(&rscheme.SignerProperties, sn) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningName(&rscheme.SignerProperties, sn) + } + } + + if sr := awsmiddleware.GetSigningRegion(ctx); sr != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningRegion(&rscheme.SignerProperties, sr) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningRegions(&rscheme.SignerProperties, []string{sr}) + } + } + + return next.HandleFinalize(ctx, in) +} + +func addSetLegacyContextSigningOptionsMiddleware(stack *middleware.Stack) error { + return stack.Finalize.Insert(&setLegacyContextSigningOptionsMiddleware{}, "Signing", middleware.Before) +} + +type withAnonymous struct { + resolver AuthSchemeResolver +} + +var _ AuthSchemeResolver = (*withAnonymous)(nil) + +func (v *withAnonymous) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + opts, err := v.resolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return nil, err + } + + opts = append(opts, &smithyauth.Option{ + SchemeID: smithyauth.SchemeIDAnonymous, + }) + return opts, nil +} + +func wrapWithAnonymousAuth(options *Options) { + if _, ok := options.AuthSchemeResolver.(*defaultAuthSchemeResolver); !ok { + return + } + + options.AuthSchemeResolver = &withAnonymous{ + resolver: options.AuthSchemeResolver, + } +} + +// AuthResolverParameters contains the set of inputs necessary for auth scheme +// resolution. +type AuthResolverParameters struct { + // The name of the operation being invoked. + Operation string + + // The region in which the operation is being invoked. + Region string +} + +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { + params := &AuthResolverParameters{ + Operation: operation, + } + + bindAuthParamsRegion(ctx, params, input, options) + + return params +} + +// AuthSchemeResolver returns a set of possible authentication options for an +// operation. +type AuthSchemeResolver interface { + ResolveAuthSchemes(context.Context, *AuthResolverParameters) ([]*smithyauth.Option, error) +} + +type defaultAuthSchemeResolver struct{} + +var _ AuthSchemeResolver = (*defaultAuthSchemeResolver)(nil) + +func (*defaultAuthSchemeResolver) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + if overrides, ok := operationAuthOptions[params.Operation]; ok { + return overrides(params), nil + } + return serviceAuthOptions(params), nil +} + +var operationAuthOptions = map[string]func(*AuthResolverParameters) []*smithyauth.Option{ + "AssociateSoftwareToken": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ChangePassword": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "CompleteWebAuthnRegistration": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ConfirmDevice": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ConfirmForgotPassword": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ConfirmSignUp": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "DeleteUser": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "DeleteUserAttributes": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "DeleteWebAuthnCredential": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ForgetDevice": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ForgotPassword": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "GetDevice": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "GetUser": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "GetUserAttributeVerificationCode": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "GetUserAuthFactors": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "GlobalSignOut": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "InitiateAuth": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ListDevices": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ListWebAuthnCredentials": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "ResendConfirmationCode": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "RespondToAuthChallenge": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "RevokeToken": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "SetUserMFAPreference": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "SetUserSettings": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "SignUp": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "StartWebAuthnRegistration": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "UpdateAuthEventFeedback": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "UpdateDeviceStatus": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "UpdateUserAttributes": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "VerifySoftwareToken": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, + + "VerifyUserAttribute": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, +} + +func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + { + SchemeID: smithyauth.SchemeIDSigV4, + SignerProperties: func() smithy.Properties { + var props smithy.Properties + smithyhttp.SetSigV4SigningName(&props, "cognito-idp") + smithyhttp.SetSigV4SigningRegion(&props, params.Region) + return props + }(), + }, + } +} + +type resolveAuthSchemeMiddleware struct { + operation string + options Options +} + +func (*resolveAuthSchemeMiddleware) ID() string { + return "ResolveAuthScheme" +} + +func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") + defer span.End() + + params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) + } + + scheme, ok := m.selectScheme(options) + if !ok { + return out, metadata, fmt.Errorf("could not select an auth scheme") + } + + ctx = setResolvedAuthScheme(ctx, scheme) + + span.SetProperty("auth.scheme_id", scheme.Scheme.SchemeID()) + span.End() + return next.HandleFinalize(ctx, in) +} + +func (m *resolveAuthSchemeMiddleware) selectScheme(options []*smithyauth.Option) (*resolvedAuthScheme, bool) { + for _, option := range options { + if option.SchemeID == smithyauth.SchemeIDAnonymous { + return newResolvedAuthScheme(smithyhttp.NewAnonymousScheme(), option), true + } + + for _, scheme := range m.options.AuthSchemes { + if scheme.SchemeID() != option.SchemeID { + continue + } + + if scheme.IdentityResolver(m.options) != nil { + return newResolvedAuthScheme(scheme, option), true + } + } + } + + return nil, false +} + +type resolvedAuthSchemeKey struct{} + +type resolvedAuthScheme struct { + Scheme smithyhttp.AuthScheme + IdentityProperties smithy.Properties + SignerProperties smithy.Properties +} + +func newResolvedAuthScheme(scheme smithyhttp.AuthScheme, option *smithyauth.Option) *resolvedAuthScheme { + return &resolvedAuthScheme{ + Scheme: scheme, + IdentityProperties: option.IdentityProperties, + SignerProperties: option.SignerProperties, + } +} + +func setResolvedAuthScheme(ctx context.Context, scheme *resolvedAuthScheme) context.Context { + return middleware.WithStackValue(ctx, resolvedAuthSchemeKey{}, scheme) +} + +func getResolvedAuthScheme(ctx context.Context) *resolvedAuthScheme { + v, _ := middleware.GetStackValue(ctx, resolvedAuthSchemeKey{}).(*resolvedAuthScheme) + return v +} + +type getIdentityMiddleware struct { + options Options +} + +func (*getIdentityMiddleware) ID() string { + return "GetIdentity" +} + +func (m *getIdentityMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + innerCtx, span := tracing.StartSpan(ctx, "GetIdentity") + defer span.End() + + rscheme := getResolvedAuthScheme(innerCtx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + resolver := rscheme.Scheme.IdentityResolver(m.options) + if resolver == nil { + return out, metadata, fmt.Errorf("no identity resolver") + } + + identity, err := timeOperationMetric(ctx, "client.call.resolve_identity_duration", + func() (smithyauth.Identity, error) { + return resolver.GetIdentity(innerCtx, rscheme.IdentityProperties) + }, + func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("get identity: %w", err) + } + + ctx = setIdentity(ctx, identity) + + span.End() + return next.HandleFinalize(ctx, in) +} + +type identityKey struct{} + +func setIdentity(ctx context.Context, identity smithyauth.Identity) context.Context { + return middleware.WithStackValue(ctx, identityKey{}, identity) +} + +func getIdentity(ctx context.Context) smithyauth.Identity { + v, _ := middleware.GetStackValue(ctx, identityKey{}).(smithyauth.Identity) + return v +} + +type signRequestMiddleware struct { + options Options +} + +func (*signRequestMiddleware) ID() string { + return "Signing" +} + +func (m *signRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "SignRequest") + defer span.End() + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unexpected transport type %T", in.Request) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + identity := getIdentity(ctx) + if identity == nil { + return out, metadata, fmt.Errorf("no identity") + } + + signer := rscheme.Scheme.Signer() + if signer == nil { + return out, metadata, fmt.Errorf("no signer") + } + + _, err = timeOperationMetric(ctx, "client.call.signing_duration", func() (any, error) { + return nil, signer.SignRequest(ctx, req, identity, rscheme.SignerProperties) + }, func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("sign request: %w", err) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/deserializers.go new file mode 100644 index 00000000..70421faa --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/deserializers.go @@ -0,0 +1,29520 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + internaldocument "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + smithy "github.com/aws/smithy-go" + smithyio "github.com/aws/smithy-go/io" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/ptr" + smithytime "github.com/aws/smithy-go/time" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "io" + "io/ioutil" + "strings" + "time" +) + +func deserializeS3Expires(v string) (*time.Time, error) { + t, err := smithytime.ParseHTTPDate(v) + if err != nil { + return nil, nil + } + return &t, nil +} + +type awsAwsjson11_deserializeOpAddCustomAttributes struct { +} + +func (*awsAwsjson11_deserializeOpAddCustomAttributes) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAddCustomAttributes) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAddCustomAttributes(response, &metadata) + } + output := &AddCustomAttributesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAddCustomAttributesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAddCustomAttributes(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserImportInProgressException", errorCode): + return awsAwsjson11_deserializeErrorUserImportInProgressException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminAddUserToGroup struct { +} + +func (*awsAwsjson11_deserializeOpAdminAddUserToGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminAddUserToGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminAddUserToGroup(response, &metadata) + } + output := &AdminAddUserToGroupOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminAddUserToGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminConfirmSignUp struct { +} + +func (*awsAwsjson11_deserializeOpAdminConfirmSignUp) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminConfirmSignUp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminConfirmSignUp(response, &metadata) + } + output := &AdminConfirmSignUpOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminConfirmSignUpOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminConfirmSignUp(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyFailedAttemptsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyFailedAttemptsException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminCreateUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminCreateUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminCreateUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminCreateUser(response, &metadata) + } + output := &AdminCreateUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminCreateUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminCreateUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PreconditionNotMetException", errorCode): + return awsAwsjson11_deserializeErrorPreconditionNotMetException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UnsupportedUserStateException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedUserStateException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + case strings.EqualFold("UsernameExistsException", errorCode): + return awsAwsjson11_deserializeErrorUsernameExistsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminDeleteUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminDeleteUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminDeleteUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminDeleteUser(response, &metadata) + } + output := &AdminDeleteUserOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminDeleteUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminDeleteUserAttributes struct { +} + +func (*awsAwsjson11_deserializeOpAdminDeleteUserAttributes) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminDeleteUserAttributes) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminDeleteUserAttributes(response, &metadata) + } + output := &AdminDeleteUserAttributesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminDeleteUserAttributesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminDeleteUserAttributes(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminDisableProviderForUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminDisableProviderForUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminDisableProviderForUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminDisableProviderForUser(response, &metadata) + } + output := &AdminDisableProviderForUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminDisableProviderForUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminDisableProviderForUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminDisableUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminDisableUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminDisableUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminDisableUser(response, &metadata) + } + output := &AdminDisableUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminDisableUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminDisableUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminEnableUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminEnableUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminEnableUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminEnableUser(response, &metadata) + } + output := &AdminEnableUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminEnableUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminEnableUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminForgetDevice struct { +} + +func (*awsAwsjson11_deserializeOpAdminForgetDevice) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminForgetDevice) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminForgetDevice(response, &metadata) + } + output := &AdminForgetDeviceOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminForgetDevice(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminGetDevice struct { +} + +func (*awsAwsjson11_deserializeOpAdminGetDevice) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminGetDevice) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminGetDevice(response, &metadata) + } + output := &AdminGetDeviceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminGetDeviceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminGetDevice(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminGetUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminGetUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminGetUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminGetUser(response, &metadata) + } + output := &AdminGetUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminGetUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminGetUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminInitiateAuth struct { +} + +func (*awsAwsjson11_deserializeOpAdminInitiateAuth) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminInitiateAuth) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminInitiateAuth(response, &metadata) + } + output := &AdminInitiateAuthOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminInitiateAuthOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminInitiateAuth(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("MFAMethodNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorMFAMethodNotFoundException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UnsupportedOperationException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedOperationException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminLinkProviderForUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminLinkProviderForUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminLinkProviderForUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminLinkProviderForUser(response, &metadata) + } + output := &AdminLinkProviderForUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminLinkProviderForUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminLinkProviderForUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminListDevices struct { +} + +func (*awsAwsjson11_deserializeOpAdminListDevices) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminListDevices) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminListDevices(response, &metadata) + } + output := &AdminListDevicesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminListDevicesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminListDevices(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminListGroupsForUser struct { +} + +func (*awsAwsjson11_deserializeOpAdminListGroupsForUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminListGroupsForUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminListGroupsForUser(response, &metadata) + } + output := &AdminListGroupsForUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminListGroupsForUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminListGroupsForUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminListUserAuthEvents struct { +} + +func (*awsAwsjson11_deserializeOpAdminListUserAuthEvents) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminListUserAuthEvents) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminListUserAuthEvents(response, &metadata) + } + output := &AdminListUserAuthEventsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminListUserAuthEventsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminListUserAuthEvents(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + case strings.EqualFold("UserPoolAddOnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolAddOnNotEnabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminRemoveUserFromGroup struct { +} + +func (*awsAwsjson11_deserializeOpAdminRemoveUserFromGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminRemoveUserFromGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminRemoveUserFromGroup(response, &metadata) + } + output := &AdminRemoveUserFromGroupOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminRemoveUserFromGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminResetUserPassword struct { +} + +func (*awsAwsjson11_deserializeOpAdminResetUserPassword) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminResetUserPassword) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminResetUserPassword(response, &metadata) + } + output := &AdminResetUserPasswordOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminResetUserPasswordOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminResetUserPassword(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminRespondToAuthChallenge struct { +} + +func (*awsAwsjson11_deserializeOpAdminRespondToAuthChallenge) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminRespondToAuthChallenge) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminRespondToAuthChallenge(response, &metadata) + } + output := &AdminRespondToAuthChallengeOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminRespondToAuthChallengeOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminRespondToAuthChallenge(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("ExpiredCodeException", errorCode): + return awsAwsjson11_deserializeErrorExpiredCodeException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("MFAMethodNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorMFAMethodNotFoundException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordHistoryPolicyViolationException", errorCode): + return awsAwsjson11_deserializeErrorPasswordHistoryPolicyViolationException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("SoftwareTokenMFANotFoundException", errorCode): + return awsAwsjson11_deserializeErrorSoftwareTokenMFANotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminSetUserMFAPreference struct { +} + +func (*awsAwsjson11_deserializeOpAdminSetUserMFAPreference) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminSetUserMFAPreference) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminSetUserMFAPreference(response, &metadata) + } + output := &AdminSetUserMFAPreferenceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminSetUserMFAPreferenceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminSetUserMFAPreference(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminSetUserPassword struct { +} + +func (*awsAwsjson11_deserializeOpAdminSetUserPassword) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminSetUserPassword) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminSetUserPassword(response, &metadata) + } + output := &AdminSetUserPasswordOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminSetUserPasswordOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminSetUserPassword(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordHistoryPolicyViolationException", errorCode): + return awsAwsjson11_deserializeErrorPasswordHistoryPolicyViolationException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminSetUserSettings struct { +} + +func (*awsAwsjson11_deserializeOpAdminSetUserSettings) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminSetUserSettings) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminSetUserSettings(response, &metadata) + } + output := &AdminSetUserSettingsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminSetUserSettingsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminSetUserSettings(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminUpdateAuthEventFeedback struct { +} + +func (*awsAwsjson11_deserializeOpAdminUpdateAuthEventFeedback) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminUpdateAuthEventFeedback) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminUpdateAuthEventFeedback(response, &metadata) + } + output := &AdminUpdateAuthEventFeedbackOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminUpdateAuthEventFeedbackOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminUpdateAuthEventFeedback(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + case strings.EqualFold("UserPoolAddOnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolAddOnNotEnabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminUpdateDeviceStatus struct { +} + +func (*awsAwsjson11_deserializeOpAdminUpdateDeviceStatus) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminUpdateDeviceStatus) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminUpdateDeviceStatus(response, &metadata) + } + output := &AdminUpdateDeviceStatusOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminUpdateDeviceStatusOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminUpdateDeviceStatus(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminUpdateUserAttributes struct { +} + +func (*awsAwsjson11_deserializeOpAdminUpdateUserAttributes) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminUpdateUserAttributes) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminUpdateUserAttributes(response, &metadata) + } + output := &AdminUpdateUserAttributesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminUpdateUserAttributesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminUpdateUserAttributes(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAdminUserGlobalSignOut struct { +} + +func (*awsAwsjson11_deserializeOpAdminUserGlobalSignOut) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAdminUserGlobalSignOut) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAdminUserGlobalSignOut(response, &metadata) + } + output := &AdminUserGlobalSignOutOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAdminUserGlobalSignOutOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAdminUserGlobalSignOut(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpAssociateSoftwareToken struct { +} + +func (*awsAwsjson11_deserializeOpAssociateSoftwareToken) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpAssociateSoftwareToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorAssociateSoftwareToken(response, &metadata) + } + output := &AssociateSoftwareTokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentAssociateSoftwareTokenOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorAssociateSoftwareToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("SoftwareTokenMFANotFoundException", errorCode): + return awsAwsjson11_deserializeErrorSoftwareTokenMFANotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpChangePassword struct { +} + +func (*awsAwsjson11_deserializeOpChangePassword) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpChangePassword) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorChangePassword(response, &metadata) + } + output := &ChangePasswordOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentChangePasswordOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorChangePassword(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordHistoryPolicyViolationException", errorCode): + return awsAwsjson11_deserializeErrorPasswordHistoryPolicyViolationException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCompleteWebAuthnRegistration struct { +} + +func (*awsAwsjson11_deserializeOpCompleteWebAuthnRegistration) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCompleteWebAuthnRegistration) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCompleteWebAuthnRegistration(response, &metadata) + } + output := &CompleteWebAuthnRegistrationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCompleteWebAuthnRegistrationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCompleteWebAuthnRegistration(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("WebAuthnChallengeNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnChallengeNotFoundException(response, errorBody) + + case strings.EqualFold("WebAuthnClientMismatchException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnClientMismatchException(response, errorBody) + + case strings.EqualFold("WebAuthnCredentialNotSupportedException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnCredentialNotSupportedException(response, errorBody) + + case strings.EqualFold("WebAuthnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnNotEnabledException(response, errorBody) + + case strings.EqualFold("WebAuthnOriginNotAllowedException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnOriginNotAllowedException(response, errorBody) + + case strings.EqualFold("WebAuthnRelyingPartyMismatchException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnRelyingPartyMismatchException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpConfirmDevice struct { +} + +func (*awsAwsjson11_deserializeOpConfirmDevice) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpConfirmDevice) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorConfirmDevice(response, &metadata) + } + output := &ConfirmDeviceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentConfirmDeviceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorConfirmDevice(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("DeviceKeyExistsException", errorCode): + return awsAwsjson11_deserializeErrorDeviceKeyExistsException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + case strings.EqualFold("UsernameExistsException", errorCode): + return awsAwsjson11_deserializeErrorUsernameExistsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpConfirmForgotPassword struct { +} + +func (*awsAwsjson11_deserializeOpConfirmForgotPassword) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpConfirmForgotPassword) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorConfirmForgotPassword(response, &metadata) + } + output := &ConfirmForgotPasswordOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentConfirmForgotPasswordOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorConfirmForgotPassword(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("ExpiredCodeException", errorCode): + return awsAwsjson11_deserializeErrorExpiredCodeException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordHistoryPolicyViolationException", errorCode): + return awsAwsjson11_deserializeErrorPasswordHistoryPolicyViolationException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyFailedAttemptsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyFailedAttemptsException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpConfirmSignUp struct { +} + +func (*awsAwsjson11_deserializeOpConfirmSignUp) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpConfirmSignUp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorConfirmSignUp(response, &metadata) + } + output := &ConfirmSignUpOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentConfirmSignUpOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorConfirmSignUp(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("ExpiredCodeException", errorCode): + return awsAwsjson11_deserializeErrorExpiredCodeException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyFailedAttemptsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyFailedAttemptsException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateGroup struct { +} + +func (*awsAwsjson11_deserializeOpCreateGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateGroup(response, &metadata) + } + output := &CreateGroupOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateGroupOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("GroupExistsException", errorCode): + return awsAwsjson11_deserializeErrorGroupExistsException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateIdentityProvider struct { +} + +func (*awsAwsjson11_deserializeOpCreateIdentityProvider) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateIdentityProvider) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateIdentityProvider(response, &metadata) + } + output := &CreateIdentityProviderOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateIdentityProviderOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateIdentityProvider(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("DuplicateProviderException", errorCode): + return awsAwsjson11_deserializeErrorDuplicateProviderException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateManagedLoginBranding struct { +} + +func (*awsAwsjson11_deserializeOpCreateManagedLoginBranding) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateManagedLoginBranding) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateManagedLoginBranding(response, &metadata) + } + output := &CreateManagedLoginBrandingOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateManagedLoginBrandingOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateManagedLoginBranding(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("ManagedLoginBrandingExistsException", errorCode): + return awsAwsjson11_deserializeErrorManagedLoginBrandingExistsException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateResourceServer struct { +} + +func (*awsAwsjson11_deserializeOpCreateResourceServer) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateResourceServer) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateResourceServer(response, &metadata) + } + output := &CreateResourceServerOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateResourceServerOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateResourceServer(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateUserImportJob struct { +} + +func (*awsAwsjson11_deserializeOpCreateUserImportJob) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateUserImportJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateUserImportJob(response, &metadata) + } + output := &CreateUserImportJobOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateUserImportJobOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateUserImportJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PreconditionNotMetException", errorCode): + return awsAwsjson11_deserializeErrorPreconditionNotMetException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateUserPool struct { +} + +func (*awsAwsjson11_deserializeOpCreateUserPool) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateUserPool) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateUserPool(response, &metadata) + } + output := &CreateUserPoolOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateUserPoolOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateUserPool(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("TierChangeNotAllowedException", errorCode): + return awsAwsjson11_deserializeErrorTierChangeNotAllowedException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserPoolTaggingException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolTaggingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateUserPoolClient struct { +} + +func (*awsAwsjson11_deserializeOpCreateUserPoolClient) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateUserPoolClient) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateUserPoolClient(response, &metadata) + } + output := &CreateUserPoolClientOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateUserPoolClientOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateUserPoolClient(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidOAuthFlowException", errorCode): + return awsAwsjson11_deserializeErrorInvalidOAuthFlowException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ScopeDoesNotExistException", errorCode): + return awsAwsjson11_deserializeErrorScopeDoesNotExistException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpCreateUserPoolDomain struct { +} + +func (*awsAwsjson11_deserializeOpCreateUserPoolDomain) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpCreateUserPoolDomain) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorCreateUserPoolDomain(response, &metadata) + } + output := &CreateUserPoolDomainOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentCreateUserPoolDomainOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorCreateUserPoolDomain(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteGroup struct { +} + +func (*awsAwsjson11_deserializeOpDeleteGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteGroup(response, &metadata) + } + output := &DeleteGroupOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteIdentityProvider struct { +} + +func (*awsAwsjson11_deserializeOpDeleteIdentityProvider) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteIdentityProvider) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteIdentityProvider(response, &metadata) + } + output := &DeleteIdentityProviderOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteIdentityProvider(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnsupportedIdentityProviderException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedIdentityProviderException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteManagedLoginBranding struct { +} + +func (*awsAwsjson11_deserializeOpDeleteManagedLoginBranding) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteManagedLoginBranding) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteManagedLoginBranding(response, &metadata) + } + output := &DeleteManagedLoginBrandingOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteManagedLoginBranding(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteResourceServer struct { +} + +func (*awsAwsjson11_deserializeOpDeleteResourceServer) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteResourceServer) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteResourceServer(response, &metadata) + } + output := &DeleteResourceServerOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteResourceServer(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteUser struct { +} + +func (*awsAwsjson11_deserializeOpDeleteUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteUser(response, &metadata) + } + output := &DeleteUserOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteUserAttributes struct { +} + +func (*awsAwsjson11_deserializeOpDeleteUserAttributes) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteUserAttributes) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteUserAttributes(response, &metadata) + } + output := &DeleteUserAttributesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDeleteUserAttributesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteUserAttributes(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteUserPool struct { +} + +func (*awsAwsjson11_deserializeOpDeleteUserPool) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteUserPool) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteUserPool(response, &metadata) + } + output := &DeleteUserPoolOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteUserPool(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserImportInProgressException", errorCode): + return awsAwsjson11_deserializeErrorUserImportInProgressException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteUserPoolClient struct { +} + +func (*awsAwsjson11_deserializeOpDeleteUserPoolClient) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteUserPoolClient) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteUserPoolClient(response, &metadata) + } + output := &DeleteUserPoolClientOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteUserPoolClient(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteUserPoolDomain struct { +} + +func (*awsAwsjson11_deserializeOpDeleteUserPoolDomain) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteUserPoolDomain) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteUserPoolDomain(response, &metadata) + } + output := &DeleteUserPoolDomainOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDeleteUserPoolDomainOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteUserPoolDomain(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDeleteWebAuthnCredential struct { +} + +func (*awsAwsjson11_deserializeOpDeleteWebAuthnCredential) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDeleteWebAuthnCredential) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDeleteWebAuthnCredential(response, &metadata) + } + output := &DeleteWebAuthnCredentialOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDeleteWebAuthnCredentialOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDeleteWebAuthnCredential(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeIdentityProvider struct { +} + +func (*awsAwsjson11_deserializeOpDescribeIdentityProvider) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeIdentityProvider) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeIdentityProvider(response, &metadata) + } + output := &DescribeIdentityProviderOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeIdentityProviderOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeIdentityProvider(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeManagedLoginBranding struct { +} + +func (*awsAwsjson11_deserializeOpDescribeManagedLoginBranding) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeManagedLoginBranding) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeManagedLoginBranding(response, &metadata) + } + output := &DescribeManagedLoginBrandingOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeManagedLoginBrandingOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeManagedLoginBranding(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeManagedLoginBrandingByClient struct { +} + +func (*awsAwsjson11_deserializeOpDescribeManagedLoginBrandingByClient) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeManagedLoginBrandingByClient) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeManagedLoginBrandingByClient(response, &metadata) + } + output := &DescribeManagedLoginBrandingByClientOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeManagedLoginBrandingByClientOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeManagedLoginBrandingByClient(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeResourceServer struct { +} + +func (*awsAwsjson11_deserializeOpDescribeResourceServer) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeResourceServer) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeResourceServer(response, &metadata) + } + output := &DescribeResourceServerOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeResourceServerOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeResourceServer(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeRiskConfiguration struct { +} + +func (*awsAwsjson11_deserializeOpDescribeRiskConfiguration) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeRiskConfiguration) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeRiskConfiguration(response, &metadata) + } + output := &DescribeRiskConfigurationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeRiskConfigurationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeRiskConfiguration(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserPoolAddOnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolAddOnNotEnabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeUserImportJob struct { +} + +func (*awsAwsjson11_deserializeOpDescribeUserImportJob) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeUserImportJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeUserImportJob(response, &metadata) + } + output := &DescribeUserImportJobOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeUserImportJobOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeUserImportJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeUserPool struct { +} + +func (*awsAwsjson11_deserializeOpDescribeUserPool) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeUserPool) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeUserPool(response, &metadata) + } + output := &DescribeUserPoolOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeUserPoolOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeUserPool(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserPoolTaggingException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolTaggingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeUserPoolClient struct { +} + +func (*awsAwsjson11_deserializeOpDescribeUserPoolClient) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeUserPoolClient) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeUserPoolClient(response, &metadata) + } + output := &DescribeUserPoolClientOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeUserPoolClientOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeUserPoolClient(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpDescribeUserPoolDomain struct { +} + +func (*awsAwsjson11_deserializeOpDescribeUserPoolDomain) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpDescribeUserPoolDomain) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorDescribeUserPoolDomain(response, &metadata) + } + output := &DescribeUserPoolDomainOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentDescribeUserPoolDomainOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorDescribeUserPoolDomain(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpForgetDevice struct { +} + +func (*awsAwsjson11_deserializeOpForgetDevice) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpForgetDevice) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorForgetDevice(response, &metadata) + } + output := &ForgetDeviceOutput{} + out.Result = output + + if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to discard response body, %w", err), + } + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorForgetDevice(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpForgotPassword struct { +} + +func (*awsAwsjson11_deserializeOpForgotPassword) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpForgotPassword) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorForgotPassword(response, &metadata) + } + output := &ForgotPasswordOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentForgotPasswordOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorForgotPassword(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetCSVHeader struct { +} + +func (*awsAwsjson11_deserializeOpGetCSVHeader) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetCSVHeader) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetCSVHeader(response, &metadata) + } + output := &GetCSVHeaderOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetCSVHeaderOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetCSVHeader(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetDevice struct { +} + +func (*awsAwsjson11_deserializeOpGetDevice) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetDevice) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetDevice(response, &metadata) + } + output := &GetDeviceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetDeviceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetDevice(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetGroup struct { +} + +func (*awsAwsjson11_deserializeOpGetGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetGroup(response, &metadata) + } + output := &GetGroupOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetGroupOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetIdentityProviderByIdentifier struct { +} + +func (*awsAwsjson11_deserializeOpGetIdentityProviderByIdentifier) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetIdentityProviderByIdentifier) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetIdentityProviderByIdentifier(response, &metadata) + } + output := &GetIdentityProviderByIdentifierOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetIdentityProviderByIdentifierOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetIdentityProviderByIdentifier(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetLogDeliveryConfiguration struct { +} + +func (*awsAwsjson11_deserializeOpGetLogDeliveryConfiguration) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetLogDeliveryConfiguration) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetLogDeliveryConfiguration(response, &metadata) + } + output := &GetLogDeliveryConfigurationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetLogDeliveryConfigurationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetLogDeliveryConfiguration(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetSigningCertificate struct { +} + +func (*awsAwsjson11_deserializeOpGetSigningCertificate) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetSigningCertificate) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetSigningCertificate(response, &metadata) + } + output := &GetSigningCertificateOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetSigningCertificateOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetSigningCertificate(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetTokensFromRefreshToken struct { +} + +func (*awsAwsjson11_deserializeOpGetTokensFromRefreshToken) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetTokensFromRefreshToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetTokensFromRefreshToken(response, &metadata) + } + output := &GetTokensFromRefreshTokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetTokensFromRefreshTokenOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetTokensFromRefreshToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("RefreshTokenReuseException", errorCode): + return awsAwsjson11_deserializeErrorRefreshTokenReuseException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetUICustomization struct { +} + +func (*awsAwsjson11_deserializeOpGetUICustomization) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetUICustomization) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetUICustomization(response, &metadata) + } + output := &GetUICustomizationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetUICustomizationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetUICustomization(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetUser struct { +} + +func (*awsAwsjson11_deserializeOpGetUser) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetUser) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetUser(response, &metadata) + } + output := &GetUserOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetUserOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetUser(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetUserAttributeVerificationCode struct { +} + +func (*awsAwsjson11_deserializeOpGetUserAttributeVerificationCode) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetUserAttributeVerificationCode) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetUserAttributeVerificationCode(response, &metadata) + } + output := &GetUserAttributeVerificationCodeOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetUserAttributeVerificationCodeOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetUserAttributeVerificationCode(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetUserAuthFactors struct { +} + +func (*awsAwsjson11_deserializeOpGetUserAuthFactors) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetUserAuthFactors) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetUserAuthFactors(response, &metadata) + } + output := &GetUserAuthFactorsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetUserAuthFactorsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetUserAuthFactors(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGetUserPoolMfaConfig struct { +} + +func (*awsAwsjson11_deserializeOpGetUserPoolMfaConfig) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGetUserPoolMfaConfig) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGetUserPoolMfaConfig(response, &metadata) + } + output := &GetUserPoolMfaConfigOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGetUserPoolMfaConfigOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGetUserPoolMfaConfig(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpGlobalSignOut struct { +} + +func (*awsAwsjson11_deserializeOpGlobalSignOut) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpGlobalSignOut) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorGlobalSignOut(response, &metadata) + } + output := &GlobalSignOutOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentGlobalSignOutOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorGlobalSignOut(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpInitiateAuth struct { +} + +func (*awsAwsjson11_deserializeOpInitiateAuth) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpInitiateAuth) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorInitiateAuth(response, &metadata) + } + output := &InitiateAuthOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentInitiateAuthOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorInitiateAuth(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UnsupportedOperationException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedOperationException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListDevices struct { +} + +func (*awsAwsjson11_deserializeOpListDevices) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListDevices) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListDevices(response, &metadata) + } + output := &ListDevicesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListDevicesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListDevices(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListGroups struct { +} + +func (*awsAwsjson11_deserializeOpListGroups) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListGroups) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListGroups(response, &metadata) + } + output := &ListGroupsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListGroupsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListGroups(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListIdentityProviders struct { +} + +func (*awsAwsjson11_deserializeOpListIdentityProviders) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListIdentityProviders) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListIdentityProviders(response, &metadata) + } + output := &ListIdentityProvidersOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListIdentityProvidersOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListIdentityProviders(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListResourceServers struct { +} + +func (*awsAwsjson11_deserializeOpListResourceServers) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListResourceServers) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListResourceServers(response, &metadata) + } + output := &ListResourceServersOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListResourceServersOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListResourceServers(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListTagsForResource struct { +} + +func (*awsAwsjson11_deserializeOpListTagsForResource) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListTagsForResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListTagsForResource(response, &metadata) + } + output := &ListTagsForResourceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListUserImportJobs struct { +} + +func (*awsAwsjson11_deserializeOpListUserImportJobs) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListUserImportJobs) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListUserImportJobs(response, &metadata) + } + output := &ListUserImportJobsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListUserImportJobsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListUserImportJobs(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListUserPoolClients struct { +} + +func (*awsAwsjson11_deserializeOpListUserPoolClients) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListUserPoolClients) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListUserPoolClients(response, &metadata) + } + output := &ListUserPoolClientsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListUserPoolClientsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListUserPoolClients(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListUserPools struct { +} + +func (*awsAwsjson11_deserializeOpListUserPools) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListUserPools) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListUserPools(response, &metadata) + } + output := &ListUserPoolsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListUserPoolsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListUserPools(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListUsers struct { +} + +func (*awsAwsjson11_deserializeOpListUsers) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListUsers) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListUsers(response, &metadata) + } + output := &ListUsersOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListUsersOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListUsers(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListUsersInGroup struct { +} + +func (*awsAwsjson11_deserializeOpListUsersInGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListUsersInGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListUsersInGroup(response, &metadata) + } + output := &ListUsersInGroupOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListUsersInGroupOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListUsersInGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpListWebAuthnCredentials struct { +} + +func (*awsAwsjson11_deserializeOpListWebAuthnCredentials) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpListWebAuthnCredentials) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorListWebAuthnCredentials(response, &metadata) + } + output := &ListWebAuthnCredentialsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentListWebAuthnCredentialsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorListWebAuthnCredentials(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpResendConfirmationCode struct { +} + +func (*awsAwsjson11_deserializeOpResendConfirmationCode) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpResendConfirmationCode) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorResendConfirmationCode(response, &metadata) + } + output := &ResendConfirmationCodeOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentResendConfirmationCodeOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorResendConfirmationCode(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpRespondToAuthChallenge struct { +} + +func (*awsAwsjson11_deserializeOpRespondToAuthChallenge) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpRespondToAuthChallenge) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorRespondToAuthChallenge(response, &metadata) + } + output := &RespondToAuthChallengeOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentRespondToAuthChallengeOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorRespondToAuthChallenge(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("ExpiredCodeException", errorCode): + return awsAwsjson11_deserializeErrorExpiredCodeException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("MFAMethodNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorMFAMethodNotFoundException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordHistoryPolicyViolationException", errorCode): + return awsAwsjson11_deserializeErrorPasswordHistoryPolicyViolationException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("SoftwareTokenMFANotFoundException", errorCode): + return awsAwsjson11_deserializeErrorSoftwareTokenMFANotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpRevokeToken struct { +} + +func (*awsAwsjson11_deserializeOpRevokeToken) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpRevokeToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorRevokeToken(response, &metadata) + } + output := &RevokeTokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentRevokeTokenOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorRevokeToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnauthorizedException", errorCode): + return awsAwsjson11_deserializeErrorUnauthorizedException(response, errorBody) + + case strings.EqualFold("UnsupportedOperationException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedOperationException(response, errorBody) + + case strings.EqualFold("UnsupportedTokenTypeException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedTokenTypeException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSetLogDeliveryConfiguration struct { +} + +func (*awsAwsjson11_deserializeOpSetLogDeliveryConfiguration) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSetLogDeliveryConfiguration) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSetLogDeliveryConfiguration(response, &metadata) + } + output := &SetLogDeliveryConfigurationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSetLogDeliveryConfigurationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSetLogDeliveryConfiguration(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSetRiskConfiguration struct { +} + +func (*awsAwsjson11_deserializeOpSetRiskConfiguration) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSetRiskConfiguration) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSetRiskConfiguration(response, &metadata) + } + output := &SetRiskConfigurationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSetRiskConfigurationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSetRiskConfiguration(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserPoolAddOnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolAddOnNotEnabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSetUICustomization struct { +} + +func (*awsAwsjson11_deserializeOpSetUICustomization) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSetUICustomization) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSetUICustomization(response, &metadata) + } + output := &SetUICustomizationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSetUICustomizationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSetUICustomization(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSetUserMFAPreference struct { +} + +func (*awsAwsjson11_deserializeOpSetUserMFAPreference) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSetUserMFAPreference) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSetUserMFAPreference(response, &metadata) + } + output := &SetUserMFAPreferenceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSetUserMFAPreferenceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSetUserMFAPreference(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSetUserPoolMfaConfig struct { +} + +func (*awsAwsjson11_deserializeOpSetUserPoolMfaConfig) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSetUserPoolMfaConfig) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSetUserPoolMfaConfig(response, &metadata) + } + output := &SetUserPoolMfaConfigOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSetUserPoolMfaConfigOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSetUserPoolMfaConfig(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSetUserSettings struct { +} + +func (*awsAwsjson11_deserializeOpSetUserSettings) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSetUserSettings) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSetUserSettings(response, &metadata) + } + output := &SetUserSettingsOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSetUserSettingsOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSetUserSettings(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpSignUp struct { +} + +func (*awsAwsjson11_deserializeOpSignUp) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpSignUp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorSignUp(response, &metadata) + } + output := &SignUpOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentSignUpOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorSignUp(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidPasswordException", errorCode): + return awsAwsjson11_deserializeErrorInvalidPasswordException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UsernameExistsException", errorCode): + return awsAwsjson11_deserializeErrorUsernameExistsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStartUserImportJob struct { +} + +func (*awsAwsjson11_deserializeOpStartUserImportJob) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStartUserImportJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStartUserImportJob(response, &metadata) + } + output := &StartUserImportJobOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStartUserImportJobOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStartUserImportJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PreconditionNotMetException", errorCode): + return awsAwsjson11_deserializeErrorPreconditionNotMetException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStartWebAuthnRegistration struct { +} + +func (*awsAwsjson11_deserializeOpStartWebAuthnRegistration) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStartWebAuthnRegistration) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStartWebAuthnRegistration(response, &metadata) + } + output := &StartWebAuthnRegistrationOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStartWebAuthnRegistrationOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStartWebAuthnRegistration(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("WebAuthnConfigurationMissingException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnConfigurationMissingException(response, errorBody) + + case strings.EqualFold("WebAuthnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorWebAuthnNotEnabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpStopUserImportJob struct { +} + +func (*awsAwsjson11_deserializeOpStopUserImportJob) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpStopUserImportJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorStopUserImportJob(response, &metadata) + } + output := &StopUserImportJobOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentStopUserImportJobOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorStopUserImportJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PreconditionNotMetException", errorCode): + return awsAwsjson11_deserializeErrorPreconditionNotMetException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpTagResource struct { +} + +func (*awsAwsjson11_deserializeOpTagResource) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpTagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorTagResource(response, &metadata) + } + output := &TagResourceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentTagResourceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUntagResource struct { +} + +func (*awsAwsjson11_deserializeOpUntagResource) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUntagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUntagResource(response, &metadata) + } + output := &UntagResourceOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUntagResourceOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateAuthEventFeedback struct { +} + +func (*awsAwsjson11_deserializeOpUpdateAuthEventFeedback) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateAuthEventFeedback) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateAuthEventFeedback(response, &metadata) + } + output := &UpdateAuthEventFeedbackOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateAuthEventFeedbackOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateAuthEventFeedback(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + case strings.EqualFold("UserPoolAddOnNotEnabledException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolAddOnNotEnabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateDeviceStatus struct { +} + +func (*awsAwsjson11_deserializeOpUpdateDeviceStatus) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateDeviceStatus) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateDeviceStatus(response, &metadata) + } + output := &UpdateDeviceStatusOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateDeviceStatusOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateDeviceStatus(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateGroup struct { +} + +func (*awsAwsjson11_deserializeOpUpdateGroup) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateGroup) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateGroup(response, &metadata) + } + output := &UpdateGroupOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateGroupOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateGroup(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateIdentityProvider struct { +} + +func (*awsAwsjson11_deserializeOpUpdateIdentityProvider) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateIdentityProvider) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateIdentityProvider(response, &metadata) + } + output := &UpdateIdentityProviderOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateIdentityProviderOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateIdentityProvider(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnsupportedIdentityProviderException", errorCode): + return awsAwsjson11_deserializeErrorUnsupportedIdentityProviderException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateManagedLoginBranding struct { +} + +func (*awsAwsjson11_deserializeOpUpdateManagedLoginBranding) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateManagedLoginBranding) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateManagedLoginBranding(response, &metadata) + } + output := &UpdateManagedLoginBrandingOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateManagedLoginBrandingOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateManagedLoginBranding(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateResourceServer struct { +} + +func (*awsAwsjson11_deserializeOpUpdateResourceServer) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateResourceServer) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateResourceServer(response, &metadata) + } + output := &UpdateResourceServerOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateResourceServerOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateResourceServer(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateUserAttributes struct { +} + +func (*awsAwsjson11_deserializeOpUpdateUserAttributes) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateUserAttributes) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateUserAttributes(response, &metadata) + } + output := &UpdateUserAttributesOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateUserAttributesOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateUserAttributes(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("CodeDeliveryFailureException", errorCode): + return awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response, errorBody) + + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("ExpiredCodeException", errorCode): + return awsAwsjson11_deserializeErrorExpiredCodeException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidLambdaResponseException", errorCode): + return awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UnexpectedLambdaException", errorCode): + return awsAwsjson11_deserializeErrorUnexpectedLambdaException(response, errorBody) + + case strings.EqualFold("UserLambdaValidationException", errorCode): + return awsAwsjson11_deserializeErrorUserLambdaValidationException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateUserPool struct { +} + +func (*awsAwsjson11_deserializeOpUpdateUserPool) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateUserPool) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateUserPool(response, &metadata) + } + output := &UpdateUserPoolOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateUserPoolOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateUserPool(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidEmailRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleAccessPolicyException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response, errorBody) + + case strings.EqualFold("InvalidSmsRoleTrustRelationshipException", errorCode): + return awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TierChangeNotAllowedException", errorCode): + return awsAwsjson11_deserializeErrorTierChangeNotAllowedException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserImportInProgressException", errorCode): + return awsAwsjson11_deserializeErrorUserImportInProgressException(response, errorBody) + + case strings.EqualFold("UserPoolTaggingException", errorCode): + return awsAwsjson11_deserializeErrorUserPoolTaggingException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateUserPoolClient struct { +} + +func (*awsAwsjson11_deserializeOpUpdateUserPoolClient) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateUserPoolClient) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateUserPoolClient(response, &metadata) + } + output := &UpdateUserPoolClientOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateUserPoolClientOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateUserPoolClient(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidOAuthFlowException", errorCode): + return awsAwsjson11_deserializeErrorInvalidOAuthFlowException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("ScopeDoesNotExistException", errorCode): + return awsAwsjson11_deserializeErrorScopeDoesNotExistException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpUpdateUserPoolDomain struct { +} + +func (*awsAwsjson11_deserializeOpUpdateUserPoolDomain) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpUpdateUserPoolDomain) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorUpdateUserPoolDomain(response, &metadata) + } + output := &UpdateUserPoolDomainOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentUpdateUserPoolDomainOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorUpdateUserPoolDomain(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("ConcurrentModificationException", errorCode): + return awsAwsjson11_deserializeErrorConcurrentModificationException(response, errorBody) + + case strings.EqualFold("FeatureUnavailableInTierException", errorCode): + return awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpVerifySoftwareToken struct { +} + +func (*awsAwsjson11_deserializeOpVerifySoftwareToken) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpVerifySoftwareToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorVerifySoftwareToken(response, &metadata) + } + output := &VerifySoftwareTokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentVerifySoftwareTokenOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorVerifySoftwareToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("EnableSoftwareTokenMFAException", errorCode): + return awsAwsjson11_deserializeErrorEnableSoftwareTokenMFAException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("InvalidUserPoolConfigurationException", errorCode): + return awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("SoftwareTokenMFANotFoundException", errorCode): + return awsAwsjson11_deserializeErrorSoftwareTokenMFANotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +type awsAwsjson11_deserializeOpVerifyUserAttribute struct { +} + +func (*awsAwsjson11_deserializeOpVerifyUserAttribute) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsjson11_deserializeOpVerifyUserAttribute) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsjson11_deserializeOpErrorVerifyUserAttribute(response, &metadata) + } + output := &VerifyUserAttributeOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsAwsjson11_deserializeOpDocumentVerifyUserAttributeOutput(&output, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsjson11_deserializeOpErrorVerifyUserAttribute(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + bodyInfo, err := getProtocolErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok { + errorCode = restjson.SanitizeErrorCode(typ) + } + if len(bodyInfo.Message) != 0 { + errorMessage = bodyInfo.Message + } + switch { + case strings.EqualFold("AliasExistsException", errorCode): + return awsAwsjson11_deserializeErrorAliasExistsException(response, errorBody) + + case strings.EqualFold("CodeMismatchException", errorCode): + return awsAwsjson11_deserializeErrorCodeMismatchException(response, errorBody) + + case strings.EqualFold("ExpiredCodeException", errorCode): + return awsAwsjson11_deserializeErrorExpiredCodeException(response, errorBody) + + case strings.EqualFold("ForbiddenException", errorCode): + return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody) + + case strings.EqualFold("InternalErrorException", errorCode): + return awsAwsjson11_deserializeErrorInternalErrorException(response, errorBody) + + case strings.EqualFold("InvalidParameterException", errorCode): + return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) + + case strings.EqualFold("LimitExceededException", errorCode): + return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) + + case strings.EqualFold("NotAuthorizedException", errorCode): + return awsAwsjson11_deserializeErrorNotAuthorizedException(response, errorBody) + + case strings.EqualFold("PasswordResetRequiredException", errorCode): + return awsAwsjson11_deserializeErrorPasswordResetRequiredException(response, errorBody) + + case strings.EqualFold("ResourceNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) + + case strings.EqualFold("TooManyRequestsException", errorCode): + return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody) + + case strings.EqualFold("UserNotConfirmedException", errorCode): + return awsAwsjson11_deserializeErrorUserNotConfirmedException(response, errorBody) + + case strings.EqualFold("UserNotFoundException", errorCode): + return awsAwsjson11_deserializeErrorUserNotFoundException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +func awsAwsjson11_deserializeErrorAliasExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.AliasExistsException{} + err := awsAwsjson11_deserializeDocumentAliasExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorCodeDeliveryFailureException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.CodeDeliveryFailureException{} + err := awsAwsjson11_deserializeDocumentCodeDeliveryFailureException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorCodeMismatchException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.CodeMismatchException{} + err := awsAwsjson11_deserializeDocumentCodeMismatchException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorConcurrentModificationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ConcurrentModificationException{} + err := awsAwsjson11_deserializeDocumentConcurrentModificationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorDeviceKeyExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.DeviceKeyExistsException{} + err := awsAwsjson11_deserializeDocumentDeviceKeyExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorDuplicateProviderException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.DuplicateProviderException{} + err := awsAwsjson11_deserializeDocumentDuplicateProviderException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorEnableSoftwareTokenMFAException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.EnableSoftwareTokenMFAException{} + err := awsAwsjson11_deserializeDocumentEnableSoftwareTokenMFAException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorExpiredCodeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ExpiredCodeException{} + err := awsAwsjson11_deserializeDocumentExpiredCodeException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorFeatureUnavailableInTierException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.FeatureUnavailableInTierException{} + err := awsAwsjson11_deserializeDocumentFeatureUnavailableInTierException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorForbiddenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ForbiddenException{} + err := awsAwsjson11_deserializeDocumentForbiddenException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorGroupExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.GroupExistsException{} + err := awsAwsjson11_deserializeDocumentGroupExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInternalErrorException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InternalErrorException{} + err := awsAwsjson11_deserializeDocumentInternalErrorException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidEmailRoleAccessPolicyException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidEmailRoleAccessPolicyException{} + err := awsAwsjson11_deserializeDocumentInvalidEmailRoleAccessPolicyException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidLambdaResponseException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidLambdaResponseException{} + err := awsAwsjson11_deserializeDocumentInvalidLambdaResponseException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidOAuthFlowException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidOAuthFlowException{} + err := awsAwsjson11_deserializeDocumentInvalidOAuthFlowException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidParameterException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidParameterException{} + err := awsAwsjson11_deserializeDocumentInvalidParameterException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidPasswordException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidPasswordException{} + err := awsAwsjson11_deserializeDocumentInvalidPasswordException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidSmsRoleAccessPolicyException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidSmsRoleAccessPolicyException{} + err := awsAwsjson11_deserializeDocumentInvalidSmsRoleAccessPolicyException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidSmsRoleTrustRelationshipException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidSmsRoleTrustRelationshipException{} + err := awsAwsjson11_deserializeDocumentInvalidSmsRoleTrustRelationshipException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorInvalidUserPoolConfigurationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.InvalidUserPoolConfigurationException{} + err := awsAwsjson11_deserializeDocumentInvalidUserPoolConfigurationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorLimitExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.LimitExceededException{} + err := awsAwsjson11_deserializeDocumentLimitExceededException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorManagedLoginBrandingExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ManagedLoginBrandingExistsException{} + err := awsAwsjson11_deserializeDocumentManagedLoginBrandingExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorMFAMethodNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.MFAMethodNotFoundException{} + err := awsAwsjson11_deserializeDocumentMFAMethodNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorNotAuthorizedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.NotAuthorizedException{} + err := awsAwsjson11_deserializeDocumentNotAuthorizedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorPasswordHistoryPolicyViolationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.PasswordHistoryPolicyViolationException{} + err := awsAwsjson11_deserializeDocumentPasswordHistoryPolicyViolationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorPasswordResetRequiredException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.PasswordResetRequiredException{} + err := awsAwsjson11_deserializeDocumentPasswordResetRequiredException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorPreconditionNotMetException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.PreconditionNotMetException{} + err := awsAwsjson11_deserializeDocumentPreconditionNotMetException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorRefreshTokenReuseException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.RefreshTokenReuseException{} + err := awsAwsjson11_deserializeDocumentRefreshTokenReuseException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorResourceNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ResourceNotFoundException{} + err := awsAwsjson11_deserializeDocumentResourceNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorScopeDoesNotExistException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.ScopeDoesNotExistException{} + err := awsAwsjson11_deserializeDocumentScopeDoesNotExistException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorSoftwareTokenMFANotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.SoftwareTokenMFANotFoundException{} + err := awsAwsjson11_deserializeDocumentSoftwareTokenMFANotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorTierChangeNotAllowedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.TierChangeNotAllowedException{} + err := awsAwsjson11_deserializeDocumentTierChangeNotAllowedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorTooManyFailedAttemptsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.TooManyFailedAttemptsException{} + err := awsAwsjson11_deserializeDocumentTooManyFailedAttemptsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorTooManyRequestsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.TooManyRequestsException{} + err := awsAwsjson11_deserializeDocumentTooManyRequestsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnauthorizedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnauthorizedException{} + err := awsAwsjson11_deserializeDocumentUnauthorizedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnexpectedLambdaException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnexpectedLambdaException{} + err := awsAwsjson11_deserializeDocumentUnexpectedLambdaException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnsupportedIdentityProviderException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnsupportedIdentityProviderException{} + err := awsAwsjson11_deserializeDocumentUnsupportedIdentityProviderException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnsupportedOperationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnsupportedOperationException{} + err := awsAwsjson11_deserializeDocumentUnsupportedOperationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnsupportedTokenTypeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnsupportedTokenTypeException{} + err := awsAwsjson11_deserializeDocumentUnsupportedTokenTypeException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUnsupportedUserStateException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UnsupportedUserStateException{} + err := awsAwsjson11_deserializeDocumentUnsupportedUserStateException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUserImportInProgressException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UserImportInProgressException{} + err := awsAwsjson11_deserializeDocumentUserImportInProgressException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUserLambdaValidationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UserLambdaValidationException{} + err := awsAwsjson11_deserializeDocumentUserLambdaValidationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUsernameExistsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UsernameExistsException{} + err := awsAwsjson11_deserializeDocumentUsernameExistsException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUserNotConfirmedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UserNotConfirmedException{} + err := awsAwsjson11_deserializeDocumentUserNotConfirmedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUserNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UserNotFoundException{} + err := awsAwsjson11_deserializeDocumentUserNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUserPoolAddOnNotEnabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UserPoolAddOnNotEnabledException{} + err := awsAwsjson11_deserializeDocumentUserPoolAddOnNotEnabledException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorUserPoolTaggingException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.UserPoolTaggingException{} + err := awsAwsjson11_deserializeDocumentUserPoolTaggingException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnChallengeNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnChallengeNotFoundException{} + err := awsAwsjson11_deserializeDocumentWebAuthnChallengeNotFoundException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnClientMismatchException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnClientMismatchException{} + err := awsAwsjson11_deserializeDocumentWebAuthnClientMismatchException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnConfigurationMissingException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnConfigurationMissingException{} + err := awsAwsjson11_deserializeDocumentWebAuthnConfigurationMissingException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnCredentialNotSupportedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnCredentialNotSupportedException{} + err := awsAwsjson11_deserializeDocumentWebAuthnCredentialNotSupportedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnNotEnabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnNotEnabledException{} + err := awsAwsjson11_deserializeDocumentWebAuthnNotEnabledException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnOriginNotAllowedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnOriginNotAllowedException{} + err := awsAwsjson11_deserializeDocumentWebAuthnOriginNotAllowedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeErrorWebAuthnRelyingPartyMismatchException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + output := &types.WebAuthnRelyingPartyMismatchException{} + err := awsAwsjson11_deserializeDocumentWebAuthnRelyingPartyMismatchException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + return output +} + +func awsAwsjson11_deserializeDocumentAccountRecoverySettingType(v **types.AccountRecoverySettingType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccountRecoverySettingType + if *v == nil { + sv = &types.AccountRecoverySettingType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "RecoveryMechanisms": + if err := awsAwsjson11_deserializeDocumentRecoveryMechanismsType(&sv.RecoveryMechanisms, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAccountTakeoverActionsType(v **types.AccountTakeoverActionsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccountTakeoverActionsType + if *v == nil { + sv = &types.AccountTakeoverActionsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "HighAction": + if err := awsAwsjson11_deserializeDocumentAccountTakeoverActionType(&sv.HighAction, value); err != nil { + return err + } + + case "LowAction": + if err := awsAwsjson11_deserializeDocumentAccountTakeoverActionType(&sv.LowAction, value); err != nil { + return err + } + + case "MediumAction": + if err := awsAwsjson11_deserializeDocumentAccountTakeoverActionType(&sv.MediumAction, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAccountTakeoverActionType(v **types.AccountTakeoverActionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccountTakeoverActionType + if *v == nil { + sv = &types.AccountTakeoverActionType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "EventAction": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AccountTakeoverEventActionType to be of type string, got %T instead", value) + } + sv.EventAction = types.AccountTakeoverEventActionType(jtv) + } + + case "Notify": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected AccountTakeoverActionNotifyType to be of type *bool, got %T instead", value) + } + sv.Notify = jtv + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAccountTakeoverRiskConfigurationType(v **types.AccountTakeoverRiskConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccountTakeoverRiskConfigurationType + if *v == nil { + sv = &types.AccountTakeoverRiskConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Actions": + if err := awsAwsjson11_deserializeDocumentAccountTakeoverActionsType(&sv.Actions, value); err != nil { + return err + } + + case "NotifyConfiguration": + if err := awsAwsjson11_deserializeDocumentNotifyConfigurationType(&sv.NotifyConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAdminCreateUserConfigType(v **types.AdminCreateUserConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AdminCreateUserConfigType + if *v == nil { + sv = &types.AdminCreateUserConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AllowAdminCreateUserOnly": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.AllowAdminCreateUserOnly = jtv + } + + case "InviteMessageTemplate": + if err := awsAwsjson11_deserializeDocumentMessageTemplateType(&sv.InviteMessageTemplate, value); err != nil { + return err + } + + case "UnusedAccountValidityDays": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected AdminCreateUserUnusedAccountValidityDaysType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.UnusedAccountValidityDays = int32(i64) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAdvancedSecurityAdditionalFlowsType(v **types.AdvancedSecurityAdditionalFlowsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AdvancedSecurityAdditionalFlowsType + if *v == nil { + sv = &types.AdvancedSecurityAdditionalFlowsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CustomAuthMode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdvancedSecurityEnabledModeType to be of type string, got %T instead", value) + } + sv.CustomAuthMode = types.AdvancedSecurityEnabledModeType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAliasAttributesListType(v *[]types.AliasAttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AliasAttributeType + if *v == nil { + cv = []types.AliasAttributeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AliasAttributeType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AliasAttributeType to be of type string, got %T instead", value) + } + col = types.AliasAttributeType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAliasExistsException(v **types.AliasExistsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AliasExistsException + if *v == nil { + sv = &types.AliasExistsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAllowedFirstAuthFactorsListType(v *[]types.AuthFactorType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AuthFactorType + if *v == nil { + cv = []types.AuthFactorType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AuthFactorType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AuthFactorType to be of type string, got %T instead", value) + } + col = types.AuthFactorType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAnalyticsConfigurationType(v **types.AnalyticsConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AnalyticsConfigurationType + if *v == nil { + sv = &types.AnalyticsConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ApplicationArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.ApplicationArn = ptr.String(jtv) + } + + case "ApplicationId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected HexStringType to be of type string, got %T instead", value) + } + sv.ApplicationId = ptr.String(jtv) + } + + case "ExternalId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.ExternalId = ptr.String(jtv) + } + + case "RoleArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.RoleArn = ptr.String(jtv) + } + + case "UserDataShared": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.UserDataShared = jtv + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAssetListType(v *[]types.AssetType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AssetType + if *v == nil { + cv = []types.AssetType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AssetType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentAssetType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAssetType(v **types.AssetType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AssetType + if *v == nil { + sv = &types.AssetType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Bytes": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AssetBytesType to be []byte, got %T instead", value) + } + dv, err := base64.StdEncoding.DecodeString(jtv) + if err != nil { + return fmt.Errorf("failed to base64 decode AssetBytesType, %w", err) + } + sv.Bytes = dv + } + + case "Category": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AssetCategoryType to be of type string, got %T instead", value) + } + sv.Category = types.AssetCategoryType(jtv) + } + + case "ColorMode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ColorSchemeModeType to be of type string, got %T instead", value) + } + sv.ColorMode = types.ColorSchemeModeType(jtv) + } + + case "Extension": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AssetExtensionType to be of type string, got %T instead", value) + } + sv.Extension = types.AssetExtensionType(jtv) + } + + case "ResourceId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ResourceIdType to be of type string, got %T instead", value) + } + sv.ResourceId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAttributeListType(v *[]types.AttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AttributeType + if *v == nil { + cv = []types.AttributeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AttributeType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentAttributeType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAttributeMappingType(v *map[string]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var mv map[string]string + if *v == nil { + mv = map[string]string{} + } else { + mv = *v + } + + for key, value := range shape { + var parsedVal string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + parsedVal = jtv + } + mv[key] = parsedVal + + } + *v = mv + return nil +} + +func awsAwsjson11_deserializeDocumentAttributesRequireVerificationBeforeUpdateType(v *[]types.VerifiedAttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.VerifiedAttributeType + if *v == nil { + cv = []types.VerifiedAttributeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.VerifiedAttributeType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected VerifiedAttributeType to be of type string, got %T instead", value) + } + col = types.VerifiedAttributeType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAttributeType(v **types.AttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AttributeType + if *v == nil { + sv = &types.AttributeType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AttributeNameType to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "Value": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AttributeValueType to be of type string, got %T instead", value) + } + sv.Value = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAuthenticationResultType(v **types.AuthenticationResultType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AuthenticationResultType + if *v == nil { + sv = &types.AuthenticationResultType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AccessToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TokenModelType to be of type string, got %T instead", value) + } + sv.AccessToken = ptr.String(jtv) + } + + case "ExpiresIn": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected IntegerType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ExpiresIn = int32(i64) + } + + case "IdToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TokenModelType to be of type string, got %T instead", value) + } + sv.IdToken = ptr.String(jtv) + } + + case "NewDeviceMetadata": + if err := awsAwsjson11_deserializeDocumentNewDeviceMetadataType(&sv.NewDeviceMetadata, value); err != nil { + return err + } + + case "RefreshToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TokenModelType to be of type string, got %T instead", value) + } + sv.RefreshToken = ptr.String(jtv) + } + + case "TokenType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.TokenType = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAuthEventsType(v *[]types.AuthEventType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AuthEventType + if *v == nil { + cv = []types.AuthEventType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AuthEventType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentAuthEventType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentAuthEventType(v **types.AuthEventType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AuthEventType + if *v == nil { + sv = &types.AuthEventType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ChallengeResponses": + if err := awsAwsjson11_deserializeDocumentChallengeResponseListType(&sv.ChallengeResponses, value); err != nil { + return err + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "EventContextData": + if err := awsAwsjson11_deserializeDocumentEventContextDataType(&sv.EventContextData, value); err != nil { + return err + } + + case "EventFeedback": + if err := awsAwsjson11_deserializeDocumentEventFeedbackType(&sv.EventFeedback, value); err != nil { + return err + } + + case "EventId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.EventId = ptr.String(jtv) + } + + case "EventResponse": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EventResponseType to be of type string, got %T instead", value) + } + sv.EventResponse = types.EventResponseType(jtv) + } + + case "EventRisk": + if err := awsAwsjson11_deserializeDocumentEventRiskType(&sv.EventRisk, value); err != nil { + return err + } + + case "EventType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EventType to be of type string, got %T instead", value) + } + sv.EventType = types.EventType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentAvailableChallengeListType(v *[]types.ChallengeNameType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ChallengeNameType + if *v == nil { + cv = []types.ChallengeNameType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ChallengeNameType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeNameType to be of type string, got %T instead", value) + } + col = types.ChallengeNameType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentBlockedIPRangeListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentCallbackURLsListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RedirectUrlType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentChallengeParametersType(v *map[string]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var mv map[string]string + if *v == nil { + mv = map[string]string{} + } else { + mv = *v + } + + for key, value := range shape { + var parsedVal string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + parsedVal = jtv + } + mv[key] = parsedVal + + } + *v = mv + return nil +} + +func awsAwsjson11_deserializeDocumentChallengeResponseListType(v *[]types.ChallengeResponseType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ChallengeResponseType + if *v == nil { + cv = []types.ChallengeResponseType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ChallengeResponseType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentChallengeResponseType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentChallengeResponseType(v **types.ChallengeResponseType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ChallengeResponseType + if *v == nil { + sv = &types.ChallengeResponseType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ChallengeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeName to be of type string, got %T instead", value) + } + sv.ChallengeName = types.ChallengeName(jtv) + } + + case "ChallengeResponse": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeResponse to be of type string, got %T instead", value) + } + sv.ChallengeResponse = types.ChallengeResponse(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentClientPermissionListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientPermissionType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentCloudWatchLogsConfigurationType(v **types.CloudWatchLogsConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CloudWatchLogsConfigurationType + if *v == nil { + sv = &types.CloudWatchLogsConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LogGroupArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.LogGroupArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCodeDeliveryDetailsListType(v *[]types.CodeDeliveryDetailsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.CodeDeliveryDetailsType + if *v == nil { + cv = []types.CodeDeliveryDetailsType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.CodeDeliveryDetailsType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentCodeDeliveryDetailsType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentCodeDeliveryDetailsType(v **types.CodeDeliveryDetailsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CodeDeliveryDetailsType + if *v == nil { + sv = &types.CodeDeliveryDetailsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AttributeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AttributeNameType to be of type string, got %T instead", value) + } + sv.AttributeName = ptr.String(jtv) + } + + case "DeliveryMedium": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DeliveryMediumType to be of type string, got %T instead", value) + } + sv.DeliveryMedium = types.DeliveryMediumType(jtv) + } + + case "Destination": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.Destination = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCodeDeliveryFailureException(v **types.CodeDeliveryFailureException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CodeDeliveryFailureException + if *v == nil { + sv = &types.CodeDeliveryFailureException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCodeMismatchException(v **types.CodeMismatchException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CodeMismatchException + if *v == nil { + sv = &types.CodeMismatchException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCompromisedCredentialsActionsType(v **types.CompromisedCredentialsActionsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CompromisedCredentialsActionsType + if *v == nil { + sv = &types.CompromisedCredentialsActionsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "EventAction": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CompromisedCredentialsEventActionType to be of type string, got %T instead", value) + } + sv.EventAction = types.CompromisedCredentialsEventActionType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCompromisedCredentialsRiskConfigurationType(v **types.CompromisedCredentialsRiskConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CompromisedCredentialsRiskConfigurationType + if *v == nil { + sv = &types.CompromisedCredentialsRiskConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Actions": + if err := awsAwsjson11_deserializeDocumentCompromisedCredentialsActionsType(&sv.Actions, value); err != nil { + return err + } + + case "EventFilter": + if err := awsAwsjson11_deserializeDocumentEventFiltersType(&sv.EventFilter, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentConcurrentModificationException(v **types.ConcurrentModificationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ConcurrentModificationException + if *v == nil { + sv = &types.ConcurrentModificationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentConfiguredUserAuthFactorsListType(v *[]types.AuthFactorType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.AuthFactorType + if *v == nil { + cv = []types.AuthFactorType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.AuthFactorType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AuthFactorType to be of type string, got %T instead", value) + } + col = types.AuthFactorType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentCustomDomainConfigType(v **types.CustomDomainConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CustomDomainConfigType + if *v == nil { + sv = &types.CustomDomainConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CertificateArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.CertificateArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCustomEmailLambdaVersionConfigType(v **types.CustomEmailLambdaVersionConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CustomEmailLambdaVersionConfigType + if *v == nil { + sv = &types.CustomEmailLambdaVersionConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LambdaArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.LambdaArn = ptr.String(jtv) + } + + case "LambdaVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CustomEmailSenderLambdaVersionType to be of type string, got %T instead", value) + } + sv.LambdaVersion = types.CustomEmailSenderLambdaVersionType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentCustomSMSLambdaVersionConfigType(v **types.CustomSMSLambdaVersionConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CustomSMSLambdaVersionConfigType + if *v == nil { + sv = &types.CustomSMSLambdaVersionConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LambdaArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.LambdaArn = ptr.String(jtv) + } + + case "LambdaVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CustomSMSSenderLambdaVersionType to be of type string, got %T instead", value) + } + sv.LambdaVersion = types.CustomSMSSenderLambdaVersionType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDeviceConfigurationType(v **types.DeviceConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DeviceConfigurationType + if *v == nil { + sv = &types.DeviceConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ChallengeRequiredOnNewDevice": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.ChallengeRequiredOnNewDevice = jtv + } + + case "DeviceOnlyRememberedOnUserPrompt": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.DeviceOnlyRememberedOnUserPrompt = jtv + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDeviceKeyExistsException(v **types.DeviceKeyExistsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DeviceKeyExistsException + if *v == nil { + sv = &types.DeviceKeyExistsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDeviceListType(v *[]types.DeviceType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.DeviceType + if *v == nil { + cv = []types.DeviceType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.DeviceType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentDeviceType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentDeviceType(v **types.DeviceType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DeviceType + if *v == nil { + sv = &types.DeviceType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DeviceAttributes": + if err := awsAwsjson11_deserializeDocumentAttributeListType(&sv.DeviceAttributes, value); err != nil { + return err + } + + case "DeviceCreateDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.DeviceCreateDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "DeviceKey": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DeviceKeyType to be of type string, got %T instead", value) + } + sv.DeviceKey = ptr.String(jtv) + } + + case "DeviceLastAuthenticatedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.DeviceLastAuthenticatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "DeviceLastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.DeviceLastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDocument(v *document.Interface, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + *v = internaldocument.NewDocumentUnmarshaler(value) + return nil +} + +func awsAwsjson11_deserializeDocumentDomainDescriptionType(v **types.DomainDescriptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DomainDescriptionType + if *v == nil { + sv = &types.DomainDescriptionType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AWSAccountId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AWSAccountIdType to be of type string, got %T instead", value) + } + sv.AWSAccountId = ptr.String(jtv) + } + + case "CloudFrontDistribution": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.CloudFrontDistribution = ptr.String(jtv) + } + + case "CustomDomainConfig": + if err := awsAwsjson11_deserializeDocumentCustomDomainConfigType(&sv.CustomDomainConfig, value); err != nil { + return err + } + + case "Domain": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainType to be of type string, got %T instead", value) + } + sv.Domain = ptr.String(jtv) + } + + case "ManagedLoginVersion": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected WrappedIntegerType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ManagedLoginVersion = ptr.Int32(int32(i64)) + } + + case "S3Bucket": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3BucketType to be of type string, got %T instead", value) + } + sv.S3Bucket = ptr.String(jtv) + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainStatusType to be of type string, got %T instead", value) + } + sv.Status = types.DomainStatusType(jtv) + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + case "Version": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainVersionType to be of type string, got %T instead", value) + } + sv.Version = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentDuplicateProviderException(v **types.DuplicateProviderException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.DuplicateProviderException + if *v == nil { + sv = &types.DuplicateProviderException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEmailConfigurationType(v **types.EmailConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EmailConfigurationType + if *v == nil { + sv = &types.EmailConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ConfigurationSet": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SESConfigurationSet to be of type string, got %T instead", value) + } + sv.ConfigurationSet = ptr.String(jtv) + } + + case "EmailSendingAccount": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailSendingAccountType to be of type string, got %T instead", value) + } + sv.EmailSendingAccount = types.EmailSendingAccountType(jtv) + } + + case "From": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.From = ptr.String(jtv) + } + + case "ReplyToEmailAddress": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailAddressType to be of type string, got %T instead", value) + } + sv.ReplyToEmailAddress = ptr.String(jtv) + } + + case "SourceArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.SourceArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEmailMfaConfigType(v **types.EmailMfaConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EmailMfaConfigType + if *v == nil { + sv = &types.EmailMfaConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailMfaMessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + case "Subject": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailMfaSubjectType to be of type string, got %T instead", value) + } + sv.Subject = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEnableSoftwareTokenMFAException(v **types.EnableSoftwareTokenMFAException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EnableSoftwareTokenMFAException + if *v == nil { + sv = &types.EnableSoftwareTokenMFAException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEventContextDataType(v **types.EventContextDataType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EventContextDataType + if *v == nil { + sv = &types.EventContextDataType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "City": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.City = ptr.String(jtv) + } + + case "Country": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.Country = ptr.String(jtv) + } + + case "DeviceName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.DeviceName = ptr.String(jtv) + } + + case "IpAddress": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.IpAddress = ptr.String(jtv) + } + + case "Timezone": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.Timezone = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEventFeedbackType(v **types.EventFeedbackType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EventFeedbackType + if *v == nil { + sv = &types.EventFeedbackType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "FeedbackDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.FeedbackDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "FeedbackValue": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected FeedbackValueType to be of type string, got %T instead", value) + } + sv.FeedbackValue = types.FeedbackValueType(jtv) + } + + case "Provider": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.Provider = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentEventFiltersType(v *[]types.EventFilterType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.EventFilterType + if *v == nil { + cv = []types.EventFilterType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.EventFilterType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EventFilterType to be of type string, got %T instead", value) + } + col = types.EventFilterType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentEventRiskType(v **types.EventRiskType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.EventRiskType + if *v == nil { + sv = &types.EventRiskType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CompromisedCredentialsDetected": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected WrappedBooleanType to be of type *bool, got %T instead", value) + } + sv.CompromisedCredentialsDetected = ptr.Bool(jtv) + } + + case "RiskDecision": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RiskDecisionType to be of type string, got %T instead", value) + } + sv.RiskDecision = types.RiskDecisionType(jtv) + } + + case "RiskLevel": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RiskLevelType to be of type string, got %T instead", value) + } + sv.RiskLevel = types.RiskLevelType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExpiredCodeException(v **types.ExpiredCodeException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ExpiredCodeException + if *v == nil { + sv = &types.ExpiredCodeException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentExplicitAuthFlowsListType(v *[]types.ExplicitAuthFlowsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ExplicitAuthFlowsType + if *v == nil { + cv = []types.ExplicitAuthFlowsType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ExplicitAuthFlowsType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ExplicitAuthFlowsType to be of type string, got %T instead", value) + } + col = types.ExplicitAuthFlowsType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentFeatureUnavailableInTierException(v **types.FeatureUnavailableInTierException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.FeatureUnavailableInTierException + if *v == nil { + sv = &types.FeatureUnavailableInTierException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentFirehoseConfigurationType(v **types.FirehoseConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.FirehoseConfigurationType + if *v == nil { + sv = &types.FirehoseConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "StreamArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.StreamArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentForbiddenException(v **types.ForbiddenException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ForbiddenException + if *v == nil { + sv = &types.ForbiddenException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentGroupExistsException(v **types.GroupExistsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.GroupExistsException + if *v == nil { + sv = &types.GroupExistsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentGroupListType(v *[]types.GroupType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.GroupType + if *v == nil { + cv = []types.GroupType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.GroupType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentGroupType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentGroupType(v **types.GroupType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.GroupType + if *v == nil { + sv = &types.GroupType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "Description": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DescriptionType to be of type string, got %T instead", value) + } + sv.Description = ptr.String(jtv) + } + + case "GroupName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected GroupNameType to be of type string, got %T instead", value) + } + sv.GroupName = ptr.String(jtv) + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "Precedence": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected PrecedenceType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Precedence = ptr.Int32(int32(i64)) + } + + case "RoleArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.RoleArn = ptr.String(jtv) + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentIdentityProviderType(v **types.IdentityProviderType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.IdentityProviderType + if *v == nil { + sv = &types.IdentityProviderType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AttributeMapping": + if err := awsAwsjson11_deserializeDocumentAttributeMappingType(&sv.AttributeMapping, value); err != nil { + return err + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "IdpIdentifiers": + if err := awsAwsjson11_deserializeDocumentIdpIdentifiersListType(&sv.IdpIdentifiers, value); err != nil { + return err + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "ProviderDetails": + if err := awsAwsjson11_deserializeDocumentProviderDetailsType(&sv.ProviderDetails, value); err != nil { + return err + } + + case "ProviderName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ProviderNameType to be of type string, got %T instead", value) + } + sv.ProviderName = ptr.String(jtv) + } + + case "ProviderType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected IdentityProviderTypeType to be of type string, got %T instead", value) + } + sv.ProviderType = types.IdentityProviderTypeType(jtv) + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentIdpIdentifiersListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected IdpIdentifierType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentInternalErrorException(v **types.InternalErrorException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InternalErrorException + if *v == nil { + sv = &types.InternalErrorException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidEmailRoleAccessPolicyException(v **types.InvalidEmailRoleAccessPolicyException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidEmailRoleAccessPolicyException + if *v == nil { + sv = &types.InvalidEmailRoleAccessPolicyException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidLambdaResponseException(v **types.InvalidLambdaResponseException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidLambdaResponseException + if *v == nil { + sv = &types.InvalidLambdaResponseException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidOAuthFlowException(v **types.InvalidOAuthFlowException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidOAuthFlowException + if *v == nil { + sv = &types.InvalidOAuthFlowException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidParameterException(v **types.InvalidParameterException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidParameterException + if *v == nil { + sv = &types.InvalidParameterException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + case "reasonCode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected InvalidParameterExceptionReasonCodeType to be of type string, got %T instead", value) + } + sv.ReasonCode = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidPasswordException(v **types.InvalidPasswordException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidPasswordException + if *v == nil { + sv = &types.InvalidPasswordException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidSmsRoleAccessPolicyException(v **types.InvalidSmsRoleAccessPolicyException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidSmsRoleAccessPolicyException + if *v == nil { + sv = &types.InvalidSmsRoleAccessPolicyException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidSmsRoleTrustRelationshipException(v **types.InvalidSmsRoleTrustRelationshipException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidSmsRoleTrustRelationshipException + if *v == nil { + sv = &types.InvalidSmsRoleTrustRelationshipException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentInvalidUserPoolConfigurationException(v **types.InvalidUserPoolConfigurationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InvalidUserPoolConfigurationException + if *v == nil { + sv = &types.InvalidUserPoolConfigurationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLambdaConfigType(v **types.LambdaConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LambdaConfigType + if *v == nil { + sv = &types.LambdaConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CreateAuthChallenge": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.CreateAuthChallenge = ptr.String(jtv) + } + + case "CustomEmailSender": + if err := awsAwsjson11_deserializeDocumentCustomEmailLambdaVersionConfigType(&sv.CustomEmailSender, value); err != nil { + return err + } + + case "CustomMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.CustomMessage = ptr.String(jtv) + } + + case "CustomSMSSender": + if err := awsAwsjson11_deserializeDocumentCustomSMSLambdaVersionConfigType(&sv.CustomSMSSender, value); err != nil { + return err + } + + case "DefineAuthChallenge": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.DefineAuthChallenge = ptr.String(jtv) + } + + case "KMSKeyID": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.KMSKeyID = ptr.String(jtv) + } + + case "PostAuthentication": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.PostAuthentication = ptr.String(jtv) + } + + case "PostConfirmation": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.PostConfirmation = ptr.String(jtv) + } + + case "PreAuthentication": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.PreAuthentication = ptr.String(jtv) + } + + case "PreSignUp": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.PreSignUp = ptr.String(jtv) + } + + case "PreTokenGeneration": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.PreTokenGeneration = ptr.String(jtv) + } + + case "PreTokenGenerationConfig": + if err := awsAwsjson11_deserializeDocumentPreTokenGenerationVersionConfigType(&sv.PreTokenGenerationConfig, value); err != nil { + return err + } + + case "UserMigration": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.UserMigration = ptr.String(jtv) + } + + case "VerifyAuthChallengeResponse": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.VerifyAuthChallengeResponse = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLimitExceededException(v **types.LimitExceededException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LimitExceededException + if *v == nil { + sv = &types.LimitExceededException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentListOfStringTypes(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentLogConfigurationListType(v *[]types.LogConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.LogConfigurationType + if *v == nil { + cv = []types.LogConfigurationType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.LogConfigurationType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentLogConfigurationType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentLogConfigurationType(v **types.LogConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LogConfigurationType + if *v == nil { + sv = &types.LogConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CloudWatchLogsConfiguration": + if err := awsAwsjson11_deserializeDocumentCloudWatchLogsConfigurationType(&sv.CloudWatchLogsConfiguration, value); err != nil { + return err + } + + case "EventSource": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EventSourceName to be of type string, got %T instead", value) + } + sv.EventSource = types.EventSourceName(jtv) + } + + case "FirehoseConfiguration": + if err := awsAwsjson11_deserializeDocumentFirehoseConfigurationType(&sv.FirehoseConfiguration, value); err != nil { + return err + } + + case "LogLevel": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected LogLevel to be of type string, got %T instead", value) + } + sv.LogLevel = types.LogLevel(jtv) + } + + case "S3Configuration": + if err := awsAwsjson11_deserializeDocumentS3ConfigurationType(&sv.S3Configuration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLogDeliveryConfigurationType(v **types.LogDeliveryConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.LogDeliveryConfigurationType + if *v == nil { + sv = &types.LogDeliveryConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LogConfigurations": + if err := awsAwsjson11_deserializeDocumentLogConfigurationListType(&sv.LogConfigurations, value); err != nil { + return err + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentLogoutURLsListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RedirectUrlType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentManagedLoginBrandingExistsException(v **types.ManagedLoginBrandingExistsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ManagedLoginBrandingExistsException + if *v == nil { + sv = &types.ManagedLoginBrandingExistsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentManagedLoginBrandingType(v **types.ManagedLoginBrandingType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ManagedLoginBrandingType + if *v == nil { + sv = &types.ManagedLoginBrandingType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Assets": + if err := awsAwsjson11_deserializeDocumentAssetListType(&sv.Assets, value); err != nil { + return err + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "ManagedLoginBrandingId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ManagedLoginBrandingIdType to be of type string, got %T instead", value) + } + sv.ManagedLoginBrandingId = ptr.String(jtv) + } + + case "Settings": + if err := awsAwsjson11_deserializeDocumentDocument(&sv.Settings, value); err != nil { + return err + } + + case "UseCognitoProvidedValues": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.UseCognitoProvidedValues = jtv + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentMessageTemplateType(v **types.MessageTemplateType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.MessageTemplateType + if *v == nil { + sv = &types.MessageTemplateType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "EmailMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailInviteMessageType to be of type string, got %T instead", value) + } + sv.EmailMessage = ptr.String(jtv) + } + + case "EmailSubject": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationSubjectType to be of type string, got %T instead", value) + } + sv.EmailSubject = ptr.String(jtv) + } + + case "SMSMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SmsInviteMessageType to be of type string, got %T instead", value) + } + sv.SMSMessage = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentMFAMethodNotFoundException(v **types.MFAMethodNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.MFAMethodNotFoundException + if *v == nil { + sv = &types.MFAMethodNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentMFAOptionListType(v *[]types.MFAOptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.MFAOptionType + if *v == nil { + cv = []types.MFAOptionType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.MFAOptionType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentMFAOptionType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentMFAOptionType(v **types.MFAOptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.MFAOptionType + if *v == nil { + sv = &types.MFAOptionType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AttributeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AttributeNameType to be of type string, got %T instead", value) + } + sv.AttributeName = ptr.String(jtv) + } + + case "DeliveryMedium": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DeliveryMediumType to be of type string, got %T instead", value) + } + sv.DeliveryMedium = types.DeliveryMediumType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentNewDeviceMetadataType(v **types.NewDeviceMetadataType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.NewDeviceMetadataType + if *v == nil { + sv = &types.NewDeviceMetadataType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DeviceGroupKey": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.DeviceGroupKey = ptr.String(jtv) + } + + case "DeviceKey": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DeviceKeyType to be of type string, got %T instead", value) + } + sv.DeviceKey = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentNotAuthorizedException(v **types.NotAuthorizedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.NotAuthorizedException + if *v == nil { + sv = &types.NotAuthorizedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentNotifyConfigurationType(v **types.NotifyConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.NotifyConfigurationType + if *v == nil { + sv = &types.NotifyConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "BlockEmail": + if err := awsAwsjson11_deserializeDocumentNotifyEmailType(&sv.BlockEmail, value); err != nil { + return err + } + + case "From": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.From = ptr.String(jtv) + } + + case "MfaEmail": + if err := awsAwsjson11_deserializeDocumentNotifyEmailType(&sv.MfaEmail, value); err != nil { + return err + } + + case "NoActionEmail": + if err := awsAwsjson11_deserializeDocumentNotifyEmailType(&sv.NoActionEmail, value); err != nil { + return err + } + + case "ReplyTo": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.ReplyTo = ptr.String(jtv) + } + + case "SourceArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.SourceArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentNotifyEmailType(v **types.NotifyEmailType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.NotifyEmailType + if *v == nil { + sv = &types.NotifyEmailType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "HtmlBody": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailNotificationBodyType to be of type string, got %T instead", value) + } + sv.HtmlBody = ptr.String(jtv) + } + + case "Subject": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailNotificationSubjectType to be of type string, got %T instead", value) + } + sv.Subject = ptr.String(jtv) + } + + case "TextBody": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailNotificationBodyType to be of type string, got %T instead", value) + } + sv.TextBody = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentNumberAttributeConstraintsType(v **types.NumberAttributeConstraintsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.NumberAttributeConstraintsType + if *v == nil { + sv = &types.NumberAttributeConstraintsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "MaxValue": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.MaxValue = ptr.String(jtv) + } + + case "MinValue": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.MinValue = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentOAuthFlowsType(v *[]types.OAuthFlowType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.OAuthFlowType + if *v == nil { + cv = []types.OAuthFlowType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.OAuthFlowType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected OAuthFlowType to be of type string, got %T instead", value) + } + col = types.OAuthFlowType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentPasswordHistoryPolicyViolationException(v **types.PasswordHistoryPolicyViolationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.PasswordHistoryPolicyViolationException + if *v == nil { + sv = &types.PasswordHistoryPolicyViolationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPasswordPolicyType(v **types.PasswordPolicyType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.PasswordPolicyType + if *v == nil { + sv = &types.PasswordPolicyType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "MinimumLength": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected PasswordPolicyMinLengthType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.MinimumLength = ptr.Int32(int32(i64)) + } + + case "PasswordHistorySize": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected PasswordHistorySizeType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.PasswordHistorySize = ptr.Int32(int32(i64)) + } + + case "RequireLowercase": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.RequireLowercase = jtv + } + + case "RequireNumbers": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.RequireNumbers = jtv + } + + case "RequireSymbols": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.RequireSymbols = jtv + } + + case "RequireUppercase": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.RequireUppercase = jtv + } + + case "TemporaryPasswordValidityDays": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected TemporaryPasswordValidityDaysType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.TemporaryPasswordValidityDays = int32(i64) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPasswordResetRequiredException(v **types.PasswordResetRequiredException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.PasswordResetRequiredException + if *v == nil { + sv = &types.PasswordResetRequiredException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPreconditionNotMetException(v **types.PreconditionNotMetException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.PreconditionNotMetException + if *v == nil { + sv = &types.PreconditionNotMetException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentPreTokenGenerationVersionConfigType(v **types.PreTokenGenerationVersionConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.PreTokenGenerationVersionConfigType + if *v == nil { + sv = &types.PreTokenGenerationVersionConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LambdaArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.LambdaArn = ptr.String(jtv) + } + + case "LambdaVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PreTokenGenerationLambdaVersionType to be of type string, got %T instead", value) + } + sv.LambdaVersion = types.PreTokenGenerationLambdaVersionType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentProviderDescription(v **types.ProviderDescription, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ProviderDescription + if *v == nil { + sv = &types.ProviderDescription{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "ProviderName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ProviderNameType to be of type string, got %T instead", value) + } + sv.ProviderName = ptr.String(jtv) + } + + case "ProviderType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected IdentityProviderTypeType to be of type string, got %T instead", value) + } + sv.ProviderType = types.IdentityProviderTypeType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentProviderDetailsType(v *map[string]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var mv map[string]string + if *v == nil { + mv = map[string]string{} + } else { + mv = *v + } + + for key, value := range shape { + var parsedVal string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + parsedVal = jtv + } + mv[key] = parsedVal + + } + *v = mv + return nil +} + +func awsAwsjson11_deserializeDocumentProvidersListType(v *[]types.ProviderDescription, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ProviderDescription + if *v == nil { + cv = []types.ProviderDescription{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ProviderDescription + destAddr := &col + if err := awsAwsjson11_deserializeDocumentProviderDescription(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentRecoveryMechanismsType(v *[]types.RecoveryOptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.RecoveryOptionType + if *v == nil { + cv = []types.RecoveryOptionType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.RecoveryOptionType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentRecoveryOptionType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentRecoveryOptionType(v **types.RecoveryOptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.RecoveryOptionType + if *v == nil { + sv = &types.RecoveryOptionType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RecoveryOptionNameType to be of type string, got %T instead", value) + } + sv.Name = types.RecoveryOptionNameType(jtv) + } + + case "Priority": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected PriorityType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.Priority = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRefreshTokenReuseException(v **types.RefreshTokenReuseException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.RefreshTokenReuseException + if *v == nil { + sv = &types.RefreshTokenReuseException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRefreshTokenRotationType(v **types.RefreshTokenRotationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.RefreshTokenRotationType + if *v == nil { + sv = &types.RefreshTokenRotationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Feature": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected FeatureType to be of type string, got %T instead", value) + } + sv.Feature = types.FeatureType(jtv) + } + + case "RetryGracePeriodSeconds": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected RetryGracePeriodSecondsType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.RetryGracePeriodSeconds = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentResourceNotFoundException(v **types.ResourceNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ResourceNotFoundException + if *v == nil { + sv = &types.ResourceNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentResourceServerScopeListType(v *[]types.ResourceServerScopeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ResourceServerScopeType + if *v == nil { + cv = []types.ResourceServerScopeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ResourceServerScopeType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentResourceServerScopeType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentResourceServerScopeType(v **types.ResourceServerScopeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ResourceServerScopeType + if *v == nil { + sv = &types.ResourceServerScopeType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ScopeDescription": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ResourceServerScopeDescriptionType to be of type string, got %T instead", value) + } + sv.ScopeDescription = ptr.String(jtv) + } + + case "ScopeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ResourceServerScopeNameType to be of type string, got %T instead", value) + } + sv.ScopeName = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentResourceServersListType(v *[]types.ResourceServerType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.ResourceServerType + if *v == nil { + cv = []types.ResourceServerType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.ResourceServerType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentResourceServerType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentResourceServerType(v **types.ResourceServerType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ResourceServerType + if *v == nil { + sv = &types.ResourceServerType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Identifier": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ResourceServerIdentifierType to be of type string, got %T instead", value) + } + sv.Identifier = ptr.String(jtv) + } + + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ResourceServerNameType to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "Scopes": + if err := awsAwsjson11_deserializeDocumentResourceServerScopeListType(&sv.Scopes, value); err != nil { + return err + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRiskConfigurationType(v **types.RiskConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.RiskConfigurationType + if *v == nil { + sv = &types.RiskConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AccountTakeoverRiskConfiguration": + if err := awsAwsjson11_deserializeDocumentAccountTakeoverRiskConfigurationType(&sv.AccountTakeoverRiskConfiguration, value); err != nil { + return err + } + + case "ClientId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientIdType to be of type string, got %T instead", value) + } + sv.ClientId = ptr.String(jtv) + } + + case "CompromisedCredentialsRiskConfiguration": + if err := awsAwsjson11_deserializeDocumentCompromisedCredentialsRiskConfigurationType(&sv.CompromisedCredentialsRiskConfiguration, value); err != nil { + return err + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "RiskExceptionConfiguration": + if err := awsAwsjson11_deserializeDocumentRiskExceptionConfigurationType(&sv.RiskExceptionConfiguration, value); err != nil { + return err + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentRiskExceptionConfigurationType(v **types.RiskExceptionConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.RiskExceptionConfigurationType + if *v == nil { + sv = &types.RiskExceptionConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "BlockedIPRangeList": + if err := awsAwsjson11_deserializeDocumentBlockedIPRangeListType(&sv.BlockedIPRangeList, value); err != nil { + return err + } + + case "SkippedIPRangeList": + if err := awsAwsjson11_deserializeDocumentSkippedIPRangeListType(&sv.SkippedIPRangeList, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentS3ConfigurationType(v **types.S3ConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.S3ConfigurationType + if *v == nil { + sv = &types.S3ConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "BucketArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected S3ArnType to be of type string, got %T instead", value) + } + sv.BucketArn = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSchemaAttributesListType(v *[]types.SchemaAttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.SchemaAttributeType + if *v == nil { + cv = []types.SchemaAttributeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.SchemaAttributeType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentSchemaAttributeType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentSchemaAttributeType(v **types.SchemaAttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SchemaAttributeType + if *v == nil { + sv = &types.SchemaAttributeType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AttributeDataType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AttributeDataType to be of type string, got %T instead", value) + } + sv.AttributeDataType = types.AttributeDataType(jtv) + } + + case "DeveloperOnlyAttribute": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.DeveloperOnlyAttribute = ptr.Bool(jtv) + } + + case "Mutable": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.Mutable = ptr.Bool(jtv) + } + + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CustomAttributeNameType to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "NumberAttributeConstraints": + if err := awsAwsjson11_deserializeDocumentNumberAttributeConstraintsType(&sv.NumberAttributeConstraints, value); err != nil { + return err + } + + case "Required": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.Required = ptr.Bool(jtv) + } + + case "StringAttributeConstraints": + if err := awsAwsjson11_deserializeDocumentStringAttributeConstraintsType(&sv.StringAttributeConstraints, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentScopeDoesNotExistException(v **types.ScopeDoesNotExistException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ScopeDoesNotExistException + if *v == nil { + sv = &types.ScopeDoesNotExistException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentScopeListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ScopeType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentSignInPolicyType(v **types.SignInPolicyType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SignInPolicyType + if *v == nil { + sv = &types.SignInPolicyType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AllowedFirstAuthFactors": + if err := awsAwsjson11_deserializeDocumentAllowedFirstAuthFactorsListType(&sv.AllowedFirstAuthFactors, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSkippedIPRangeListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentSmsConfigurationType(v **types.SmsConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SmsConfigurationType + if *v == nil { + sv = &types.SmsConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ExternalId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.ExternalId = ptr.String(jtv) + } + + case "SnsCallerArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.SnsCallerArn = ptr.String(jtv) + } + + case "SnsRegion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RegionCodeType to be of type string, got %T instead", value) + } + sv.SnsRegion = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSmsMfaConfigType(v **types.SmsMfaConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SmsMfaConfigType + if *v == nil { + sv = &types.SmsMfaConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "SmsAuthenticationMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SmsVerificationMessageType to be of type string, got %T instead", value) + } + sv.SmsAuthenticationMessage = ptr.String(jtv) + } + + case "SmsConfiguration": + if err := awsAwsjson11_deserializeDocumentSmsConfigurationType(&sv.SmsConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSoftwareTokenMfaConfigType(v **types.SoftwareTokenMfaConfigType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SoftwareTokenMfaConfigType + if *v == nil { + sv = &types.SoftwareTokenMfaConfigType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Enabled": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.Enabled = jtv + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSoftwareTokenMFANotFoundException(v **types.SoftwareTokenMFANotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.SoftwareTokenMFANotFoundException + if *v == nil { + sv = &types.SoftwareTokenMFANotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentStringAttributeConstraintsType(v **types.StringAttributeConstraintsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.StringAttributeConstraintsType + if *v == nil { + sv = &types.StringAttributeConstraintsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "MaxLength": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.MaxLength = ptr.String(jtv) + } + + case "MinLength": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.MinLength = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentSupportedIdentityProvidersListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ProviderNameType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentTierChangeNotAllowedException(v **types.TierChangeNotAllowedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TierChangeNotAllowedException + if *v == nil { + sv = &types.TierChangeNotAllowedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentTokenValidityUnitsType(v **types.TokenValidityUnitsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TokenValidityUnitsType + if *v == nil { + sv = &types.TokenValidityUnitsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AccessToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TimeUnitsType to be of type string, got %T instead", value) + } + sv.AccessToken = types.TimeUnitsType(jtv) + } + + case "IdToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TimeUnitsType to be of type string, got %T instead", value) + } + sv.IdToken = types.TimeUnitsType(jtv) + } + + case "RefreshToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TimeUnitsType to be of type string, got %T instead", value) + } + sv.RefreshToken = types.TimeUnitsType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentTooManyFailedAttemptsException(v **types.TooManyFailedAttemptsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TooManyFailedAttemptsException + if *v == nil { + sv = &types.TooManyFailedAttemptsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentTooManyRequestsException(v **types.TooManyRequestsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TooManyRequestsException + if *v == nil { + sv = &types.TooManyRequestsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUICustomizationType(v **types.UICustomizationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UICustomizationType + if *v == nil { + sv = &types.UICustomizationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ClientId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientIdType to be of type string, got %T instead", value) + } + sv.ClientId = ptr.String(jtv) + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "CSS": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CSSType to be of type string, got %T instead", value) + } + sv.CSS = ptr.String(jtv) + } + + case "CSSVersion": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CSSVersionType to be of type string, got %T instead", value) + } + sv.CSSVersion = ptr.String(jtv) + } + + case "ImageUrl": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ImageUrlType to be of type string, got %T instead", value) + } + sv.ImageUrl = ptr.String(jtv) + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnauthorizedException(v **types.UnauthorizedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnauthorizedException + if *v == nil { + sv = &types.UnauthorizedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnexpectedLambdaException(v **types.UnexpectedLambdaException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnexpectedLambdaException + if *v == nil { + sv = &types.UnexpectedLambdaException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnsupportedIdentityProviderException(v **types.UnsupportedIdentityProviderException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnsupportedIdentityProviderException + if *v == nil { + sv = &types.UnsupportedIdentityProviderException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnsupportedOperationException(v **types.UnsupportedOperationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnsupportedOperationException + if *v == nil { + sv = &types.UnsupportedOperationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnsupportedTokenTypeException(v **types.UnsupportedTokenTypeException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnsupportedTokenTypeException + if *v == nil { + sv = &types.UnsupportedTokenTypeException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUnsupportedUserStateException(v **types.UnsupportedUserStateException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UnsupportedUserStateException + if *v == nil { + sv = &types.UnsupportedUserStateException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserAttributeUpdateSettingsType(v **types.UserAttributeUpdateSettingsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserAttributeUpdateSettingsType + if *v == nil { + sv = &types.UserAttributeUpdateSettingsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AttributesRequireVerificationBeforeUpdate": + if err := awsAwsjson11_deserializeDocumentAttributesRequireVerificationBeforeUpdateType(&sv.AttributesRequireVerificationBeforeUpdate, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserImportInProgressException(v **types.UserImportInProgressException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserImportInProgressException + if *v == nil { + sv = &types.UserImportInProgressException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserImportJobsListType(v *[]types.UserImportJobType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.UserImportJobType + if *v == nil { + cv = []types.UserImportJobType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.UserImportJobType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentUserImportJobType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUserImportJobType(v **types.UserImportJobType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserImportJobType + if *v == nil { + sv = &types.UserImportJobType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CloudWatchLogsRoleArn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.CloudWatchLogsRoleArn = ptr.String(jtv) + } + + case "CompletionDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CompletionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "CompletionMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected CompletionMessageType to be of type string, got %T instead", value) + } + sv.CompletionMessage = ptr.String(jtv) + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "FailedUsers": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected LongType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.FailedUsers = i64 + } + + case "ImportedUsers": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected LongType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ImportedUsers = i64 + } + + case "JobId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserImportJobIdType to be of type string, got %T instead", value) + } + sv.JobId = ptr.String(jtv) + } + + case "JobName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserImportJobNameType to be of type string, got %T instead", value) + } + sv.JobName = ptr.String(jtv) + } + + case "PreSignedUrl": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PreSignedUrlType to be of type string, got %T instead", value) + } + sv.PreSignedUrl = ptr.String(jtv) + } + + case "SkippedUsers": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected LongType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.SkippedUsers = i64 + } + + case "StartDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.StartDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserImportJobStatusType to be of type string, got %T instead", value) + } + sv.Status = types.UserImportJobStatusType(jtv) + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserLambdaValidationException(v **types.UserLambdaValidationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserLambdaValidationException + if *v == nil { + sv = &types.UserLambdaValidationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserMFASettingListType(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUsernameAttributesListType(v *[]types.UsernameAttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.UsernameAttributeType + if *v == nil { + cv = []types.UsernameAttributeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.UsernameAttributeType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UsernameAttributeType to be of type string, got %T instead", value) + } + col = types.UsernameAttributeType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUsernameConfigurationType(v **types.UsernameConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UsernameConfigurationType + if *v == nil { + sv = &types.UsernameConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CaseSensitive": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected WrappedBooleanType to be of type *bool, got %T instead", value) + } + sv.CaseSensitive = ptr.Bool(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUsernameExistsException(v **types.UsernameExistsException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UsernameExistsException + if *v == nil { + sv = &types.UsernameExistsException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserNotConfirmedException(v **types.UserNotConfirmedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserNotConfirmedException + if *v == nil { + sv = &types.UserNotConfirmedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserNotFoundException(v **types.UserNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserNotFoundException + if *v == nil { + sv = &types.UserNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolAddOnNotEnabledException(v **types.UserPoolAddOnNotEnabledException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolAddOnNotEnabledException + if *v == nil { + sv = &types.UserPoolAddOnNotEnabledException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolAddOnsType(v **types.UserPoolAddOnsType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolAddOnsType + if *v == nil { + sv = &types.UserPoolAddOnsType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AdvancedSecurityAdditionalFlows": + if err := awsAwsjson11_deserializeDocumentAdvancedSecurityAdditionalFlowsType(&sv.AdvancedSecurityAdditionalFlows, value); err != nil { + return err + } + + case "AdvancedSecurityMode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected AdvancedSecurityModeType to be of type string, got %T instead", value) + } + sv.AdvancedSecurityMode = types.AdvancedSecurityModeType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolClientDescription(v **types.UserPoolClientDescription, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolClientDescription + if *v == nil { + sv = &types.UserPoolClientDescription{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ClientId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientIdType to be of type string, got %T instead", value) + } + sv.ClientId = ptr.String(jtv) + } + + case "ClientName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientNameType to be of type string, got %T instead", value) + } + sv.ClientName = ptr.String(jtv) + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolClientListType(v *[]types.UserPoolClientDescription, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.UserPoolClientDescription + if *v == nil { + cv = []types.UserPoolClientDescription{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.UserPoolClientDescription + destAddr := &col + if err := awsAwsjson11_deserializeDocumentUserPoolClientDescription(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolClientType(v **types.UserPoolClientType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolClientType + if *v == nil { + sv = &types.UserPoolClientType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AccessTokenValidity": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected AccessTokenValidityType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.AccessTokenValidity = ptr.Int32(int32(i64)) + } + + case "AllowedOAuthFlows": + if err := awsAwsjson11_deserializeDocumentOAuthFlowsType(&sv.AllowedOAuthFlows, value); err != nil { + return err + } + + case "AllowedOAuthFlowsUserPoolClient": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.AllowedOAuthFlowsUserPoolClient = ptr.Bool(jtv) + } + + case "AllowedOAuthScopes": + if err := awsAwsjson11_deserializeDocumentScopeListType(&sv.AllowedOAuthScopes, value); err != nil { + return err + } + + case "AnalyticsConfiguration": + if err := awsAwsjson11_deserializeDocumentAnalyticsConfigurationType(&sv.AnalyticsConfiguration, value); err != nil { + return err + } + + case "AuthSessionValidity": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected AuthSessionValidityType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.AuthSessionValidity = ptr.Int32(int32(i64)) + } + + case "CallbackURLs": + if err := awsAwsjson11_deserializeDocumentCallbackURLsListType(&sv.CallbackURLs, value); err != nil { + return err + } + + case "ClientId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientIdType to be of type string, got %T instead", value) + } + sv.ClientId = ptr.String(jtv) + } + + case "ClientName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientNameType to be of type string, got %T instead", value) + } + sv.ClientName = ptr.String(jtv) + } + + case "ClientSecret": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ClientSecretType to be of type string, got %T instead", value) + } + sv.ClientSecret = ptr.String(jtv) + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "DefaultRedirectURI": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RedirectUrlType to be of type string, got %T instead", value) + } + sv.DefaultRedirectURI = ptr.String(jtv) + } + + case "EnablePropagateAdditionalUserContextData": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected WrappedBooleanType to be of type *bool, got %T instead", value) + } + sv.EnablePropagateAdditionalUserContextData = ptr.Bool(jtv) + } + + case "EnableTokenRevocation": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected WrappedBooleanType to be of type *bool, got %T instead", value) + } + sv.EnableTokenRevocation = ptr.Bool(jtv) + } + + case "ExplicitAuthFlows": + if err := awsAwsjson11_deserializeDocumentExplicitAuthFlowsListType(&sv.ExplicitAuthFlows, value); err != nil { + return err + } + + case "IdTokenValidity": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected IdTokenValidityType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.IdTokenValidity = ptr.Int32(int32(i64)) + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "LogoutURLs": + if err := awsAwsjson11_deserializeDocumentLogoutURLsListType(&sv.LogoutURLs, value); err != nil { + return err + } + + case "PreventUserExistenceErrors": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PreventUserExistenceErrorTypes to be of type string, got %T instead", value) + } + sv.PreventUserExistenceErrors = types.PreventUserExistenceErrorTypes(jtv) + } + + case "ReadAttributes": + if err := awsAwsjson11_deserializeDocumentClientPermissionListType(&sv.ReadAttributes, value); err != nil { + return err + } + + case "RefreshTokenRotation": + if err := awsAwsjson11_deserializeDocumentRefreshTokenRotationType(&sv.RefreshTokenRotation, value); err != nil { + return err + } + + case "RefreshTokenValidity": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected RefreshTokenValidityType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.RefreshTokenValidity = int32(i64) + } + + case "SupportedIdentityProviders": + if err := awsAwsjson11_deserializeDocumentSupportedIdentityProvidersListType(&sv.SupportedIdentityProviders, value); err != nil { + return err + } + + case "TokenValidityUnits": + if err := awsAwsjson11_deserializeDocumentTokenValidityUnitsType(&sv.TokenValidityUnits, value); err != nil { + return err + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + case "WriteAttributes": + if err := awsAwsjson11_deserializeDocumentClientPermissionListType(&sv.WriteAttributes, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolDescriptionType(v **types.UserPoolDescriptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolDescriptionType + if *v == nil { + sv = &types.UserPoolDescriptionType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "Id": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.Id = ptr.String(jtv) + } + + case "LambdaConfig": + if err := awsAwsjson11_deserializeDocumentLambdaConfigType(&sv.LambdaConfig, value); err != nil { + return err + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolNameType to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusType to be of type string, got %T instead", value) + } + sv.Status = types.StatusType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolListType(v *[]types.UserPoolDescriptionType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.UserPoolDescriptionType + if *v == nil { + cv = []types.UserPoolDescriptionType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.UserPoolDescriptionType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentUserPoolDescriptionType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolPolicyType(v **types.UserPoolPolicyType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolPolicyType + if *v == nil { + sv = &types.UserPoolPolicyType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "PasswordPolicy": + if err := awsAwsjson11_deserializeDocumentPasswordPolicyType(&sv.PasswordPolicy, value); err != nil { + return err + } + + case "SignInPolicy": + if err := awsAwsjson11_deserializeDocumentSignInPolicyType(&sv.SignInPolicy, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolTaggingException(v **types.UserPoolTaggingException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolTaggingException + if *v == nil { + sv = &types.UserPoolTaggingException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolTagsType(v *map[string]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var mv map[string]string + if *v == nil { + mv = map[string]string{} + } else { + mv = *v + } + + for key, value := range shape { + var parsedVal string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TagValueType to be of type string, got %T instead", value) + } + parsedVal = jtv + } + mv[key] = parsedVal + + } + *v = mv + return nil +} + +func awsAwsjson11_deserializeDocumentUserPoolType(v **types.UserPoolType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserPoolType + if *v == nil { + sv = &types.UserPoolType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AccountRecoverySetting": + if err := awsAwsjson11_deserializeDocumentAccountRecoverySettingType(&sv.AccountRecoverySetting, value); err != nil { + return err + } + + case "AdminCreateUserConfig": + if err := awsAwsjson11_deserializeDocumentAdminCreateUserConfigType(&sv.AdminCreateUserConfig, value); err != nil { + return err + } + + case "AliasAttributes": + if err := awsAwsjson11_deserializeDocumentAliasAttributesListType(&sv.AliasAttributes, value); err != nil { + return err + } + + case "Arn": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ArnType to be of type string, got %T instead", value) + } + sv.Arn = ptr.String(jtv) + } + + case "AutoVerifiedAttributes": + if err := awsAwsjson11_deserializeDocumentVerifiedAttributesListType(&sv.AutoVerifiedAttributes, value); err != nil { + return err + } + + case "CreationDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "CustomDomain": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainType to be of type string, got %T instead", value) + } + sv.CustomDomain = ptr.String(jtv) + } + + case "DeletionProtection": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DeletionProtectionType to be of type string, got %T instead", value) + } + sv.DeletionProtection = types.DeletionProtectionType(jtv) + } + + case "DeviceConfiguration": + if err := awsAwsjson11_deserializeDocumentDeviceConfigurationType(&sv.DeviceConfiguration, value); err != nil { + return err + } + + case "Domain": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainType to be of type string, got %T instead", value) + } + sv.Domain = ptr.String(jtv) + } + + case "EmailConfiguration": + if err := awsAwsjson11_deserializeDocumentEmailConfigurationType(&sv.EmailConfiguration, value); err != nil { + return err + } + + case "EmailConfigurationFailure": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.EmailConfigurationFailure = ptr.String(jtv) + } + + case "EmailVerificationMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationMessageType to be of type string, got %T instead", value) + } + sv.EmailVerificationMessage = ptr.String(jtv) + } + + case "EmailVerificationSubject": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationSubjectType to be of type string, got %T instead", value) + } + sv.EmailVerificationSubject = ptr.String(jtv) + } + + case "EstimatedNumberOfUsers": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected IntegerType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.EstimatedNumberOfUsers = int32(i64) + } + + case "Id": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.Id = ptr.String(jtv) + } + + case "LambdaConfig": + if err := awsAwsjson11_deserializeDocumentLambdaConfigType(&sv.LambdaConfig, value); err != nil { + return err + } + + case "LastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "MfaConfiguration": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolMfaType to be of type string, got %T instead", value) + } + sv.MfaConfiguration = types.UserPoolMfaType(jtv) + } + + case "Name": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolNameType to be of type string, got %T instead", value) + } + sv.Name = ptr.String(jtv) + } + + case "Policies": + if err := awsAwsjson11_deserializeDocumentUserPoolPolicyType(&sv.Policies, value); err != nil { + return err + } + + case "SchemaAttributes": + if err := awsAwsjson11_deserializeDocumentSchemaAttributesListType(&sv.SchemaAttributes, value); err != nil { + return err + } + + case "SmsAuthenticationMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SmsVerificationMessageType to be of type string, got %T instead", value) + } + sv.SmsAuthenticationMessage = ptr.String(jtv) + } + + case "SmsConfiguration": + if err := awsAwsjson11_deserializeDocumentSmsConfigurationType(&sv.SmsConfiguration, value); err != nil { + return err + } + + case "SmsConfigurationFailure": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.SmsConfigurationFailure = ptr.String(jtv) + } + + case "SmsVerificationMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SmsVerificationMessageType to be of type string, got %T instead", value) + } + sv.SmsVerificationMessage = ptr.String(jtv) + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StatusType to be of type string, got %T instead", value) + } + sv.Status = types.StatusType(jtv) + } + + case "UserAttributeUpdateSettings": + if err := awsAwsjson11_deserializeDocumentUserAttributeUpdateSettingsType(&sv.UserAttributeUpdateSettings, value); err != nil { + return err + } + + case "UsernameAttributes": + if err := awsAwsjson11_deserializeDocumentUsernameAttributesListType(&sv.UsernameAttributes, value); err != nil { + return err + } + + case "UsernameConfiguration": + if err := awsAwsjson11_deserializeDocumentUsernameConfigurationType(&sv.UsernameConfiguration, value); err != nil { + return err + } + + case "UserPoolAddOns": + if err := awsAwsjson11_deserializeDocumentUserPoolAddOnsType(&sv.UserPoolAddOns, value); err != nil { + return err + } + + case "UserPoolTags": + if err := awsAwsjson11_deserializeDocumentUserPoolTagsType(&sv.UserPoolTags, value); err != nil { + return err + } + + case "UserPoolTier": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolTierType to be of type string, got %T instead", value) + } + sv.UserPoolTier = types.UserPoolTierType(jtv) + } + + case "VerificationMessageTemplate": + if err := awsAwsjson11_deserializeDocumentVerificationMessageTemplateType(&sv.VerificationMessageTemplate, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentUsersListType(v *[]types.UserType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.UserType + if *v == nil { + cv = []types.UserType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.UserType + destAddr := &col + if err := awsAwsjson11_deserializeDocumentUserType(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentUserType(v **types.UserType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.UserType + if *v == nil { + sv = &types.UserType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Attributes": + if err := awsAwsjson11_deserializeDocumentAttributeListType(&sv.Attributes, value); err != nil { + return err + } + + case "Enabled": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.Enabled = jtv + } + + case "MFAOptions": + if err := awsAwsjson11_deserializeDocumentMFAOptionListType(&sv.MFAOptions, value); err != nil { + return err + } + + case "UserCreateDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UserCreateDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "UserLastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UserLastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "Username": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UsernameType to be of type string, got %T instead", value) + } + sv.Username = ptr.String(jtv) + } + + case "UserStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserStatusType to be of type string, got %T instead", value) + } + sv.UserStatus = types.UserStatusType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentVerificationMessageTemplateType(v **types.VerificationMessageTemplateType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.VerificationMessageTemplateType + if *v == nil { + sv = &types.VerificationMessageTemplateType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DefaultEmailOption": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DefaultEmailOptionType to be of type string, got %T instead", value) + } + sv.DefaultEmailOption = types.DefaultEmailOptionType(jtv) + } + + case "EmailMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationMessageType to be of type string, got %T instead", value) + } + sv.EmailMessage = ptr.String(jtv) + } + + case "EmailMessageByLink": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationMessageByLinkType to be of type string, got %T instead", value) + } + sv.EmailMessageByLink = ptr.String(jtv) + } + + case "EmailSubject": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationSubjectType to be of type string, got %T instead", value) + } + sv.EmailSubject = ptr.String(jtv) + } + + case "EmailSubjectByLink": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected EmailVerificationSubjectByLinkType to be of type string, got %T instead", value) + } + sv.EmailSubjectByLink = ptr.String(jtv) + } + + case "SmsMessage": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SmsVerificationMessageType to be of type string, got %T instead", value) + } + sv.SmsMessage = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentVerifiedAttributesListType(v *[]types.VerifiedAttributeType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.VerifiedAttributeType + if *v == nil { + cv = []types.VerifiedAttributeType{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.VerifiedAttributeType + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected VerifiedAttributeType to be of type string, got %T instead", value) + } + col = types.VerifiedAttributeType(jtv) + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnAuthenticatorTransportsList(v *[]string, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []string + if *v == nil { + cv = []string{} + } else { + cv = *v + } + + for _, value := range shape { + var col string + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected WebAuthnAuthenticatorTransportType to be of type string, got %T instead", value) + } + col = jtv + } + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnChallengeNotFoundException(v **types.WebAuthnChallengeNotFoundException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnChallengeNotFoundException + if *v == nil { + sv = &types.WebAuthnChallengeNotFoundException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnClientMismatchException(v **types.WebAuthnClientMismatchException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnClientMismatchException + if *v == nil { + sv = &types.WebAuthnClientMismatchException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnConfigurationMissingException(v **types.WebAuthnConfigurationMissingException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnConfigurationMissingException + if *v == nil { + sv = &types.WebAuthnConfigurationMissingException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnConfigurationType(v **types.WebAuthnConfigurationType, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnConfigurationType + if *v == nil { + sv = &types.WebAuthnConfigurationType{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "RelyingPartyId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RelyingPartyIdType to be of type string, got %T instead", value) + } + sv.RelyingPartyId = ptr.String(jtv) + } + + case "UserVerification": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserVerificationType to be of type string, got %T instead", value) + } + sv.UserVerification = types.UserVerificationType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnCredentialDescription(v **types.WebAuthnCredentialDescription, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnCredentialDescription + if *v == nil { + sv = &types.WebAuthnCredentialDescription{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthenticatorAttachment": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected WebAuthnAuthenticatorAttachmentType to be of type string, got %T instead", value) + } + sv.AuthenticatorAttachment = ptr.String(jtv) + } + + case "AuthenticatorTransports": + if err := awsAwsjson11_deserializeDocumentWebAuthnAuthenticatorTransportsList(&sv.AuthenticatorTransports, value); err != nil { + return err + } + + case "CreatedAt": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.CreatedAt = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "CredentialId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.CredentialId = ptr.String(jtv) + } + + case "FriendlyCredentialName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.FriendlyCredentialName = ptr.String(jtv) + } + + case "RelyingPartyId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.RelyingPartyId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnCredentialDescriptionListType(v *[]types.WebAuthnCredentialDescription, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var cv []types.WebAuthnCredentialDescription + if *v == nil { + cv = []types.WebAuthnCredentialDescription{} + } else { + cv = *v + } + + for _, value := range shape { + var col types.WebAuthnCredentialDescription + destAddr := &col + if err := awsAwsjson11_deserializeDocumentWebAuthnCredentialDescription(&destAddr, value); err != nil { + return err + } + col = *destAddr + cv = append(cv, col) + + } + *v = cv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnCredentialNotSupportedException(v **types.WebAuthnCredentialNotSupportedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnCredentialNotSupportedException + if *v == nil { + sv = &types.WebAuthnCredentialNotSupportedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnNotEnabledException(v **types.WebAuthnNotEnabledException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnNotEnabledException + if *v == nil { + sv = &types.WebAuthnNotEnabledException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnOriginNotAllowedException(v **types.WebAuthnOriginNotAllowedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnOriginNotAllowedException + if *v == nil { + sv = &types.WebAuthnOriginNotAllowedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeDocumentWebAuthnRelyingPartyMismatchException(v **types.WebAuthnRelyingPartyMismatchException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.WebAuthnRelyingPartyMismatchException + if *v == nil { + sv = &types.WebAuthnRelyingPartyMismatchException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected MessageType to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAddCustomAttributesOutput(v **AddCustomAttributesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AddCustomAttributesOutput + if *v == nil { + sv = &AddCustomAttributesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminConfirmSignUpOutput(v **AdminConfirmSignUpOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminConfirmSignUpOutput + if *v == nil { + sv = &AdminConfirmSignUpOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminCreateUserOutput(v **AdminCreateUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminCreateUserOutput + if *v == nil { + sv = &AdminCreateUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "User": + if err := awsAwsjson11_deserializeDocumentUserType(&sv.User, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminDeleteUserAttributesOutput(v **AdminDeleteUserAttributesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminDeleteUserAttributesOutput + if *v == nil { + sv = &AdminDeleteUserAttributesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminDisableProviderForUserOutput(v **AdminDisableProviderForUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminDisableProviderForUserOutput + if *v == nil { + sv = &AdminDisableProviderForUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminDisableUserOutput(v **AdminDisableUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminDisableUserOutput + if *v == nil { + sv = &AdminDisableUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminEnableUserOutput(v **AdminEnableUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminEnableUserOutput + if *v == nil { + sv = &AdminEnableUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminGetDeviceOutput(v **AdminGetDeviceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminGetDeviceOutput + if *v == nil { + sv = &AdminGetDeviceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Device": + if err := awsAwsjson11_deserializeDocumentDeviceType(&sv.Device, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminGetUserOutput(v **AdminGetUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminGetUserOutput + if *v == nil { + sv = &AdminGetUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Enabled": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.Enabled = jtv + } + + case "MFAOptions": + if err := awsAwsjson11_deserializeDocumentMFAOptionListType(&sv.MFAOptions, value); err != nil { + return err + } + + case "PreferredMfaSetting": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.PreferredMfaSetting = ptr.String(jtv) + } + + case "UserAttributes": + if err := awsAwsjson11_deserializeDocumentAttributeListType(&sv.UserAttributes, value); err != nil { + return err + } + + case "UserCreateDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UserCreateDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "UserLastModifiedDate": + if value != nil { + switch jtv := value.(type) { + case json.Number: + f64, err := jtv.Float64() + if err != nil { + return err + } + sv.UserLastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) + + default: + return fmt.Errorf("expected DateType to be a JSON Number, got %T instead", value) + + } + } + + case "UserMFASettingList": + if err := awsAwsjson11_deserializeDocumentUserMFASettingListType(&sv.UserMFASettingList, value); err != nil { + return err + } + + case "Username": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UsernameType to be of type string, got %T instead", value) + } + sv.Username = ptr.String(jtv) + } + + case "UserStatus": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserStatusType to be of type string, got %T instead", value) + } + sv.UserStatus = types.UserStatusType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminInitiateAuthOutput(v **AdminInitiateAuthOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminInitiateAuthOutput + if *v == nil { + sv = &AdminInitiateAuthOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthenticationResult": + if err := awsAwsjson11_deserializeDocumentAuthenticationResultType(&sv.AuthenticationResult, value); err != nil { + return err + } + + case "AvailableChallenges": + if err := awsAwsjson11_deserializeDocumentAvailableChallengeListType(&sv.AvailableChallenges, value); err != nil { + return err + } + + case "ChallengeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeNameType to be of type string, got %T instead", value) + } + sv.ChallengeName = types.ChallengeNameType(jtv) + } + + case "ChallengeParameters": + if err := awsAwsjson11_deserializeDocumentChallengeParametersType(&sv.ChallengeParameters, value); err != nil { + return err + } + + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminLinkProviderForUserOutput(v **AdminLinkProviderForUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminLinkProviderForUserOutput + if *v == nil { + sv = &AdminLinkProviderForUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminListDevicesOutput(v **AdminListDevicesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminListDevicesOutput + if *v == nil { + sv = &AdminListDevicesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Devices": + if err := awsAwsjson11_deserializeDocumentDeviceListType(&sv.Devices, value); err != nil { + return err + } + + case "PaginationToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SearchPaginationTokenType to be of type string, got %T instead", value) + } + sv.PaginationToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminListGroupsForUserOutput(v **AdminListGroupsForUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminListGroupsForUserOutput + if *v == nil { + sv = &AdminListGroupsForUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Groups": + if err := awsAwsjson11_deserializeDocumentGroupListType(&sv.Groups, value); err != nil { + return err + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKey to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminListUserAuthEventsOutput(v **AdminListUserAuthEventsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminListUserAuthEventsOutput + if *v == nil { + sv = &AdminListUserAuthEventsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthEvents": + if err := awsAwsjson11_deserializeDocumentAuthEventsType(&sv.AuthEvents, value); err != nil { + return err + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKey to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminResetUserPasswordOutput(v **AdminResetUserPasswordOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminResetUserPasswordOutput + if *v == nil { + sv = &AdminResetUserPasswordOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminRespondToAuthChallengeOutput(v **AdminRespondToAuthChallengeOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminRespondToAuthChallengeOutput + if *v == nil { + sv = &AdminRespondToAuthChallengeOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthenticationResult": + if err := awsAwsjson11_deserializeDocumentAuthenticationResultType(&sv.AuthenticationResult, value); err != nil { + return err + } + + case "ChallengeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeNameType to be of type string, got %T instead", value) + } + sv.ChallengeName = types.ChallengeNameType(jtv) + } + + case "ChallengeParameters": + if err := awsAwsjson11_deserializeDocumentChallengeParametersType(&sv.ChallengeParameters, value); err != nil { + return err + } + + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminSetUserMFAPreferenceOutput(v **AdminSetUserMFAPreferenceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminSetUserMFAPreferenceOutput + if *v == nil { + sv = &AdminSetUserMFAPreferenceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminSetUserPasswordOutput(v **AdminSetUserPasswordOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminSetUserPasswordOutput + if *v == nil { + sv = &AdminSetUserPasswordOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminSetUserSettingsOutput(v **AdminSetUserSettingsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminSetUserSettingsOutput + if *v == nil { + sv = &AdminSetUserSettingsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminUpdateAuthEventFeedbackOutput(v **AdminUpdateAuthEventFeedbackOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminUpdateAuthEventFeedbackOutput + if *v == nil { + sv = &AdminUpdateAuthEventFeedbackOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminUpdateDeviceStatusOutput(v **AdminUpdateDeviceStatusOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminUpdateDeviceStatusOutput + if *v == nil { + sv = &AdminUpdateDeviceStatusOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminUpdateUserAttributesOutput(v **AdminUpdateUserAttributesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminUpdateUserAttributesOutput + if *v == nil { + sv = &AdminUpdateUserAttributesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAdminUserGlobalSignOutOutput(v **AdminUserGlobalSignOutOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AdminUserGlobalSignOutOutput + if *v == nil { + sv = &AdminUserGlobalSignOutOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentAssociateSoftwareTokenOutput(v **AssociateSoftwareTokenOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *AssociateSoftwareTokenOutput + if *v == nil { + sv = &AssociateSoftwareTokenOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "SecretCode": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SecretCodeType to be of type string, got %T instead", value) + } + sv.SecretCode = ptr.String(jtv) + } + + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentChangePasswordOutput(v **ChangePasswordOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ChangePasswordOutput + if *v == nil { + sv = &ChangePasswordOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCompleteWebAuthnRegistrationOutput(v **CompleteWebAuthnRegistrationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CompleteWebAuthnRegistrationOutput + if *v == nil { + sv = &CompleteWebAuthnRegistrationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentConfirmDeviceOutput(v **ConfirmDeviceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ConfirmDeviceOutput + if *v == nil { + sv = &ConfirmDeviceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserConfirmationNecessary": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.UserConfirmationNecessary = jtv + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentConfirmForgotPasswordOutput(v **ConfirmForgotPasswordOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ConfirmForgotPasswordOutput + if *v == nil { + sv = &ConfirmForgotPasswordOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentConfirmSignUpOutput(v **ConfirmSignUpOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ConfirmSignUpOutput + if *v == nil { + sv = &ConfirmSignUpOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateGroupOutput(v **CreateGroupOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateGroupOutput + if *v == nil { + sv = &CreateGroupOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Group": + if err := awsAwsjson11_deserializeDocumentGroupType(&sv.Group, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateIdentityProviderOutput(v **CreateIdentityProviderOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateIdentityProviderOutput + if *v == nil { + sv = &CreateIdentityProviderOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "IdentityProvider": + if err := awsAwsjson11_deserializeDocumentIdentityProviderType(&sv.IdentityProvider, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateManagedLoginBrandingOutput(v **CreateManagedLoginBrandingOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateManagedLoginBrandingOutput + if *v == nil { + sv = &CreateManagedLoginBrandingOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ManagedLoginBranding": + if err := awsAwsjson11_deserializeDocumentManagedLoginBrandingType(&sv.ManagedLoginBranding, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateResourceServerOutput(v **CreateResourceServerOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateResourceServerOutput + if *v == nil { + sv = &CreateResourceServerOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ResourceServer": + if err := awsAwsjson11_deserializeDocumentResourceServerType(&sv.ResourceServer, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateUserImportJobOutput(v **CreateUserImportJobOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateUserImportJobOutput + if *v == nil { + sv = &CreateUserImportJobOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserImportJob": + if err := awsAwsjson11_deserializeDocumentUserImportJobType(&sv.UserImportJob, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateUserPoolClientOutput(v **CreateUserPoolClientOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateUserPoolClientOutput + if *v == nil { + sv = &CreateUserPoolClientOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserPoolClient": + if err := awsAwsjson11_deserializeDocumentUserPoolClientType(&sv.UserPoolClient, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateUserPoolDomainOutput(v **CreateUserPoolDomainOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateUserPoolDomainOutput + if *v == nil { + sv = &CreateUserPoolDomainOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CloudFrontDomain": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainType to be of type string, got %T instead", value) + } + sv.CloudFrontDomain = ptr.String(jtv) + } + + case "ManagedLoginVersion": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected WrappedIntegerType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ManagedLoginVersion = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentCreateUserPoolOutput(v **CreateUserPoolOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateUserPoolOutput + if *v == nil { + sv = &CreateUserPoolOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserPool": + if err := awsAwsjson11_deserializeDocumentUserPoolType(&sv.UserPool, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDeleteUserAttributesOutput(v **DeleteUserAttributesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DeleteUserAttributesOutput + if *v == nil { + sv = &DeleteUserAttributesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDeleteUserPoolDomainOutput(v **DeleteUserPoolDomainOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DeleteUserPoolDomainOutput + if *v == nil { + sv = &DeleteUserPoolDomainOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDeleteWebAuthnCredentialOutput(v **DeleteWebAuthnCredentialOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DeleteWebAuthnCredentialOutput + if *v == nil { + sv = &DeleteWebAuthnCredentialOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeIdentityProviderOutput(v **DescribeIdentityProviderOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeIdentityProviderOutput + if *v == nil { + sv = &DescribeIdentityProviderOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "IdentityProvider": + if err := awsAwsjson11_deserializeDocumentIdentityProviderType(&sv.IdentityProvider, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeManagedLoginBrandingByClientOutput(v **DescribeManagedLoginBrandingByClientOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeManagedLoginBrandingByClientOutput + if *v == nil { + sv = &DescribeManagedLoginBrandingByClientOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ManagedLoginBranding": + if err := awsAwsjson11_deserializeDocumentManagedLoginBrandingType(&sv.ManagedLoginBranding, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeManagedLoginBrandingOutput(v **DescribeManagedLoginBrandingOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeManagedLoginBrandingOutput + if *v == nil { + sv = &DescribeManagedLoginBrandingOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ManagedLoginBranding": + if err := awsAwsjson11_deserializeDocumentManagedLoginBrandingType(&sv.ManagedLoginBranding, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeResourceServerOutput(v **DescribeResourceServerOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeResourceServerOutput + if *v == nil { + sv = &DescribeResourceServerOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ResourceServer": + if err := awsAwsjson11_deserializeDocumentResourceServerType(&sv.ResourceServer, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeRiskConfigurationOutput(v **DescribeRiskConfigurationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeRiskConfigurationOutput + if *v == nil { + sv = &DescribeRiskConfigurationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "RiskConfiguration": + if err := awsAwsjson11_deserializeDocumentRiskConfigurationType(&sv.RiskConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeUserImportJobOutput(v **DescribeUserImportJobOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeUserImportJobOutput + if *v == nil { + sv = &DescribeUserImportJobOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserImportJob": + if err := awsAwsjson11_deserializeDocumentUserImportJobType(&sv.UserImportJob, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeUserPoolClientOutput(v **DescribeUserPoolClientOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeUserPoolClientOutput + if *v == nil { + sv = &DescribeUserPoolClientOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserPoolClient": + if err := awsAwsjson11_deserializeDocumentUserPoolClientType(&sv.UserPoolClient, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeUserPoolDomainOutput(v **DescribeUserPoolDomainOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeUserPoolDomainOutput + if *v == nil { + sv = &DescribeUserPoolDomainOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "DomainDescription": + if err := awsAwsjson11_deserializeDocumentDomainDescriptionType(&sv.DomainDescription, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentDescribeUserPoolOutput(v **DescribeUserPoolOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *DescribeUserPoolOutput + if *v == nil { + sv = &DescribeUserPoolOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserPool": + if err := awsAwsjson11_deserializeDocumentUserPoolType(&sv.UserPool, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentForgotPasswordOutput(v **ForgotPasswordOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ForgotPasswordOutput + if *v == nil { + sv = &ForgotPasswordOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CodeDeliveryDetails": + if err := awsAwsjson11_deserializeDocumentCodeDeliveryDetailsType(&sv.CodeDeliveryDetails, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetCSVHeaderOutput(v **GetCSVHeaderOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetCSVHeaderOutput + if *v == nil { + sv = &GetCSVHeaderOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CSVHeader": + if err := awsAwsjson11_deserializeDocumentListOfStringTypes(&sv.CSVHeader, value); err != nil { + return err + } + + case "UserPoolId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolIdType to be of type string, got %T instead", value) + } + sv.UserPoolId = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetDeviceOutput(v **GetDeviceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetDeviceOutput + if *v == nil { + sv = &GetDeviceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Device": + if err := awsAwsjson11_deserializeDocumentDeviceType(&sv.Device, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetGroupOutput(v **GetGroupOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetGroupOutput + if *v == nil { + sv = &GetGroupOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Group": + if err := awsAwsjson11_deserializeDocumentGroupType(&sv.Group, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetIdentityProviderByIdentifierOutput(v **GetIdentityProviderByIdentifierOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetIdentityProviderByIdentifierOutput + if *v == nil { + sv = &GetIdentityProviderByIdentifierOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "IdentityProvider": + if err := awsAwsjson11_deserializeDocumentIdentityProviderType(&sv.IdentityProvider, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetLogDeliveryConfigurationOutput(v **GetLogDeliveryConfigurationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetLogDeliveryConfigurationOutput + if *v == nil { + sv = &GetLogDeliveryConfigurationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LogDeliveryConfiguration": + if err := awsAwsjson11_deserializeDocumentLogDeliveryConfigurationType(&sv.LogDeliveryConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetSigningCertificateOutput(v **GetSigningCertificateOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetSigningCertificateOutput + if *v == nil { + sv = &GetSigningCertificateOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Certificate": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.Certificate = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetTokensFromRefreshTokenOutput(v **GetTokensFromRefreshTokenOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetTokensFromRefreshTokenOutput + if *v == nil { + sv = &GetTokensFromRefreshTokenOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthenticationResult": + if err := awsAwsjson11_deserializeDocumentAuthenticationResultType(&sv.AuthenticationResult, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetUICustomizationOutput(v **GetUICustomizationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetUICustomizationOutput + if *v == nil { + sv = &GetUICustomizationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UICustomization": + if err := awsAwsjson11_deserializeDocumentUICustomizationType(&sv.UICustomization, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetUserAttributeVerificationCodeOutput(v **GetUserAttributeVerificationCodeOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetUserAttributeVerificationCodeOutput + if *v == nil { + sv = &GetUserAttributeVerificationCodeOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CodeDeliveryDetails": + if err := awsAwsjson11_deserializeDocumentCodeDeliveryDetailsType(&sv.CodeDeliveryDetails, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetUserAuthFactorsOutput(v **GetUserAuthFactorsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetUserAuthFactorsOutput + if *v == nil { + sv = &GetUserAuthFactorsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ConfiguredUserAuthFactors": + if err := awsAwsjson11_deserializeDocumentConfiguredUserAuthFactorsListType(&sv.ConfiguredUserAuthFactors, value); err != nil { + return err + } + + case "PreferredMfaSetting": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.PreferredMfaSetting = ptr.String(jtv) + } + + case "UserMFASettingList": + if err := awsAwsjson11_deserializeDocumentUserMFASettingListType(&sv.UserMFASettingList, value); err != nil { + return err + } + + case "Username": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UsernameType to be of type string, got %T instead", value) + } + sv.Username = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetUserOutput(v **GetUserOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetUserOutput + if *v == nil { + sv = &GetUserOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "MFAOptions": + if err := awsAwsjson11_deserializeDocumentMFAOptionListType(&sv.MFAOptions, value); err != nil { + return err + } + + case "PreferredMfaSetting": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.PreferredMfaSetting = ptr.String(jtv) + } + + case "UserAttributes": + if err := awsAwsjson11_deserializeDocumentAttributeListType(&sv.UserAttributes, value); err != nil { + return err + } + + case "UserMFASettingList": + if err := awsAwsjson11_deserializeDocumentUserMFASettingListType(&sv.UserMFASettingList, value); err != nil { + return err + } + + case "Username": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UsernameType to be of type string, got %T instead", value) + } + sv.Username = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGetUserPoolMfaConfigOutput(v **GetUserPoolMfaConfigOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GetUserPoolMfaConfigOutput + if *v == nil { + sv = &GetUserPoolMfaConfigOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "EmailMfaConfiguration": + if err := awsAwsjson11_deserializeDocumentEmailMfaConfigType(&sv.EmailMfaConfiguration, value); err != nil { + return err + } + + case "MfaConfiguration": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolMfaType to be of type string, got %T instead", value) + } + sv.MfaConfiguration = types.UserPoolMfaType(jtv) + } + + case "SmsMfaConfiguration": + if err := awsAwsjson11_deserializeDocumentSmsMfaConfigType(&sv.SmsMfaConfiguration, value); err != nil { + return err + } + + case "SoftwareTokenMfaConfiguration": + if err := awsAwsjson11_deserializeDocumentSoftwareTokenMfaConfigType(&sv.SoftwareTokenMfaConfiguration, value); err != nil { + return err + } + + case "WebAuthnConfiguration": + if err := awsAwsjson11_deserializeDocumentWebAuthnConfigurationType(&sv.WebAuthnConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentGlobalSignOutOutput(v **GlobalSignOutOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *GlobalSignOutOutput + if *v == nil { + sv = &GlobalSignOutOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentInitiateAuthOutput(v **InitiateAuthOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *InitiateAuthOutput + if *v == nil { + sv = &InitiateAuthOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthenticationResult": + if err := awsAwsjson11_deserializeDocumentAuthenticationResultType(&sv.AuthenticationResult, value); err != nil { + return err + } + + case "AvailableChallenges": + if err := awsAwsjson11_deserializeDocumentAvailableChallengeListType(&sv.AvailableChallenges, value); err != nil { + return err + } + + case "ChallengeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeNameType to be of type string, got %T instead", value) + } + sv.ChallengeName = types.ChallengeNameType(jtv) + } + + case "ChallengeParameters": + if err := awsAwsjson11_deserializeDocumentChallengeParametersType(&sv.ChallengeParameters, value); err != nil { + return err + } + + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListDevicesOutput(v **ListDevicesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListDevicesOutput + if *v == nil { + sv = &ListDevicesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Devices": + if err := awsAwsjson11_deserializeDocumentDeviceListType(&sv.Devices, value); err != nil { + return err + } + + case "PaginationToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SearchPaginationTokenType to be of type string, got %T instead", value) + } + sv.PaginationToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListGroupsOutput(v **ListGroupsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListGroupsOutput + if *v == nil { + sv = &ListGroupsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Groups": + if err := awsAwsjson11_deserializeDocumentGroupListType(&sv.Groups, value); err != nil { + return err + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKey to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListIdentityProvidersOutput(v **ListIdentityProvidersOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListIdentityProvidersOutput + if *v == nil { + sv = &ListIdentityProvidersOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKeyType to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "Providers": + if err := awsAwsjson11_deserializeDocumentProvidersListType(&sv.Providers, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListResourceServersOutput(v **ListResourceServersOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListResourceServersOutput + if *v == nil { + sv = &ListResourceServersOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKeyType to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "ResourceServers": + if err := awsAwsjson11_deserializeDocumentResourceServersListType(&sv.ResourceServers, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(v **ListTagsForResourceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListTagsForResourceOutput + if *v == nil { + sv = &ListTagsForResourceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Tags": + if err := awsAwsjson11_deserializeDocumentUserPoolTagsType(&sv.Tags, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListUserImportJobsOutput(v **ListUserImportJobsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListUserImportJobsOutput + if *v == nil { + sv = &ListUserImportJobsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "PaginationToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKeyType to be of type string, got %T instead", value) + } + sv.PaginationToken = ptr.String(jtv) + } + + case "UserImportJobs": + if err := awsAwsjson11_deserializeDocumentUserImportJobsListType(&sv.UserImportJobs, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListUserPoolClientsOutput(v **ListUserPoolClientsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListUserPoolClientsOutput + if *v == nil { + sv = &ListUserPoolClientsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKey to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "UserPoolClients": + if err := awsAwsjson11_deserializeDocumentUserPoolClientListType(&sv.UserPoolClients, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListUserPoolsOutput(v **ListUserPoolsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListUserPoolsOutput + if *v == nil { + sv = &ListUserPoolsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKeyType to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "UserPools": + if err := awsAwsjson11_deserializeDocumentUserPoolListType(&sv.UserPools, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListUsersInGroupOutput(v **ListUsersInGroupOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListUsersInGroupOutput + if *v == nil { + sv = &ListUsersInGroupOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKey to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + case "Users": + if err := awsAwsjson11_deserializeDocumentUsersListType(&sv.Users, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListUsersOutput(v **ListUsersOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListUsersOutput + if *v == nil { + sv = &ListUsersOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "PaginationToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SearchPaginationTokenType to be of type string, got %T instead", value) + } + sv.PaginationToken = ptr.String(jtv) + } + + case "Users": + if err := awsAwsjson11_deserializeDocumentUsersListType(&sv.Users, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentListWebAuthnCredentialsOutput(v **ListWebAuthnCredentialsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ListWebAuthnCredentialsOutput + if *v == nil { + sv = &ListWebAuthnCredentialsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Credentials": + if err := awsAwsjson11_deserializeDocumentWebAuthnCredentialDescriptionListType(&sv.Credentials, value); err != nil { + return err + } + + case "NextToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected PaginationKey to be of type string, got %T instead", value) + } + sv.NextToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentResendConfirmationCodeOutput(v **ResendConfirmationCodeOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *ResendConfirmationCodeOutput + if *v == nil { + sv = &ResendConfirmationCodeOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CodeDeliveryDetails": + if err := awsAwsjson11_deserializeDocumentCodeDeliveryDetailsType(&sv.CodeDeliveryDetails, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentRespondToAuthChallengeOutput(v **RespondToAuthChallengeOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *RespondToAuthChallengeOutput + if *v == nil { + sv = &RespondToAuthChallengeOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "AuthenticationResult": + if err := awsAwsjson11_deserializeDocumentAuthenticationResultType(&sv.AuthenticationResult, value); err != nil { + return err + } + + case "ChallengeName": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected ChallengeNameType to be of type string, got %T instead", value) + } + sv.ChallengeName = types.ChallengeNameType(jtv) + } + + case "ChallengeParameters": + if err := awsAwsjson11_deserializeDocumentChallengeParametersType(&sv.ChallengeParameters, value); err != nil { + return err + } + + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentRevokeTokenOutput(v **RevokeTokenOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *RevokeTokenOutput + if *v == nil { + sv = &RevokeTokenOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSetLogDeliveryConfigurationOutput(v **SetLogDeliveryConfigurationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SetLogDeliveryConfigurationOutput + if *v == nil { + sv = &SetLogDeliveryConfigurationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "LogDeliveryConfiguration": + if err := awsAwsjson11_deserializeDocumentLogDeliveryConfigurationType(&sv.LogDeliveryConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSetRiskConfigurationOutput(v **SetRiskConfigurationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SetRiskConfigurationOutput + if *v == nil { + sv = &SetRiskConfigurationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "RiskConfiguration": + if err := awsAwsjson11_deserializeDocumentRiskConfigurationType(&sv.RiskConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSetUICustomizationOutput(v **SetUICustomizationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SetUICustomizationOutput + if *v == nil { + sv = &SetUICustomizationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UICustomization": + if err := awsAwsjson11_deserializeDocumentUICustomizationType(&sv.UICustomization, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSetUserMFAPreferenceOutput(v **SetUserMFAPreferenceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SetUserMFAPreferenceOutput + if *v == nil { + sv = &SetUserMFAPreferenceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSetUserPoolMfaConfigOutput(v **SetUserPoolMfaConfigOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SetUserPoolMfaConfigOutput + if *v == nil { + sv = &SetUserPoolMfaConfigOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "EmailMfaConfiguration": + if err := awsAwsjson11_deserializeDocumentEmailMfaConfigType(&sv.EmailMfaConfiguration, value); err != nil { + return err + } + + case "MfaConfiguration": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected UserPoolMfaType to be of type string, got %T instead", value) + } + sv.MfaConfiguration = types.UserPoolMfaType(jtv) + } + + case "SmsMfaConfiguration": + if err := awsAwsjson11_deserializeDocumentSmsMfaConfigType(&sv.SmsMfaConfiguration, value); err != nil { + return err + } + + case "SoftwareTokenMfaConfiguration": + if err := awsAwsjson11_deserializeDocumentSoftwareTokenMfaConfigType(&sv.SoftwareTokenMfaConfiguration, value); err != nil { + return err + } + + case "WebAuthnConfiguration": + if err := awsAwsjson11_deserializeDocumentWebAuthnConfigurationType(&sv.WebAuthnConfiguration, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSetUserSettingsOutput(v **SetUserSettingsOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SetUserSettingsOutput + if *v == nil { + sv = &SetUserSettingsOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentSignUpOutput(v **SignUpOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *SignUpOutput + if *v == nil { + sv = &SignUpOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CodeDeliveryDetails": + if err := awsAwsjson11_deserializeDocumentCodeDeliveryDetailsType(&sv.CodeDeliveryDetails, value); err != nil { + return err + } + + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + case "UserConfirmed": + if value != nil { + jtv, ok := value.(bool) + if !ok { + return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) + } + sv.UserConfirmed = jtv + } + + case "UserSub": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected StringType to be of type string, got %T instead", value) + } + sv.UserSub = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStartUserImportJobOutput(v **StartUserImportJobOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StartUserImportJobOutput + if *v == nil { + sv = &StartUserImportJobOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserImportJob": + if err := awsAwsjson11_deserializeDocumentUserImportJobType(&sv.UserImportJob, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStartWebAuthnRegistrationOutput(v **StartWebAuthnRegistrationOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StartWebAuthnRegistrationOutput + if *v == nil { + sv = &StartWebAuthnRegistrationOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CredentialCreationOptions": + if err := awsAwsjson11_deserializeDocumentDocument(&sv.CredentialCreationOptions, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentStopUserImportJobOutput(v **StopUserImportJobOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *StopUserImportJobOutput + if *v == nil { + sv = &StopUserImportJobOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserImportJob": + if err := awsAwsjson11_deserializeDocumentUserImportJobType(&sv.UserImportJob, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentTagResourceOutput(v **TagResourceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *TagResourceOutput + if *v == nil { + sv = &TagResourceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUntagResourceOutput(v **UntagResourceOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UntagResourceOutput + if *v == nil { + sv = &UntagResourceOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateAuthEventFeedbackOutput(v **UpdateAuthEventFeedbackOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateAuthEventFeedbackOutput + if *v == nil { + sv = &UpdateAuthEventFeedbackOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateDeviceStatusOutput(v **UpdateDeviceStatusOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateDeviceStatusOutput + if *v == nil { + sv = &UpdateDeviceStatusOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateGroupOutput(v **UpdateGroupOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateGroupOutput + if *v == nil { + sv = &UpdateGroupOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Group": + if err := awsAwsjson11_deserializeDocumentGroupType(&sv.Group, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateIdentityProviderOutput(v **UpdateIdentityProviderOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateIdentityProviderOutput + if *v == nil { + sv = &UpdateIdentityProviderOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "IdentityProvider": + if err := awsAwsjson11_deserializeDocumentIdentityProviderType(&sv.IdentityProvider, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateManagedLoginBrandingOutput(v **UpdateManagedLoginBrandingOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateManagedLoginBrandingOutput + if *v == nil { + sv = &UpdateManagedLoginBrandingOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ManagedLoginBranding": + if err := awsAwsjson11_deserializeDocumentManagedLoginBrandingType(&sv.ManagedLoginBranding, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateResourceServerOutput(v **UpdateResourceServerOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateResourceServerOutput + if *v == nil { + sv = &UpdateResourceServerOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "ResourceServer": + if err := awsAwsjson11_deserializeDocumentResourceServerType(&sv.ResourceServer, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateUserAttributesOutput(v **UpdateUserAttributesOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateUserAttributesOutput + if *v == nil { + sv = &UpdateUserAttributesOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CodeDeliveryDetailsList": + if err := awsAwsjson11_deserializeDocumentCodeDeliveryDetailsListType(&sv.CodeDeliveryDetailsList, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateUserPoolClientOutput(v **UpdateUserPoolClientOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateUserPoolClientOutput + if *v == nil { + sv = &UpdateUserPoolClientOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "UserPoolClient": + if err := awsAwsjson11_deserializeDocumentUserPoolClientType(&sv.UserPoolClient, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateUserPoolDomainOutput(v **UpdateUserPoolDomainOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateUserPoolDomainOutput + if *v == nil { + sv = &UpdateUserPoolDomainOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "CloudFrontDomain": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected DomainType to be of type string, got %T instead", value) + } + sv.CloudFrontDomain = ptr.String(jtv) + } + + case "ManagedLoginVersion": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected WrappedIntegerType to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ManagedLoginVersion = ptr.Int32(int32(i64)) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentUpdateUserPoolOutput(v **UpdateUserPoolOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *UpdateUserPoolOutput + if *v == nil { + sv = &UpdateUserPoolOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentVerifySoftwareTokenOutput(v **VerifySoftwareTokenOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *VerifySoftwareTokenOutput + if *v == nil { + sv = &VerifySoftwareTokenOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "Session": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected SessionType to be of type string, got %T instead", value) + } + sv.Session = ptr.String(jtv) + } + + case "Status": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected VerifySoftwareTokenResponseType to be of type string, got %T instead", value) + } + sv.Status = types.VerifySoftwareTokenResponseType(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsAwsjson11_deserializeOpDocumentVerifyUserAttributeOutput(v **VerifyUserAttributeOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *VerifyUserAttributeOutput + if *v == nil { + sv = &VerifyUserAttributeOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +type protocolErrorInfo struct { + Type string `json:"__type"` + Message string + Code any // nonstandard for awsjson but some services do present the type here +} + +func getProtocolErrorInfo(decoder *json.Decoder) (protocolErrorInfo, error) { + var errInfo protocolErrorInfo + if err := decoder.Decode(&errInfo); err != nil { + if err == io.EOF { + return errInfo, nil + } + return errInfo, err + } + + return errInfo, nil +} + +func resolveProtocolErrorType(headerType string, bodyInfo protocolErrorInfo) (string, bool) { + if len(headerType) != 0 { + return headerType, true + } else if len(bodyInfo.Type) != 0 { + return bodyInfo.Type, true + } else if code, ok := bodyInfo.Code.(string); ok && len(code) != 0 { + return code, true + } + return "", false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/doc.go new file mode 100644 index 00000000..9b06d4a3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/doc.go @@ -0,0 +1,45 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +// Package cognitoidentityprovider provides the API client, operations, and +// parameter types for Amazon Cognito Identity Provider. +// +// With the Amazon Cognito user pools API, you can configure user pools and +// authenticate users. To authenticate users from third-party identity providers +// (IdPs) in this API, you can [link IdP users to native user profiles]. Learn more about the authentication and +// authorization of federated users at [Adding user pool sign-in through a third party]and in the [User pool federation endpoints and managed login reference]. +// +// This API reference provides detailed information about API operations and +// object types in Amazon Cognito. +// +// Along with resource management operations, the Amazon Cognito user pools API +// includes classes of operations and authorization models for client-side and +// server-side authentication of users. You can interact with operations in the +// Amazon Cognito user pools API as any of the following subjects. +// +// - An administrator who wants to configure user pools, app clients, users, +// groups, or other user pool functions. +// +// - A server-side app, like a web application, that wants to use its Amazon Web +// Services privileges to manage, authenticate, or authorize a user. +// +// - A client-side app, like a mobile app, that wants to make unauthenticated +// requests to manage, authenticate, or authorize a user. +// +// For more information, see [Understanding API, OIDC, and managed login pages authentication] in the Amazon Cognito Developer Guide. +// +// With your Amazon Web Services SDK, you can build the logic to support +// operational flows in every use case for this API. You can also make direct REST +// API requests to [Amazon Cognito user pools service endpoints]. The following links can get you started with the +// CognitoIdentityProvider client in supported Amazon Web Services SDKs. +// +// To get started with an Amazon Web Services SDK, see [Tools to Build on Amazon Web Services]. For example actions and +// scenarios, see [Code examples for Amazon Cognito Identity Provider using Amazon Web Services SDKs]. +// +// [Adding user pool sign-in through a third party]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html +// [User pool federation endpoints and managed login reference]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html +// [Amazon Cognito user pools service endpoints]: https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html#cognito_identity_your_user_pools_region +// [Understanding API, OIDC, and managed login pages authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flows-public-server-side.html#user-pools-API-operations +// [link IdP users to native user profiles]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation-consolidate-users.html +// [Tools to Build on Amazon Web Services]: http://aws.amazon.com/developer/tools/ +// [Code examples for Amazon Cognito Identity Provider using Amazon Web Services SDKs]: https://docs.aws.amazon.com/cognito/latest/developerguide/service_code_examples_cognito-identity-provider.html +package cognitoidentityprovider diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/doc.go new file mode 100644 index 00000000..2b06b14f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/doc.go @@ -0,0 +1,66 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +// Package document implements encoding and decoding of open-content that has a JSON-like data model. +// This data-model allows for UTF-8 strings, arbitrary precision numbers, booleans, nulls, a list of these values, and a +// map of UTF-8 strings to these values. +// +// Interface defines the semantics for how a document type is marshalled and unmarshalled for requests and responses +// for the service. To send a document as input to the service you use NewLazyDocument and pass it the Go type to be +// sent to the service. NewLazyDocument returns a document Interface type that encodes the provided Go type during +// the request serialization step after you have invoked an API client operation that uses the document type. +// +// The following examples show how you can create document types using basic Go types. +// +// NewLazyDocument(map[string]interface{}{ +// "favoriteNumber": 42, +// "fruits": []string{"apple", "orange"}, +// "capitals": map[string]interface{}{ +// "Washington": "Olympia", +// "Oregon": "Salem", +// }, +// "skyIsBlue": true, +// }) +// +// NewLazyDocument(3.14159) +// +// NewLazyDocument([]interface{"One", 2, 3, 3.5, "four"}) +// +// NewLazyDocument(true) +// +// Services can send document types as part of their API responses. To retrieve the content of a response document +// you use the UnmarshalSmithyDocument method on the response document. When calling UnmarshalSmithyDocument you pass +// a reference to the Go type that you want to unmarshal and map the response to. +// +// For example, if you expect to receive key/value map from the service response: +// +// var kv map[string]interface{} +// if err := outputDocument.UnmarshalSmithyDocument(&kv); err != nil { +// // handle error +// } +// +// If a service can return one or more data-types in the response, you can use an empty interface and type switch to +// dynamically handle the response type. +// +// var v interface{} +// if err := outputDocument.UnmarshalSmithyDocument(&v); err != nil { +// // handle error +// } +// +// switch vv := v.(type) { +// case map[string]interface{}: +// // handle key/value map +// case []interface{}: +// // handle array of values +// case bool: +// // handle boolean +// case document.Number: +// // handle an arbitrary precision number +// case string: +// // handle string +// default: +// // handle unknown case +// } +// +// The mapping of Go types to document types is covered in more depth in https://pkg.go.dev/github.com/aws/smithy-go/document +// including more in depth examples that cover user-defined structure types. +package document diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/document.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/document.go new file mode 100644 index 00000000..dc1fe3e6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document/document.go @@ -0,0 +1,34 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package document + +import ( + internaldocument "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document" +) + +// Interface defines a document which is a protocol-agnostic type which supports a +// JSON-like data-model. You can use this type to send UTF-8 strings, arbitrary +// precision numbers, booleans, nulls, a list of these values, and a map of UTF-8 +// strings to these values. +// +// You create a document type using the NewLazyDocument function and passing it +// the Go type to marshal. When receiving a document in an API response, you use +// the document's UnmarshalSmithyDocument function to decode the response to your +// desired Go type. Unless documented specifically generated structure types in +// client packages or client types packages are not supported at this time. Such +// types embed a noSmithyDocumentSerde and will cause an error to be returned when +// attempting to send an API request. +// +// For more information see the accompanying package documentation and linked +// references. +type Interface = internaldocument.Interface + +// You create document type using the NewLazyDocument function and passing it the +// Go type to be marshaled and sent to the service. The document marshaler supports +// semantics similar to the encoding/json Go standard library. +// +// For more information see the accompanying package documentation and linked +// references. +func NewLazyDocument(v interface{}) Interface { + return internaldocument.NewDocumentMarshaler(v) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/endpoints.go new file mode 100644 index 00000000..f1ae6443 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/endpoints.go @@ -0,0 +1,608 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "errors" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + "github.com/aws/aws-sdk-go-v2/internal/endpoints" + "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" + internalendpoints "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/endpoints" + smithyauth "github.com/aws/smithy-go/auth" + smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/ptr" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" + "net/url" + "os" + "strings" +) + +// EndpointResolverOptions is the service endpoint resolver options +type EndpointResolverOptions = internalendpoints.Options + +// EndpointResolver interface for resolving service endpoints. +type EndpointResolver interface { + ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) +} + +var _ EndpointResolver = &internalendpoints.Resolver{} + +// NewDefaultEndpointResolver constructs a new service endpoint resolver +func NewDefaultEndpointResolver() *internalendpoints.Resolver { + return internalendpoints.New() +} + +// EndpointResolverFunc is a helper utility that wraps a function so it satisfies +// the EndpointResolver interface. This is useful when you want to add additional +// endpoint resolving logic, or stub out specific endpoints with custom values. +type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) + +func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { + return fn(region, options) +} + +// EndpointResolverFromURL returns an EndpointResolver configured using the +// provided endpoint url. By default, the resolved endpoint resolver uses the +// client region as signing region, and the endpoint source is set to +// EndpointSourceCustom.You can provide functional options to configure endpoint +// values for the resolved endpoint. +func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { + e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} + for _, fn := range optFns { + fn(&e) + } + + return EndpointResolverFunc( + func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { + if len(e.SigningRegion) == 0 { + e.SigningRegion = region + } + return e, nil + }, + ) +} + +type ResolveEndpoint struct { + Resolver EndpointResolver + Options EndpointResolverOptions +} + +func (*ResolveEndpoint) ID() string { + return "ResolveEndpoint" +} + +func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleSerialize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.Resolver == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + eo := m.Options + eo.Logger = middleware.GetLogger(ctx) + + var endpoint aws.Endpoint + endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) + if err != nil { + nf := (&aws.EndpointNotFoundError{}) + if errors.As(err, &nf) { + ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) + return next.HandleSerialize(ctx, in) + } + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + req.URL, err = url.Parse(endpoint.URL) + if err != nil { + return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) + } + + if len(awsmiddleware.GetSigningName(ctx)) == 0 { + signingName := endpoint.SigningName + if len(signingName) == 0 { + signingName = "cognito-idp" + } + ctx = awsmiddleware.SetSigningName(ctx, signingName) + } + ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) + ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) + ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) + ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) + return next.HandleSerialize(ctx, in) +} +func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { + return stack.Serialize.Insert(&ResolveEndpoint{ + Resolver: o.EndpointResolver, + Options: o.EndpointOptions, + }, "OperationSerializer", middleware.Before) +} + +func removeResolveEndpointMiddleware(stack *middleware.Stack) error { + _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) + return err +} + +type wrappedEndpointResolver struct { + awsResolver aws.EndpointResolverWithOptions +} + +func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { + return w.awsResolver.ResolveEndpoint(ServiceID, region, options) +} + +type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) + +func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { + return a(service, region) +} + +var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) + +// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. +// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, +// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked +// via its middleware. +// +// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. +func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { + var resolver aws.EndpointResolverWithOptions + + if awsResolverWithOptions != nil { + resolver = awsResolverWithOptions + } else if awsResolver != nil { + resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) + } + + return &wrappedEndpointResolver{ + awsResolver: resolver, + } +} + +func finalizeClientEndpointResolverOptions(options *Options) { + options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() + + if len(options.EndpointOptions.ResolvedRegion) == 0 { + const fipsInfix = "-fips-" + const fipsPrefix = "fips-" + const fipsSuffix = "-fips" + + if strings.Contains(options.Region, fipsInfix) || + strings.Contains(options.Region, fipsPrefix) || + strings.Contains(options.Region, fipsSuffix) { + options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( + options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") + options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled + } + } + +} + +func resolveEndpointResolverV2(options *Options) { + if options.EndpointResolverV2 == nil { + options.EndpointResolverV2 = NewDefaultEndpointResolverV2() + } +} + +func resolveBaseEndpoint(cfg aws.Config, o *Options) { + if cfg.BaseEndpoint != nil { + o.BaseEndpoint = cfg.BaseEndpoint + } + + _, g := os.LookupEnv("AWS_ENDPOINT_URL") + _, s := os.LookupEnv("AWS_ENDPOINT_URL_COGNITO_IDENTITY_PROVIDER") + + if g && !s { + return + } + + value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "Cognito Identity Provider", cfg.ConfigSources) + if found && err == nil { + o.BaseEndpoint = &value + } +} + +func bindRegion(region string) *string { + if region == "" { + return nil + } + return aws.String(endpoints.MapFIPSRegion(region)) +} + +// EndpointParameters provides the parameters that influence how endpoints are +// resolved. +type EndpointParameters struct { + // The AWS region used to dispatch the request. + // + // Parameter is + // required. + // + // AWS::Region + Region *string + + // When true, use the dual-stack endpoint. If the configured endpoint does not + // support dual-stack, dispatching the request MAY return an error. + // + // Defaults to + // false if no value is provided. + // + // AWS::UseDualStack + UseDualStack *bool + + // When true, send this request to the FIPS-compliant regional endpoint. If the + // configured endpoint does not have a FIPS compliant endpoint, dispatching the + // request will return an error. + // + // Defaults to false if no value is + // provided. + // + // AWS::UseFIPS + UseFIPS *bool + + // Override the endpoint used to send this request + // + // Parameter is + // required. + // + // SDK::Endpoint + Endpoint *string +} + +// ValidateRequired validates required parameters are set. +func (p EndpointParameters) ValidateRequired() error { + if p.UseDualStack == nil { + return fmt.Errorf("parameter UseDualStack is required") + } + + if p.UseFIPS == nil { + return fmt.Errorf("parameter UseFIPS is required") + } + + return nil +} + +// WithDefaults returns a shallow copy of EndpointParameterswith default values +// applied to members where applicable. +func (p EndpointParameters) WithDefaults() EndpointParameters { + if p.UseDualStack == nil { + p.UseDualStack = ptr.Bool(false) + } + + if p.UseFIPS == nil { + p.UseFIPS = ptr.Bool(false) + } + return p +} + +type stringSlice []string + +func (s stringSlice) Get(i int) *string { + if i < 0 || i >= len(s) { + return nil + } + + v := s[i] + return &v +} + +// EndpointResolverV2 provides the interface for resolving service endpoints. +type EndpointResolverV2 interface { + // ResolveEndpoint attempts to resolve the endpoint with the provided options, + // returning the endpoint if found. Otherwise an error is returned. + ResolveEndpoint(ctx context.Context, params EndpointParameters) ( + smithyendpoints.Endpoint, error, + ) +} + +// resolver provides the implementation for resolving endpoints. +type resolver struct{} + +func NewDefaultEndpointResolverV2() EndpointResolverV2 { + return &resolver{} +} + +// ResolveEndpoint attempts to resolve the endpoint with the provided options, +// returning the endpoint if found. Otherwise an error is returned. +func (r *resolver) ResolveEndpoint( + ctx context.Context, params EndpointParameters, +) ( + endpoint smithyendpoints.Endpoint, err error, +) { + params = params.WithDefaults() + if err = params.ValidateRequired(); err != nil { + return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) + } + _UseDualStack := *params.UseDualStack + _UseFIPS := *params.UseFIPS + + if exprVal := params.Endpoint; exprVal != nil { + _Endpoint := *exprVal + _ = _Endpoint + if _UseFIPS == true { + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") + } + if _UseDualStack == true { + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") + } + uriString := _Endpoint + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + if exprVal := params.Region; exprVal != nil { + _Region := *exprVal + _ = _Region + if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { + _PartitionResult := *exprVal + _ = _PartitionResult + if _UseFIPS == true { + if _UseDualStack == true { + if true == _PartitionResult.SupportsFIPS { + if true == _PartitionResult.SupportsDualStack { + if _Region == "us-east-1" { + uriString := "https://cognito-idp-fips.us-east-1.amazonaws.com" + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + if _Region == "us-east-2" { + uriString := "https://cognito-idp-fips.us-east-2.amazonaws.com" + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + if _Region == "us-west-1" { + uriString := "https://cognito-idp-fips.us-west-1.amazonaws.com" + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + if _Region == "us-west-2" { + uriString := "https://cognito-idp-fips.us-west-2.amazonaws.com" + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + uriString := func() string { + var out strings.Builder + out.WriteString("https://cognito-idp-fips.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DualStackDnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") + } + } + if _UseFIPS == true { + if _PartitionResult.SupportsFIPS == true { + uriString := func() string { + var out strings.Builder + out.WriteString("https://cognito-idp-fips.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") + } + if _UseDualStack == true { + if true == _PartitionResult.SupportsDualStack { + if "aws" == _PartitionResult.Name { + uriString := func() string { + var out strings.Builder + out.WriteString("https://cognito-idp.") + out.WriteString(_Region) + out.WriteString(".amazonaws.com") + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + uriString := func() string { + var out strings.Builder + out.WriteString("https://cognito-idp.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DualStackDnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") + } + uriString := func() string { + var out strings.Builder + out.WriteString("https://cognito-idp.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") +} + +type endpointParamsBinder interface { + bindEndpointParams(*EndpointParameters) +} + +func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { + params := &EndpointParameters{} + + params.Region = bindRegion(options.Region) + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) + params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) + params.Endpoint = options.BaseEndpoint + + if b, ok := input.(endpointParamsBinder); ok { + b.bindEndpointParams(params) + } + + return params +} + +type resolveEndpointV2Middleware struct { + options Options +} + +func (*resolveEndpointV2Middleware) ID() string { + return "ResolveEndpointV2" +} + +func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveEndpoint") + defer span.End() + + if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleFinalize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.options.EndpointResolverV2 == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", + func() (smithyendpoints.Endpoint, error) { + return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) + }) + if err != nil { + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + span.SetProperty("client.call.resolved_endpoint", endpt.URI.String()) + + if endpt.URI.RawPath == "" && req.URL.RawPath != "" { + endpt.URI.RawPath = endpt.URI.Path + } + req.URL.Scheme = endpt.URI.Scheme + req.URL.Host = endpt.URI.Host + req.URL.Path = smithyhttp.JoinPath(endpt.URI.Path, req.URL.Path) + req.URL.RawPath = smithyhttp.JoinPath(endpt.URI.RawPath, req.URL.RawPath) + for k := range endpt.Headers { + req.Header.Set(k, endpt.Headers.Get(k)) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + opts, _ := smithyauth.GetAuthOptions(&endpt.Properties) + for _, o := range opts { + rscheme.SignerProperties.SetAll(&o.SignerProperties) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/generated.json new file mode 100644 index 00000000..1f285e22 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/generated.json @@ -0,0 +1,151 @@ +{ + "dependencies": { + "github.com/aws/aws-sdk-go-v2": "v1.4.0", + "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", + "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", + "github.com/aws/smithy-go": "v1.4.0" + }, + "files": [ + "api_client.go", + "api_client_test.go", + "api_op_AddCustomAttributes.go", + "api_op_AdminAddUserToGroup.go", + "api_op_AdminConfirmSignUp.go", + "api_op_AdminCreateUser.go", + "api_op_AdminDeleteUser.go", + "api_op_AdminDeleteUserAttributes.go", + "api_op_AdminDisableProviderForUser.go", + "api_op_AdminDisableUser.go", + "api_op_AdminEnableUser.go", + "api_op_AdminForgetDevice.go", + "api_op_AdminGetDevice.go", + "api_op_AdminGetUser.go", + "api_op_AdminInitiateAuth.go", + "api_op_AdminLinkProviderForUser.go", + "api_op_AdminListDevices.go", + "api_op_AdminListGroupsForUser.go", + "api_op_AdminListUserAuthEvents.go", + "api_op_AdminRemoveUserFromGroup.go", + "api_op_AdminResetUserPassword.go", + "api_op_AdminRespondToAuthChallenge.go", + "api_op_AdminSetUserMFAPreference.go", + "api_op_AdminSetUserPassword.go", + "api_op_AdminSetUserSettings.go", + "api_op_AdminUpdateAuthEventFeedback.go", + "api_op_AdminUpdateDeviceStatus.go", + "api_op_AdminUpdateUserAttributes.go", + "api_op_AdminUserGlobalSignOut.go", + "api_op_AssociateSoftwareToken.go", + "api_op_ChangePassword.go", + "api_op_CompleteWebAuthnRegistration.go", + "api_op_ConfirmDevice.go", + "api_op_ConfirmForgotPassword.go", + "api_op_ConfirmSignUp.go", + "api_op_CreateGroup.go", + "api_op_CreateIdentityProvider.go", + "api_op_CreateManagedLoginBranding.go", + "api_op_CreateResourceServer.go", + "api_op_CreateUserImportJob.go", + "api_op_CreateUserPool.go", + "api_op_CreateUserPoolClient.go", + "api_op_CreateUserPoolDomain.go", + "api_op_DeleteGroup.go", + "api_op_DeleteIdentityProvider.go", + "api_op_DeleteManagedLoginBranding.go", + "api_op_DeleteResourceServer.go", + "api_op_DeleteUser.go", + "api_op_DeleteUserAttributes.go", + "api_op_DeleteUserPool.go", + "api_op_DeleteUserPoolClient.go", + "api_op_DeleteUserPoolDomain.go", + "api_op_DeleteWebAuthnCredential.go", + "api_op_DescribeIdentityProvider.go", + "api_op_DescribeManagedLoginBranding.go", + "api_op_DescribeManagedLoginBrandingByClient.go", + "api_op_DescribeResourceServer.go", + "api_op_DescribeRiskConfiguration.go", + "api_op_DescribeUserImportJob.go", + "api_op_DescribeUserPool.go", + "api_op_DescribeUserPoolClient.go", + "api_op_DescribeUserPoolDomain.go", + "api_op_ForgetDevice.go", + "api_op_ForgotPassword.go", + "api_op_GetCSVHeader.go", + "api_op_GetDevice.go", + "api_op_GetGroup.go", + "api_op_GetIdentityProviderByIdentifier.go", + "api_op_GetLogDeliveryConfiguration.go", + "api_op_GetSigningCertificate.go", + "api_op_GetTokensFromRefreshToken.go", + "api_op_GetUICustomization.go", + "api_op_GetUser.go", + "api_op_GetUserAttributeVerificationCode.go", + "api_op_GetUserAuthFactors.go", + "api_op_GetUserPoolMfaConfig.go", + "api_op_GlobalSignOut.go", + "api_op_InitiateAuth.go", + "api_op_ListDevices.go", + "api_op_ListGroups.go", + "api_op_ListIdentityProviders.go", + "api_op_ListResourceServers.go", + "api_op_ListTagsForResource.go", + "api_op_ListUserImportJobs.go", + "api_op_ListUserPoolClients.go", + "api_op_ListUserPools.go", + "api_op_ListUsers.go", + "api_op_ListUsersInGroup.go", + "api_op_ListWebAuthnCredentials.go", + "api_op_ResendConfirmationCode.go", + "api_op_RespondToAuthChallenge.go", + "api_op_RevokeToken.go", + "api_op_SetLogDeliveryConfiguration.go", + "api_op_SetRiskConfiguration.go", + "api_op_SetUICustomization.go", + "api_op_SetUserMFAPreference.go", + "api_op_SetUserPoolMfaConfig.go", + "api_op_SetUserSettings.go", + "api_op_SignUp.go", + "api_op_StartUserImportJob.go", + "api_op_StartWebAuthnRegistration.go", + "api_op_StopUserImportJob.go", + "api_op_TagResource.go", + "api_op_UntagResource.go", + "api_op_UpdateAuthEventFeedback.go", + "api_op_UpdateDeviceStatus.go", + "api_op_UpdateGroup.go", + "api_op_UpdateIdentityProvider.go", + "api_op_UpdateManagedLoginBranding.go", + "api_op_UpdateResourceServer.go", + "api_op_UpdateUserAttributes.go", + "api_op_UpdateUserPool.go", + "api_op_UpdateUserPoolClient.go", + "api_op_UpdateUserPoolDomain.go", + "api_op_VerifySoftwareToken.go", + "api_op_VerifyUserAttribute.go", + "auth.go", + "deserializers.go", + "doc.go", + "document/doc.go", + "document/document.go", + "endpoints.go", + "endpoints_config_test.go", + "endpoints_test.go", + "generated.json", + "internal/document/document.go", + "internal/document/document_test.go", + "internal/endpoints/endpoints.go", + "internal/endpoints/endpoints_test.go", + "options.go", + "protocol_test.go", + "serializers.go", + "snapshot_test.go", + "sra_operation_order_test.go", + "types/enums.go", + "types/errors.go", + "types/types.go", + "validators.go" + ], + "go": "1.22", + "module": "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider", + "unstable": false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/go_module_metadata.go new file mode 100644 index 00000000..bf199c77 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/go_module_metadata.go @@ -0,0 +1,6 @@ +// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. + +package cognitoidentityprovider + +// goModuleVersion is the tagged release for this module +const goModuleVersion = "1.53.0" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document/document.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document/document.go new file mode 100644 index 00000000..f89044b4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document/document.go @@ -0,0 +1,99 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package document + +import ( + "bytes" + "encoding/json" + smithydocument "github.com/aws/smithy-go/document" + smithydocumentjson "github.com/aws/smithy-go/document/json" +) + +// github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document.smithyDocument +// is an interface which is used to bind a document type to its service client. +type smithyDocument interface { + isSmithyDocument() +} + +// github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document.Interface +// is a JSON-like data model type that is protocol agnostic and is usedto send +// open-content to a service. +type Interface interface { + smithyDocument + smithydocument.Marshaler + smithydocument.Unmarshaler +} + +type documentMarshaler struct { + value interface{} +} + +func (m *documentMarshaler) UnmarshalSmithyDocument(v interface{}) error { + mBytes, err := m.MarshalSmithyDocument() + if err != nil { + return err + } + + jDecoder := json.NewDecoder(bytes.NewReader(mBytes)) + jDecoder.UseNumber() + + var jv interface{} + if err := jDecoder.Decode(&v); err != nil { + return err + } + + return NewDocumentUnmarshaler(v).UnmarshalSmithyDocument(&jv) +} + +func (m *documentMarshaler) MarshalSmithyDocument() ([]byte, error) { + return smithydocumentjson.NewEncoder().Encode(m.value) +} + +func (m *documentMarshaler) isSmithyDocument() {} + +var _ Interface = (*documentMarshaler)(nil) + +type documentUnmarshaler struct { + value interface{} +} + +func (m *documentUnmarshaler) UnmarshalSmithyDocument(v interface{}) error { + decoder := smithydocumentjson.NewDecoder() + return decoder.DecodeJSONInterface(m.value, v) +} + +func (m *documentUnmarshaler) MarshalSmithyDocument() ([]byte, error) { + return json.Marshal(m.value) +} + +func (m *documentUnmarshaler) isSmithyDocument() {} + +var _ Interface = (*documentUnmarshaler)(nil) + +// NewDocumentMarshaler creates a new document marshaler for the given input type +func NewDocumentMarshaler(v interface{}) Interface { + return &documentMarshaler{ + value: v, + } +} + +// NewDocumentUnmarshaler creates a new document unmarshaler for the given service +// response +func NewDocumentUnmarshaler(v interface{}) Interface { + return &documentUnmarshaler{ + value: v, + } +} + +// github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document.IsInterface +// returns whether the given Interface implementation is a valid client +// implementation +func IsInterface(v Interface) (ok bool) { + defer func() { + if err := recover(); err != nil { + ok = false + } + }() + v.isSmithyDocument() + return true +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/endpoints/endpoints.go new file mode 100644 index 00000000..b0e1d8e5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/endpoints/endpoints.go @@ -0,0 +1,716 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package endpoints + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" + "github.com/aws/smithy-go/logging" + "regexp" +) + +// Options is the endpoint resolver configuration options +type Options struct { + // Logger is a logging implementation that log events should be sent to. + Logger logging.Logger + + // LogDeprecated indicates that deprecated endpoints should be logged to the + // provided logger. + LogDeprecated bool + + // ResolvedRegion is used to override the region to be resolved, rather then the + // using the value passed to the ResolveEndpoint method. This value is used by the + // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative + // name. You must not set this value directly in your application. + ResolvedRegion string + + // DisableHTTPS informs the resolver to return an endpoint that does not use the + // HTTPS scheme. + DisableHTTPS bool + + // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. + UseDualStackEndpoint aws.DualStackEndpointState + + // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. + UseFIPSEndpoint aws.FIPSEndpointState +} + +func (o Options) GetResolvedRegion() string { + return o.ResolvedRegion +} + +func (o Options) GetDisableHTTPS() bool { + return o.DisableHTTPS +} + +func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { + return o.UseDualStackEndpoint +} + +func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { + return o.UseFIPSEndpoint +} + +func transformToSharedOptions(options Options) endpoints.Options { + return endpoints.Options{ + Logger: options.Logger, + LogDeprecated: options.LogDeprecated, + ResolvedRegion: options.ResolvedRegion, + DisableHTTPS: options.DisableHTTPS, + UseDualStackEndpoint: options.UseDualStackEndpoint, + UseFIPSEndpoint: options.UseFIPSEndpoint, + } +} + +// Resolver Cognito Identity Provider endpoint resolver +type Resolver struct { + partitions endpoints.Partitions +} + +// ResolveEndpoint resolves the service endpoint for the given region and options +func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { + if len(region) == 0 { + return endpoint, &aws.MissingRegionError{} + } + + opt := transformToSharedOptions(options) + return r.partitions.ResolveEndpoint(region, opt) +} + +// New returns a new Resolver +func New() *Resolver { + return &Resolver{ + partitions: defaultPartitions, + } +} + +var partitionRegexp = struct { + Aws *regexp.Regexp + AwsCn *regexp.Regexp + AwsEusc *regexp.Regexp + AwsIso *regexp.Regexp + AwsIsoB *regexp.Regexp + AwsIsoE *regexp.Regexp + AwsIsoF *regexp.Regexp + AwsUsGov *regexp.Regexp +}{ + + Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$"), + AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), + AwsEusc: regexp.MustCompile("^eusc\\-(de)\\-\\w+\\-\\d+$"), + AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), + AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), + AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), + AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), + AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), +} + +var defaultPartitions = endpoints.Partitions{ + { + ID: "aws", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.Aws, + IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "af-south-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "af-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.af-south-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-northeast-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-northeast-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-northeast-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-northeast-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-northeast-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-northeast-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-northeast-3", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-northeast-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-northeast-3.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-south-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-south-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-south-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-south-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-south-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-southeast-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-southeast-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-3", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-southeast-3.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-4", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-4", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-southeast-4.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ap-southeast-5", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ap-southeast-5", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ap-southeast-5.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ca-central-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ca-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ca-central-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "ca-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "ca-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.ca-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-central-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-central-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-central-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-central-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-central-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-north-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-north-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-north-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-south-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-south-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-south-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-south-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-south-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-west-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-west-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-west-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "eu-west-3", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "eu-west-3", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.eu-west-3.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "fips-us-east-1", + }: endpoints.Endpoint{ + Hostname: "cognito-idp-fips.us-east-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-east-2", + }: endpoints.Endpoint{ + Hostname: "cognito-idp-fips.us-east-2.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-east-2", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-west-1", + }: endpoints.Endpoint{ + Hostname: "cognito-idp-fips.us-west-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "fips-us-west-2", + }: endpoints.Endpoint{ + Hostname: "cognito-idp-fips.us-west-2.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-west-2", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "il-central-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "il-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.il-central-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "me-central-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "me-central-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.me-central-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "me-south-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "me-south-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.me-south-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "sa-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "sa-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.sa-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.us-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.us-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.us-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.us-east-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.us-east-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-east-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.us-east-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.us-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.us-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.us-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-2", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.us-west-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.us-west-2.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-west-2", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.us-west-2.amazonaws.com", + }, + }, + }, + { + ID: "aws-cn", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.{region}.api.amazonwebservices.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.amazonaws.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.{region}.api.amazonwebservices.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.amazonaws.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsCn, + IsRegionalized: true, + }, + { + ID: "aws-eusc", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.amazonaws.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.amazonaws.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsEusc, + IsRegionalized: true, + }, + { + ID: "aws-iso", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.c2s.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.c2s.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIso, + IsRegionalized: true, + }, + { + ID: "aws-iso-b", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.sc2s.sgov.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.sc2s.sgov.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoB, + IsRegionalized: true, + }, + { + ID: "aws-iso-e", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoE, + IsRegionalized: true, + }, + { + ID: "aws-iso-f", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoF, + IsRegionalized: true, + }, + { + ID: "aws-us-gov", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "cognito-idp.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsUsGov, + IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "fips-us-gov-west-1", + }: endpoints.Endpoint{ + Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", + CredentialScope: endpoints.CredentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: aws.TrueTernary, + }, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-gov-east-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.us-gov-east-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.FIPSVariant, + }: { + Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", + }, + endpoints.EndpointKey{ + Region: "us-gov-west-1", + Variant: endpoints.DualStackVariant, + }: { + Hostname: "cognito-idp.us-gov-west-1.amazonaws.com", + }, + }, + }, +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/options.go new file mode 100644 index 00000000..d107aa78 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/options.go @@ -0,0 +1,232 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" +) + +type HTTPClient interface { + Do(*http.Request) (*http.Response, error) +} + +type Options struct { + // Set of options to modify how an operation is invoked. These apply to all + // operations invoked for this client. Use functional options on operation call to + // modify this list for per operation behavior. + APIOptions []func(*middleware.Stack) error + + // The optional application specific identifier appended to the User-Agent header. + AppID string + + // This endpoint will be given as input to an EndpointResolverV2. It is used for + // providing a custom base endpoint that is subject to modifications by the + // processing EndpointResolverV2. + BaseEndpoint *string + + // Configures the events that will be sent to the configured logger. + ClientLogMode aws.ClientLogMode + + // The credentials object to use when signing requests. + Credentials aws.CredentialsProvider + + // The configuration DefaultsMode that the SDK should use when constructing the + // clients initial default settings. + DefaultsMode aws.DefaultsMode + + // The endpoint options to be used when attempting to resolve an endpoint. + EndpointOptions EndpointResolverOptions + + // The service endpoint resolver. + // + // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a + // value for this field will likely prevent you from using any endpoint-related + // service features released after the introduction of EndpointResolverV2 and + // BaseEndpoint. + // + // To migrate an EndpointResolver implementation that uses a custom endpoint, set + // the client option BaseEndpoint instead. + EndpointResolver EndpointResolver + + // Resolves the endpoint used for a particular service operation. This should be + // used over the deprecated EndpointResolver. + EndpointResolverV2 EndpointResolverV2 + + // Signature Version 4 (SigV4) Signer + HTTPSignerV4 HTTPSignerV4 + + // The logger writer interface to write logging messages to. + Logger logging.Logger + + // The client meter provider. + MeterProvider metrics.MeterProvider + + // The region to send requests to. (Required) + Region string + + // RetryMaxAttempts specifies the maximum number attempts an API client will call + // an operation that fails with a retryable error. A value of 0 is ignored, and + // will not be used to configure the API client created default retryer, or modify + // per operation call's retry max attempts. + // + // If specified in an operation call's functional options with a value that is + // different than the constructed client's Options, the Client's Retryer will be + // wrapped to use the operation's specific RetryMaxAttempts value. + RetryMaxAttempts int + + // RetryMode specifies the retry mode the API client will be created with, if + // Retryer option is not also specified. + // + // When creating a new API Clients this member will only be used if the Retryer + // Options member is nil. This value will be ignored if Retryer is not nil. + // + // Currently does not support per operation call overrides, may in the future. + RetryMode aws.RetryMode + + // Retryer guides how HTTP requests should be retried in case of recoverable + // failures. When nil the API client will use a default retryer. The kind of + // default retry created by the API client can be changed with the RetryMode + // option. + Retryer aws.Retryer + + // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set + // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You + // should not populate this structure programmatically, or rely on the values here + // within your applications. + RuntimeEnvironment aws.RuntimeEnvironment + + // The client tracer provider. + TracerProvider tracing.TracerProvider + + // The initial DefaultsMode used when the client options were constructed. If the + // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved + // value was at that point in time. + // + // Currently does not support per operation call overrides, may in the future. + resolvedDefaultsMode aws.DefaultsMode + + // The HTTP client to invoke API calls with. Defaults to client's default HTTP + // implementation if nil. + HTTPClient HTTPClient + + // The auth scheme resolver which determines how to authenticate for each + // operation. + AuthSchemeResolver AuthSchemeResolver + + // The list of auth schemes supported by the client. + AuthSchemes []smithyhttp.AuthScheme +} + +// Copy creates a clone where the APIOptions list is deep copied. +func (o Options) Copy() Options { + to := o + to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) + copy(to.APIOptions, o.APIOptions) + + return to +} + +func (o Options) GetIdentityResolver(schemeID string) smithyauth.IdentityResolver { + if schemeID == "aws.auth#sigv4" { + return getSigV4IdentityResolver(o) + } + if schemeID == "smithy.api#noAuth" { + return &smithyauth.AnonymousIdentityResolver{} + } + return nil +} + +// WithAPIOptions returns a functional option for setting the Client's APIOptions +// option. +func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { + return func(o *Options) { + o.APIOptions = append(o.APIOptions, optFns...) + } +} + +// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for +// this field will likely prevent you from using any endpoint-related service +// features released after the introduction of EndpointResolverV2 and BaseEndpoint. +// +// To migrate an EndpointResolver implementation that uses a custom endpoint, set +// the client option BaseEndpoint instead. +func WithEndpointResolver(v EndpointResolver) func(*Options) { + return func(o *Options) { + o.EndpointResolver = v + } +} + +// WithEndpointResolverV2 returns a functional option for setting the Client's +// EndpointResolverV2 option. +func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { + return func(o *Options) { + o.EndpointResolverV2 = v + } +} + +func getSigV4IdentityResolver(o Options) smithyauth.IdentityResolver { + if o.Credentials != nil { + return &internalauthsmithy.CredentialsProviderAdapter{Provider: o.Credentials} + } + return nil +} + +// WithSigV4SigningName applies an override to the authentication workflow to +// use the given signing name for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing name from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningName(name string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningName(ctx, name), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningName", fn), + middleware.Before, + ) + }) + } +} + +// WithSigV4SigningRegion applies an override to the authentication workflow to +// use the given signing region for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing region from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningRegion(region string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningRegion(ctx, region), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningRegion", fn), + middleware.Before, + ) + }) + } +} + +func ignoreAnonymousAuth(options *Options) { + if aws.IsCredentialsProvider(options.Credentials, (*aws.AnonymousCredentials)(nil)) { + options.Credentials = nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/serializers.go new file mode 100644 index 00000000..51737515 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/serializers.go @@ -0,0 +1,11903 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "bytes" + "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + internaldocument "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + smithy "github.com/aws/smithy-go" + "github.com/aws/smithy-go/encoding/httpbinding" + smithyjson "github.com/aws/smithy-go/encoding/json" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "path" +) + +type awsAwsjson11_serializeOpAddCustomAttributes struct { +} + +func (*awsAwsjson11_serializeOpAddCustomAttributes) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAddCustomAttributes) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AddCustomAttributesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AddCustomAttributes") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAddCustomAttributesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminAddUserToGroup struct { +} + +func (*awsAwsjson11_serializeOpAdminAddUserToGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminAddUserToGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminAddUserToGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminAddUserToGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminAddUserToGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminConfirmSignUp struct { +} + +func (*awsAwsjson11_serializeOpAdminConfirmSignUp) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminConfirmSignUp) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminConfirmSignUpInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminConfirmSignUp") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminConfirmSignUpInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminCreateUser struct { +} + +func (*awsAwsjson11_serializeOpAdminCreateUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminCreateUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminCreateUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminCreateUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminCreateUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminDeleteUser struct { +} + +func (*awsAwsjson11_serializeOpAdminDeleteUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminDeleteUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminDeleteUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminDeleteUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminDeleteUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminDeleteUserAttributes struct { +} + +func (*awsAwsjson11_serializeOpAdminDeleteUserAttributes) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminDeleteUserAttributes) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminDeleteUserAttributesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminDeleteUserAttributes") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminDeleteUserAttributesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminDisableProviderForUser struct { +} + +func (*awsAwsjson11_serializeOpAdminDisableProviderForUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminDisableProviderForUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminDisableProviderForUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminDisableProviderForUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminDisableProviderForUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminDisableUser struct { +} + +func (*awsAwsjson11_serializeOpAdminDisableUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminDisableUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminDisableUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminDisableUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminDisableUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminEnableUser struct { +} + +func (*awsAwsjson11_serializeOpAdminEnableUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminEnableUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminEnableUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminEnableUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminEnableUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminForgetDevice struct { +} + +func (*awsAwsjson11_serializeOpAdminForgetDevice) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminForgetDevice) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminForgetDeviceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminForgetDevice") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminForgetDeviceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminGetDevice struct { +} + +func (*awsAwsjson11_serializeOpAdminGetDevice) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminGetDevice) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminGetDeviceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminGetDevice") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminGetDeviceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminGetUser struct { +} + +func (*awsAwsjson11_serializeOpAdminGetUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminGetUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminGetUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminGetUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminGetUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminInitiateAuth struct { +} + +func (*awsAwsjson11_serializeOpAdminInitiateAuth) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminInitiateAuth) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminInitiateAuthInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminInitiateAuth") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminInitiateAuthInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminLinkProviderForUser struct { +} + +func (*awsAwsjson11_serializeOpAdminLinkProviderForUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminLinkProviderForUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminLinkProviderForUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminLinkProviderForUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminLinkProviderForUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminListDevices struct { +} + +func (*awsAwsjson11_serializeOpAdminListDevices) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminListDevices) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminListDevicesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminListDevices") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminListDevicesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminListGroupsForUser struct { +} + +func (*awsAwsjson11_serializeOpAdminListGroupsForUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminListGroupsForUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminListGroupsForUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminListGroupsForUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminListGroupsForUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminListUserAuthEvents struct { +} + +func (*awsAwsjson11_serializeOpAdminListUserAuthEvents) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminListUserAuthEvents) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminListUserAuthEventsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminListUserAuthEvents") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminListUserAuthEventsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminRemoveUserFromGroup struct { +} + +func (*awsAwsjson11_serializeOpAdminRemoveUserFromGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminRemoveUserFromGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminRemoveUserFromGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminRemoveUserFromGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminRemoveUserFromGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminResetUserPassword struct { +} + +func (*awsAwsjson11_serializeOpAdminResetUserPassword) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminResetUserPassword) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminResetUserPasswordInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminResetUserPassword") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminResetUserPasswordInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminRespondToAuthChallenge struct { +} + +func (*awsAwsjson11_serializeOpAdminRespondToAuthChallenge) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminRespondToAuthChallenge) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminRespondToAuthChallengeInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminRespondToAuthChallenge") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminRespondToAuthChallengeInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminSetUserMFAPreference struct { +} + +func (*awsAwsjson11_serializeOpAdminSetUserMFAPreference) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminSetUserMFAPreference) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminSetUserMFAPreferenceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminSetUserMFAPreference") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminSetUserMFAPreferenceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminSetUserPassword struct { +} + +func (*awsAwsjson11_serializeOpAdminSetUserPassword) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminSetUserPassword) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminSetUserPasswordInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminSetUserPassword") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminSetUserPasswordInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminSetUserSettings struct { +} + +func (*awsAwsjson11_serializeOpAdminSetUserSettings) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminSetUserSettings) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminSetUserSettingsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminSetUserSettings") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminSetUserSettingsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminUpdateAuthEventFeedback struct { +} + +func (*awsAwsjson11_serializeOpAdminUpdateAuthEventFeedback) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminUpdateAuthEventFeedback) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminUpdateAuthEventFeedbackInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminUpdateAuthEventFeedback") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminUpdateAuthEventFeedbackInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminUpdateDeviceStatus struct { +} + +func (*awsAwsjson11_serializeOpAdminUpdateDeviceStatus) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminUpdateDeviceStatus) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminUpdateDeviceStatusInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminUpdateDeviceStatus") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminUpdateDeviceStatusInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminUpdateUserAttributes struct { +} + +func (*awsAwsjson11_serializeOpAdminUpdateUserAttributes) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminUpdateUserAttributes) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminUpdateUserAttributesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminUpdateUserAttributes") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminUpdateUserAttributesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAdminUserGlobalSignOut struct { +} + +func (*awsAwsjson11_serializeOpAdminUserGlobalSignOut) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAdminUserGlobalSignOut) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AdminUserGlobalSignOutInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AdminUserGlobalSignOut") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAdminUserGlobalSignOutInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpAssociateSoftwareToken struct { +} + +func (*awsAwsjson11_serializeOpAssociateSoftwareToken) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpAssociateSoftwareToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*AssociateSoftwareTokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.AssociateSoftwareToken") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentAssociateSoftwareTokenInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpChangePassword struct { +} + +func (*awsAwsjson11_serializeOpChangePassword) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpChangePassword) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ChangePasswordInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ChangePassword") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentChangePasswordInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCompleteWebAuthnRegistration struct { +} + +func (*awsAwsjson11_serializeOpCompleteWebAuthnRegistration) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCompleteWebAuthnRegistration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CompleteWebAuthnRegistrationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CompleteWebAuthnRegistration") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCompleteWebAuthnRegistrationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpConfirmDevice struct { +} + +func (*awsAwsjson11_serializeOpConfirmDevice) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpConfirmDevice) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ConfirmDeviceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ConfirmDevice") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentConfirmDeviceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpConfirmForgotPassword struct { +} + +func (*awsAwsjson11_serializeOpConfirmForgotPassword) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpConfirmForgotPassword) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ConfirmForgotPasswordInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ConfirmForgotPassword") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentConfirmForgotPasswordInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpConfirmSignUp struct { +} + +func (*awsAwsjson11_serializeOpConfirmSignUp) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpConfirmSignUp) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ConfirmSignUpInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ConfirmSignUp") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentConfirmSignUpInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateGroup struct { +} + +func (*awsAwsjson11_serializeOpCreateGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateIdentityProvider struct { +} + +func (*awsAwsjson11_serializeOpCreateIdentityProvider) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateIdentityProvider) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateIdentityProviderInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateIdentityProvider") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateIdentityProviderInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateManagedLoginBranding struct { +} + +func (*awsAwsjson11_serializeOpCreateManagedLoginBranding) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateManagedLoginBranding) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateManagedLoginBrandingInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateManagedLoginBranding") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateManagedLoginBrandingInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateResourceServer struct { +} + +func (*awsAwsjson11_serializeOpCreateResourceServer) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateResourceServer) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateResourceServerInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateResourceServer") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateResourceServerInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateUserImportJob struct { +} + +func (*awsAwsjson11_serializeOpCreateUserImportJob) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateUserImportJob) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateUserImportJobInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateUserImportJob") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateUserImportJobInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateUserPool struct { +} + +func (*awsAwsjson11_serializeOpCreateUserPool) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateUserPool) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateUserPoolInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateUserPool") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateUserPoolInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateUserPoolClient struct { +} + +func (*awsAwsjson11_serializeOpCreateUserPoolClient) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateUserPoolClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateUserPoolClientInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateUserPoolClient") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateUserPoolClientInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpCreateUserPoolDomain struct { +} + +func (*awsAwsjson11_serializeOpCreateUserPoolDomain) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpCreateUserPoolDomain) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateUserPoolDomainInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.CreateUserPoolDomain") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentCreateUserPoolDomainInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteGroup struct { +} + +func (*awsAwsjson11_serializeOpDeleteGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteIdentityProvider struct { +} + +func (*awsAwsjson11_serializeOpDeleteIdentityProvider) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteIdentityProvider) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteIdentityProviderInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteIdentityProvider") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteIdentityProviderInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteManagedLoginBranding struct { +} + +func (*awsAwsjson11_serializeOpDeleteManagedLoginBranding) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteManagedLoginBranding) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteManagedLoginBrandingInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteManagedLoginBranding") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteManagedLoginBrandingInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteResourceServer struct { +} + +func (*awsAwsjson11_serializeOpDeleteResourceServer) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteResourceServer) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteResourceServerInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteResourceServer") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteResourceServerInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteUser struct { +} + +func (*awsAwsjson11_serializeOpDeleteUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteUserAttributes struct { +} + +func (*awsAwsjson11_serializeOpDeleteUserAttributes) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteUserAttributes) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteUserAttributesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteUserAttributes") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteUserAttributesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteUserPool struct { +} + +func (*awsAwsjson11_serializeOpDeleteUserPool) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteUserPool) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteUserPoolInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteUserPool") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteUserPoolInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteUserPoolClient struct { +} + +func (*awsAwsjson11_serializeOpDeleteUserPoolClient) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteUserPoolClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteUserPoolClientInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteUserPoolClient") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteUserPoolClientInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteUserPoolDomain struct { +} + +func (*awsAwsjson11_serializeOpDeleteUserPoolDomain) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteUserPoolDomain) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteUserPoolDomainInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteUserPoolDomain") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteUserPoolDomainInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDeleteWebAuthnCredential struct { +} + +func (*awsAwsjson11_serializeOpDeleteWebAuthnCredential) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDeleteWebAuthnCredential) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DeleteWebAuthnCredentialInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DeleteWebAuthnCredential") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDeleteWebAuthnCredentialInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeIdentityProvider struct { +} + +func (*awsAwsjson11_serializeOpDescribeIdentityProvider) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeIdentityProvider) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeIdentityProviderInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeIdentityProvider") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeIdentityProviderInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeManagedLoginBranding struct { +} + +func (*awsAwsjson11_serializeOpDescribeManagedLoginBranding) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeManagedLoginBranding) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeManagedLoginBrandingInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeManagedLoginBranding") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeManagedLoginBrandingInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeManagedLoginBrandingByClient struct { +} + +func (*awsAwsjson11_serializeOpDescribeManagedLoginBrandingByClient) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeManagedLoginBrandingByClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeManagedLoginBrandingByClientInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeManagedLoginBrandingByClient") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeManagedLoginBrandingByClientInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeResourceServer struct { +} + +func (*awsAwsjson11_serializeOpDescribeResourceServer) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeResourceServer) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeResourceServerInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeResourceServer") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeResourceServerInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeRiskConfiguration struct { +} + +func (*awsAwsjson11_serializeOpDescribeRiskConfiguration) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeRiskConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeRiskConfigurationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeRiskConfiguration") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeRiskConfigurationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeUserImportJob struct { +} + +func (*awsAwsjson11_serializeOpDescribeUserImportJob) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeUserImportJob) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeUserImportJobInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeUserImportJob") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeUserImportJobInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeUserPool struct { +} + +func (*awsAwsjson11_serializeOpDescribeUserPool) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeUserPool) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeUserPoolInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeUserPool") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeUserPoolInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeUserPoolClient struct { +} + +func (*awsAwsjson11_serializeOpDescribeUserPoolClient) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeUserPoolClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeUserPoolClientInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeUserPoolClient") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeUserPoolClientInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpDescribeUserPoolDomain struct { +} + +func (*awsAwsjson11_serializeOpDescribeUserPoolDomain) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpDescribeUserPoolDomain) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*DescribeUserPoolDomainInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.DescribeUserPoolDomain") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentDescribeUserPoolDomainInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpForgetDevice struct { +} + +func (*awsAwsjson11_serializeOpForgetDevice) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpForgetDevice) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ForgetDeviceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ForgetDevice") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentForgetDeviceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpForgotPassword struct { +} + +func (*awsAwsjson11_serializeOpForgotPassword) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpForgotPassword) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ForgotPasswordInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ForgotPassword") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentForgotPasswordInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetCSVHeader struct { +} + +func (*awsAwsjson11_serializeOpGetCSVHeader) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetCSVHeader) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetCSVHeaderInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetCSVHeader") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetCSVHeaderInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetDevice struct { +} + +func (*awsAwsjson11_serializeOpGetDevice) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetDevice) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetDeviceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetDevice") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetDeviceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetGroup struct { +} + +func (*awsAwsjson11_serializeOpGetGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetIdentityProviderByIdentifier struct { +} + +func (*awsAwsjson11_serializeOpGetIdentityProviderByIdentifier) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetIdentityProviderByIdentifier) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetIdentityProviderByIdentifierInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetIdentityProviderByIdentifier") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetIdentityProviderByIdentifierInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetLogDeliveryConfiguration struct { +} + +func (*awsAwsjson11_serializeOpGetLogDeliveryConfiguration) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetLogDeliveryConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetLogDeliveryConfigurationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetLogDeliveryConfiguration") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetLogDeliveryConfigurationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetSigningCertificate struct { +} + +func (*awsAwsjson11_serializeOpGetSigningCertificate) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetSigningCertificate) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetSigningCertificateInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetSigningCertificate") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetSigningCertificateInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetTokensFromRefreshToken struct { +} + +func (*awsAwsjson11_serializeOpGetTokensFromRefreshToken) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetTokensFromRefreshToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetTokensFromRefreshTokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetTokensFromRefreshToken") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetTokensFromRefreshTokenInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetUICustomization struct { +} + +func (*awsAwsjson11_serializeOpGetUICustomization) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetUICustomization) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetUICustomizationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetUICustomization") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetUICustomizationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetUser struct { +} + +func (*awsAwsjson11_serializeOpGetUser) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetUser) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetUserInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetUser") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetUserInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetUserAttributeVerificationCode struct { +} + +func (*awsAwsjson11_serializeOpGetUserAttributeVerificationCode) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetUserAttributeVerificationCode) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetUserAttributeVerificationCodeInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetUserAttributeVerificationCode") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetUserAttributeVerificationCodeInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetUserAuthFactors struct { +} + +func (*awsAwsjson11_serializeOpGetUserAuthFactors) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetUserAuthFactors) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetUserAuthFactorsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetUserAuthFactors") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetUserAuthFactorsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGetUserPoolMfaConfig struct { +} + +func (*awsAwsjson11_serializeOpGetUserPoolMfaConfig) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGetUserPoolMfaConfig) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetUserPoolMfaConfigInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GetUserPoolMfaConfig") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGetUserPoolMfaConfigInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpGlobalSignOut struct { +} + +func (*awsAwsjson11_serializeOpGlobalSignOut) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpGlobalSignOut) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GlobalSignOutInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.GlobalSignOut") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentGlobalSignOutInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpInitiateAuth struct { +} + +func (*awsAwsjson11_serializeOpInitiateAuth) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpInitiateAuth) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*InitiateAuthInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.InitiateAuth") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentInitiateAuthInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListDevices struct { +} + +func (*awsAwsjson11_serializeOpListDevices) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListDevices) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListDevicesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListDevices") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListDevicesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListGroups struct { +} + +func (*awsAwsjson11_serializeOpListGroups) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListGroups) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListGroupsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListGroups") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListGroupsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListIdentityProviders struct { +} + +func (*awsAwsjson11_serializeOpListIdentityProviders) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListIdentityProviders) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListIdentityProvidersInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListIdentityProviders") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListIdentityProvidersInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListResourceServers struct { +} + +func (*awsAwsjson11_serializeOpListResourceServers) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListResourceServers) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListResourceServersInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListResourceServers") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListResourceServersInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListTagsForResource struct { +} + +func (*awsAwsjson11_serializeOpListTagsForResource) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListTagsForResourceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListTagsForResource") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListTagsForResourceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListUserImportJobs struct { +} + +func (*awsAwsjson11_serializeOpListUserImportJobs) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListUserImportJobs) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListUserImportJobsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListUserImportJobs") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListUserImportJobsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListUserPoolClients struct { +} + +func (*awsAwsjson11_serializeOpListUserPoolClients) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListUserPoolClients) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListUserPoolClientsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListUserPoolClients") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListUserPoolClientsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListUserPools struct { +} + +func (*awsAwsjson11_serializeOpListUserPools) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListUserPools) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListUserPoolsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListUserPools") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListUserPoolsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListUsers struct { +} + +func (*awsAwsjson11_serializeOpListUsers) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListUsers) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListUsersInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListUsers") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListUsersInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListUsersInGroup struct { +} + +func (*awsAwsjson11_serializeOpListUsersInGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListUsersInGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListUsersInGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListUsersInGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListUsersInGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpListWebAuthnCredentials struct { +} + +func (*awsAwsjson11_serializeOpListWebAuthnCredentials) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpListWebAuthnCredentials) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ListWebAuthnCredentialsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ListWebAuthnCredentials") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentListWebAuthnCredentialsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpResendConfirmationCode struct { +} + +func (*awsAwsjson11_serializeOpResendConfirmationCode) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpResendConfirmationCode) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*ResendConfirmationCodeInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.ResendConfirmationCode") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentResendConfirmationCodeInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpRespondToAuthChallenge struct { +} + +func (*awsAwsjson11_serializeOpRespondToAuthChallenge) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpRespondToAuthChallenge) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*RespondToAuthChallengeInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.RespondToAuthChallenge") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentRespondToAuthChallengeInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpRevokeToken struct { +} + +func (*awsAwsjson11_serializeOpRevokeToken) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpRevokeToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*RevokeTokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.RevokeToken") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentRevokeTokenInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSetLogDeliveryConfiguration struct { +} + +func (*awsAwsjson11_serializeOpSetLogDeliveryConfiguration) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSetLogDeliveryConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SetLogDeliveryConfigurationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SetLogDeliveryConfiguration") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSetLogDeliveryConfigurationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSetRiskConfiguration struct { +} + +func (*awsAwsjson11_serializeOpSetRiskConfiguration) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSetRiskConfiguration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SetRiskConfigurationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SetRiskConfiguration") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSetRiskConfigurationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSetUICustomization struct { +} + +func (*awsAwsjson11_serializeOpSetUICustomization) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSetUICustomization) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SetUICustomizationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SetUICustomization") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSetUICustomizationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSetUserMFAPreference struct { +} + +func (*awsAwsjson11_serializeOpSetUserMFAPreference) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSetUserMFAPreference) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SetUserMFAPreferenceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SetUserMFAPreference") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSetUserMFAPreferenceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSetUserPoolMfaConfig struct { +} + +func (*awsAwsjson11_serializeOpSetUserPoolMfaConfig) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSetUserPoolMfaConfig) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SetUserPoolMfaConfigInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SetUserPoolMfaConfig") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSetUserPoolMfaConfigInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSetUserSettings struct { +} + +func (*awsAwsjson11_serializeOpSetUserSettings) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSetUserSettings) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SetUserSettingsInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SetUserSettings") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSetUserSettingsInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpSignUp struct { +} + +func (*awsAwsjson11_serializeOpSignUp) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpSignUp) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*SignUpInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.SignUp") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentSignUpInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStartUserImportJob struct { +} + +func (*awsAwsjson11_serializeOpStartUserImportJob) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStartUserImportJob) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StartUserImportJobInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.StartUserImportJob") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStartUserImportJobInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStartWebAuthnRegistration struct { +} + +func (*awsAwsjson11_serializeOpStartWebAuthnRegistration) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStartWebAuthnRegistration) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StartWebAuthnRegistrationInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.StartWebAuthnRegistration") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStartWebAuthnRegistrationInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpStopUserImportJob struct { +} + +func (*awsAwsjson11_serializeOpStopUserImportJob) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpStopUserImportJob) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*StopUserImportJobInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.StopUserImportJob") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentStopUserImportJobInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpTagResource struct { +} + +func (*awsAwsjson11_serializeOpTagResource) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*TagResourceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.TagResource") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentTagResourceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUntagResource struct { +} + +func (*awsAwsjson11_serializeOpUntagResource) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UntagResourceInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UntagResource") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUntagResourceInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateAuthEventFeedback struct { +} + +func (*awsAwsjson11_serializeOpUpdateAuthEventFeedback) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateAuthEventFeedback) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateAuthEventFeedbackInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateAuthEventFeedback") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateAuthEventFeedbackInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateDeviceStatus struct { +} + +func (*awsAwsjson11_serializeOpUpdateDeviceStatus) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateDeviceStatus) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateDeviceStatusInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateDeviceStatus") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateDeviceStatusInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateGroup struct { +} + +func (*awsAwsjson11_serializeOpUpdateGroup) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateGroupInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateGroup") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateGroupInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateIdentityProvider struct { +} + +func (*awsAwsjson11_serializeOpUpdateIdentityProvider) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateIdentityProvider) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateIdentityProviderInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateIdentityProvider") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateIdentityProviderInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateManagedLoginBranding struct { +} + +func (*awsAwsjson11_serializeOpUpdateManagedLoginBranding) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateManagedLoginBranding) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateManagedLoginBrandingInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateManagedLoginBranding") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateManagedLoginBrandingInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateResourceServer struct { +} + +func (*awsAwsjson11_serializeOpUpdateResourceServer) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateResourceServer) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateResourceServerInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateResourceServer") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateResourceServerInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateUserAttributes struct { +} + +func (*awsAwsjson11_serializeOpUpdateUserAttributes) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateUserAttributes) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateUserAttributesInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateUserAttributes") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateUserAttributesInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateUserPool struct { +} + +func (*awsAwsjson11_serializeOpUpdateUserPool) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateUserPool) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateUserPoolInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateUserPool") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateUserPoolInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateUserPoolClient struct { +} + +func (*awsAwsjson11_serializeOpUpdateUserPoolClient) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateUserPoolClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateUserPoolClientInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateUserPoolClient") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateUserPoolClientInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpUpdateUserPoolDomain struct { +} + +func (*awsAwsjson11_serializeOpUpdateUserPoolDomain) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpUpdateUserPoolDomain) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*UpdateUserPoolDomainInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.UpdateUserPoolDomain") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentUpdateUserPoolDomainInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpVerifySoftwareToken struct { +} + +func (*awsAwsjson11_serializeOpVerifySoftwareToken) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpVerifySoftwareToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*VerifySoftwareTokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.VerifySoftwareToken") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentVerifySoftwareTokenInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + +type awsAwsjson11_serializeOpVerifyUserAttribute struct { +} + +func (*awsAwsjson11_serializeOpVerifyUserAttribute) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsjson11_serializeOpVerifyUserAttribute) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*VerifyUserAttributeInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-amz-json-1.1") + httpBindingEncoder.SetHeader("X-Amz-Target").String("AWSCognitoIdentityProviderService.VerifyUserAttribute") + + jsonEncoder := smithyjson.NewEncoder() + if err := awsAwsjson11_serializeOpDocumentVerifyUserAttributeInput(input, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} +func awsAwsjson11_serializeDocumentAccountRecoverySettingType(v *types.AccountRecoverySettingType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.RecoveryMechanisms != nil { + ok := object.Key("RecoveryMechanisms") + if err := awsAwsjson11_serializeDocumentRecoveryMechanismsType(v.RecoveryMechanisms, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentAccountTakeoverActionsType(v *types.AccountTakeoverActionsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.HighAction != nil { + ok := object.Key("HighAction") + if err := awsAwsjson11_serializeDocumentAccountTakeoverActionType(v.HighAction, ok); err != nil { + return err + } + } + + if v.LowAction != nil { + ok := object.Key("LowAction") + if err := awsAwsjson11_serializeDocumentAccountTakeoverActionType(v.LowAction, ok); err != nil { + return err + } + } + + if v.MediumAction != nil { + ok := object.Key("MediumAction") + if err := awsAwsjson11_serializeDocumentAccountTakeoverActionType(v.MediumAction, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentAccountTakeoverActionType(v *types.AccountTakeoverActionType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.EventAction) > 0 { + ok := object.Key("EventAction") + ok.String(string(v.EventAction)) + } + + { + ok := object.Key("Notify") + ok.Boolean(v.Notify) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAccountTakeoverRiskConfigurationType(v *types.AccountTakeoverRiskConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Actions != nil { + ok := object.Key("Actions") + if err := awsAwsjson11_serializeDocumentAccountTakeoverActionsType(v.Actions, ok); err != nil { + return err + } + } + + if v.NotifyConfiguration != nil { + ok := object.Key("NotifyConfiguration") + if err := awsAwsjson11_serializeDocumentNotifyConfigurationType(v.NotifyConfiguration, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentAdminCreateUserConfigType(v *types.AdminCreateUserConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AllowAdminCreateUserOnly { + ok := object.Key("AllowAdminCreateUserOnly") + ok.Boolean(v.AllowAdminCreateUserOnly) + } + + if v.InviteMessageTemplate != nil { + ok := object.Key("InviteMessageTemplate") + if err := awsAwsjson11_serializeDocumentMessageTemplateType(v.InviteMessageTemplate, ok); err != nil { + return err + } + } + + if v.UnusedAccountValidityDays != 0 { + ok := object.Key("UnusedAccountValidityDays") + ok.Integer(v.UnusedAccountValidityDays) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAdvancedSecurityAdditionalFlowsType(v *types.AdvancedSecurityAdditionalFlowsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.CustomAuthMode) > 0 { + ok := object.Key("CustomAuthMode") + ok.String(string(v.CustomAuthMode)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAliasAttributesListType(v []types.AliasAttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentAllowedFirstAuthFactorsListType(v []types.AuthFactorType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentAnalyticsConfigurationType(v *types.AnalyticsConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ApplicationArn != nil { + ok := object.Key("ApplicationArn") + ok.String(*v.ApplicationArn) + } + + if v.ApplicationId != nil { + ok := object.Key("ApplicationId") + ok.String(*v.ApplicationId) + } + + if v.ExternalId != nil { + ok := object.Key("ExternalId") + ok.String(*v.ExternalId) + } + + if v.RoleArn != nil { + ok := object.Key("RoleArn") + ok.String(*v.RoleArn) + } + + if v.UserDataShared { + ok := object.Key("UserDataShared") + ok.Boolean(v.UserDataShared) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAnalyticsMetadataType(v *types.AnalyticsMetadataType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsEndpointId != nil { + ok := object.Key("AnalyticsEndpointId") + ok.String(*v.AnalyticsEndpointId) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAssetListType(v []types.AssetType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentAssetType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentAssetType(v *types.AssetType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Bytes != nil { + ok := object.Key("Bytes") + ok.Base64EncodeBytes(v.Bytes) + } + + if len(v.Category) > 0 { + ok := object.Key("Category") + ok.String(string(v.Category)) + } + + if len(v.ColorMode) > 0 { + ok := object.Key("ColorMode") + ok.String(string(v.ColorMode)) + } + + if len(v.Extension) > 0 { + ok := object.Key("Extension") + ok.String(string(v.Extension)) + } + + if v.ResourceId != nil { + ok := object.Key("ResourceId") + ok.String(*v.ResourceId) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAttributeListType(v []types.AttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentAttributeType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentAttributeMappingType(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeDocumentAttributeNameListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentAttributesRequireVerificationBeforeUpdateType(v []types.VerifiedAttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentAttributeType(v *types.AttributeType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Name != nil { + ok := object.Key("Name") + ok.String(*v.Name) + } + + if v.Value != nil { + ok := object.Key("Value") + ok.String(*v.Value) + } + + return nil +} + +func awsAwsjson11_serializeDocumentAuthParametersType(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeDocumentBlockedIPRangeListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentCallbackURLsListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentChallengeResponsesType(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeDocumentClientMetadataType(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeDocumentClientPermissionListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentCloudWatchLogsConfigurationType(v *types.CloudWatchLogsConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.LogGroupArn != nil { + ok := object.Key("LogGroupArn") + ok.String(*v.LogGroupArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentCompromisedCredentialsActionsType(v *types.CompromisedCredentialsActionsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.EventAction) > 0 { + ok := object.Key("EventAction") + ok.String(string(v.EventAction)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentCompromisedCredentialsRiskConfigurationType(v *types.CompromisedCredentialsRiskConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Actions != nil { + ok := object.Key("Actions") + if err := awsAwsjson11_serializeDocumentCompromisedCredentialsActionsType(v.Actions, ok); err != nil { + return err + } + } + + if v.EventFilter != nil { + ok := object.Key("EventFilter") + if err := awsAwsjson11_serializeDocumentEventFiltersType(v.EventFilter, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentContextDataType(v *types.ContextDataType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EncodedData != nil { + ok := object.Key("EncodedData") + ok.String(*v.EncodedData) + } + + if v.HttpHeaders != nil { + ok := object.Key("HttpHeaders") + if err := awsAwsjson11_serializeDocumentHttpHeaderList(v.HttpHeaders, ok); err != nil { + return err + } + } + + if v.IpAddress != nil { + ok := object.Key("IpAddress") + ok.String(*v.IpAddress) + } + + if v.ServerName != nil { + ok := object.Key("ServerName") + ok.String(*v.ServerName) + } + + if v.ServerPath != nil { + ok := object.Key("ServerPath") + ok.String(*v.ServerPath) + } + + return nil +} + +func awsAwsjson11_serializeDocumentCustomAttributesListType(v []types.SchemaAttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentSchemaAttributeType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentCustomDomainConfigType(v *types.CustomDomainConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CertificateArn != nil { + ok := object.Key("CertificateArn") + ok.String(*v.CertificateArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentCustomEmailLambdaVersionConfigType(v *types.CustomEmailLambdaVersionConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.LambdaArn != nil { + ok := object.Key("LambdaArn") + ok.String(*v.LambdaArn) + } + + if len(v.LambdaVersion) > 0 { + ok := object.Key("LambdaVersion") + ok.String(string(v.LambdaVersion)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentCustomSMSLambdaVersionConfigType(v *types.CustomSMSLambdaVersionConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.LambdaArn != nil { + ok := object.Key("LambdaArn") + ok.String(*v.LambdaArn) + } + + if len(v.LambdaVersion) > 0 { + ok := object.Key("LambdaVersion") + ok.String(string(v.LambdaVersion)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentDeliveryMediumListType(v []types.DeliveryMediumType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentDeviceConfigurationType(v *types.DeviceConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ChallengeRequiredOnNewDevice { + ok := object.Key("ChallengeRequiredOnNewDevice") + ok.Boolean(v.ChallengeRequiredOnNewDevice) + } + + if v.DeviceOnlyRememberedOnUserPrompt { + ok := object.Key("DeviceOnlyRememberedOnUserPrompt") + ok.Boolean(v.DeviceOnlyRememberedOnUserPrompt) + } + + return nil +} + +func awsAwsjson11_serializeDocumentDeviceSecretVerifierConfigType(v *types.DeviceSecretVerifierConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.PasswordVerifier != nil { + ok := object.Key("PasswordVerifier") + ok.String(*v.PasswordVerifier) + } + + if v.Salt != nil { + ok := object.Key("Salt") + ok.String(*v.Salt) + } + + return nil +} + +func awsAwsjson11_serializeDocumentDocument(v document.Interface, value smithyjson.Value) error { + if v == nil { + return nil + } + if !internaldocument.IsInterface(v) { + return fmt.Errorf("%T is not a compatible document type", v) + } + db, err := v.MarshalSmithyDocument() + if err != nil { + return err + } + value.Write(db) + return nil +} + +func awsAwsjson11_serializeDocumentEmailConfigurationType(v *types.EmailConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ConfigurationSet != nil { + ok := object.Key("ConfigurationSet") + ok.String(*v.ConfigurationSet) + } + + if len(v.EmailSendingAccount) > 0 { + ok := object.Key("EmailSendingAccount") + ok.String(string(v.EmailSendingAccount)) + } + + if v.From != nil { + ok := object.Key("From") + ok.String(*v.From) + } + + if v.ReplyToEmailAddress != nil { + ok := object.Key("ReplyToEmailAddress") + ok.String(*v.ReplyToEmailAddress) + } + + if v.SourceArn != nil { + ok := object.Key("SourceArn") + ok.String(*v.SourceArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentEmailMfaConfigType(v *types.EmailMfaConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Message != nil { + ok := object.Key("Message") + ok.String(*v.Message) + } + + if v.Subject != nil { + ok := object.Key("Subject") + ok.String(*v.Subject) + } + + return nil +} + +func awsAwsjson11_serializeDocumentEmailMfaSettingsType(v *types.EmailMfaSettingsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Enabled { + ok := object.Key("Enabled") + ok.Boolean(v.Enabled) + } + + if v.PreferredMfa { + ok := object.Key("PreferredMfa") + ok.Boolean(v.PreferredMfa) + } + + return nil +} + +func awsAwsjson11_serializeDocumentEventFiltersType(v []types.EventFilterType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentExplicitAuthFlowsListType(v []types.ExplicitAuthFlowsType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentFirehoseConfigurationType(v *types.FirehoseConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.StreamArn != nil { + ok := object.Key("StreamArn") + ok.String(*v.StreamArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentHttpHeader(v *types.HttpHeader, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.HeaderName != nil { + ok := object.Key("headerName") + ok.String(*v.HeaderName) + } + + if v.HeaderValue != nil { + ok := object.Key("headerValue") + ok.String(*v.HeaderValue) + } + + return nil +} + +func awsAwsjson11_serializeDocumentHttpHeaderList(v []types.HttpHeader, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentHttpHeader(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentIdpIdentifiersListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentLambdaConfigType(v *types.LambdaConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CreateAuthChallenge != nil { + ok := object.Key("CreateAuthChallenge") + ok.String(*v.CreateAuthChallenge) + } + + if v.CustomEmailSender != nil { + ok := object.Key("CustomEmailSender") + if err := awsAwsjson11_serializeDocumentCustomEmailLambdaVersionConfigType(v.CustomEmailSender, ok); err != nil { + return err + } + } + + if v.CustomMessage != nil { + ok := object.Key("CustomMessage") + ok.String(*v.CustomMessage) + } + + if v.CustomSMSSender != nil { + ok := object.Key("CustomSMSSender") + if err := awsAwsjson11_serializeDocumentCustomSMSLambdaVersionConfigType(v.CustomSMSSender, ok); err != nil { + return err + } + } + + if v.DefineAuthChallenge != nil { + ok := object.Key("DefineAuthChallenge") + ok.String(*v.DefineAuthChallenge) + } + + if v.KMSKeyID != nil { + ok := object.Key("KMSKeyID") + ok.String(*v.KMSKeyID) + } + + if v.PostAuthentication != nil { + ok := object.Key("PostAuthentication") + ok.String(*v.PostAuthentication) + } + + if v.PostConfirmation != nil { + ok := object.Key("PostConfirmation") + ok.String(*v.PostConfirmation) + } + + if v.PreAuthentication != nil { + ok := object.Key("PreAuthentication") + ok.String(*v.PreAuthentication) + } + + if v.PreSignUp != nil { + ok := object.Key("PreSignUp") + ok.String(*v.PreSignUp) + } + + if v.PreTokenGeneration != nil { + ok := object.Key("PreTokenGeneration") + ok.String(*v.PreTokenGeneration) + } + + if v.PreTokenGenerationConfig != nil { + ok := object.Key("PreTokenGenerationConfig") + if err := awsAwsjson11_serializeDocumentPreTokenGenerationVersionConfigType(v.PreTokenGenerationConfig, ok); err != nil { + return err + } + } + + if v.UserMigration != nil { + ok := object.Key("UserMigration") + ok.String(*v.UserMigration) + } + + if v.VerifyAuthChallengeResponse != nil { + ok := object.Key("VerifyAuthChallengeResponse") + ok.String(*v.VerifyAuthChallengeResponse) + } + + return nil +} + +func awsAwsjson11_serializeDocumentLogConfigurationListType(v []types.LogConfigurationType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentLogConfigurationType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentLogConfigurationType(v *types.LogConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CloudWatchLogsConfiguration != nil { + ok := object.Key("CloudWatchLogsConfiguration") + if err := awsAwsjson11_serializeDocumentCloudWatchLogsConfigurationType(v.CloudWatchLogsConfiguration, ok); err != nil { + return err + } + } + + if len(v.EventSource) > 0 { + ok := object.Key("EventSource") + ok.String(string(v.EventSource)) + } + + if v.FirehoseConfiguration != nil { + ok := object.Key("FirehoseConfiguration") + if err := awsAwsjson11_serializeDocumentFirehoseConfigurationType(v.FirehoseConfiguration, ok); err != nil { + return err + } + } + + if len(v.LogLevel) > 0 { + ok := object.Key("LogLevel") + ok.String(string(v.LogLevel)) + } + + if v.S3Configuration != nil { + ok := object.Key("S3Configuration") + if err := awsAwsjson11_serializeDocumentS3ConfigurationType(v.S3Configuration, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentLogoutURLsListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentMessageTemplateType(v *types.MessageTemplateType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EmailMessage != nil { + ok := object.Key("EmailMessage") + ok.String(*v.EmailMessage) + } + + if v.EmailSubject != nil { + ok := object.Key("EmailSubject") + ok.String(*v.EmailSubject) + } + + if v.SMSMessage != nil { + ok := object.Key("SMSMessage") + ok.String(*v.SMSMessage) + } + + return nil +} + +func awsAwsjson11_serializeDocumentMFAOptionListType(v []types.MFAOptionType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentMFAOptionType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentMFAOptionType(v *types.MFAOptionType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AttributeName != nil { + ok := object.Key("AttributeName") + ok.String(*v.AttributeName) + } + + if len(v.DeliveryMedium) > 0 { + ok := object.Key("DeliveryMedium") + ok.String(string(v.DeliveryMedium)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentNotifyConfigurationType(v *types.NotifyConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.BlockEmail != nil { + ok := object.Key("BlockEmail") + if err := awsAwsjson11_serializeDocumentNotifyEmailType(v.BlockEmail, ok); err != nil { + return err + } + } + + if v.From != nil { + ok := object.Key("From") + ok.String(*v.From) + } + + if v.MfaEmail != nil { + ok := object.Key("MfaEmail") + if err := awsAwsjson11_serializeDocumentNotifyEmailType(v.MfaEmail, ok); err != nil { + return err + } + } + + if v.NoActionEmail != nil { + ok := object.Key("NoActionEmail") + if err := awsAwsjson11_serializeDocumentNotifyEmailType(v.NoActionEmail, ok); err != nil { + return err + } + } + + if v.ReplyTo != nil { + ok := object.Key("ReplyTo") + ok.String(*v.ReplyTo) + } + + if v.SourceArn != nil { + ok := object.Key("SourceArn") + ok.String(*v.SourceArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentNotifyEmailType(v *types.NotifyEmailType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.HtmlBody != nil { + ok := object.Key("HtmlBody") + ok.String(*v.HtmlBody) + } + + if v.Subject != nil { + ok := object.Key("Subject") + ok.String(*v.Subject) + } + + if v.TextBody != nil { + ok := object.Key("TextBody") + ok.String(*v.TextBody) + } + + return nil +} + +func awsAwsjson11_serializeDocumentNumberAttributeConstraintsType(v *types.NumberAttributeConstraintsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxValue != nil { + ok := object.Key("MaxValue") + ok.String(*v.MaxValue) + } + + if v.MinValue != nil { + ok := object.Key("MinValue") + ok.String(*v.MinValue) + } + + return nil +} + +func awsAwsjson11_serializeDocumentOAuthFlowsType(v []types.OAuthFlowType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentPasswordPolicyType(v *types.PasswordPolicyType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MinimumLength != nil { + ok := object.Key("MinimumLength") + ok.Integer(*v.MinimumLength) + } + + if v.PasswordHistorySize != nil { + ok := object.Key("PasswordHistorySize") + ok.Integer(*v.PasswordHistorySize) + } + + if v.RequireLowercase { + ok := object.Key("RequireLowercase") + ok.Boolean(v.RequireLowercase) + } + + if v.RequireNumbers { + ok := object.Key("RequireNumbers") + ok.Boolean(v.RequireNumbers) + } + + if v.RequireSymbols { + ok := object.Key("RequireSymbols") + ok.Boolean(v.RequireSymbols) + } + + if v.RequireUppercase { + ok := object.Key("RequireUppercase") + ok.Boolean(v.RequireUppercase) + } + + if v.TemporaryPasswordValidityDays != 0 { + ok := object.Key("TemporaryPasswordValidityDays") + ok.Integer(v.TemporaryPasswordValidityDays) + } + + return nil +} + +func awsAwsjson11_serializeDocumentPreTokenGenerationVersionConfigType(v *types.PreTokenGenerationVersionConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.LambdaArn != nil { + ok := object.Key("LambdaArn") + ok.String(*v.LambdaArn) + } + + if len(v.LambdaVersion) > 0 { + ok := object.Key("LambdaVersion") + ok.String(string(v.LambdaVersion)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentProviderDetailsType(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeDocumentProviderUserIdentifierType(v *types.ProviderUserIdentifierType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ProviderAttributeName != nil { + ok := object.Key("ProviderAttributeName") + ok.String(*v.ProviderAttributeName) + } + + if v.ProviderAttributeValue != nil { + ok := object.Key("ProviderAttributeValue") + ok.String(*v.ProviderAttributeValue) + } + + if v.ProviderName != nil { + ok := object.Key("ProviderName") + ok.String(*v.ProviderName) + } + + return nil +} + +func awsAwsjson11_serializeDocumentRecoveryMechanismsType(v []types.RecoveryOptionType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentRecoveryOptionType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentRecoveryOptionType(v *types.RecoveryOptionType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.Name) > 0 { + ok := object.Key("Name") + ok.String(string(v.Name)) + } + + if v.Priority != nil { + ok := object.Key("Priority") + ok.Integer(*v.Priority) + } + + return nil +} + +func awsAwsjson11_serializeDocumentRefreshTokenRotationType(v *types.RefreshTokenRotationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.Feature) > 0 { + ok := object.Key("Feature") + ok.String(string(v.Feature)) + } + + if v.RetryGracePeriodSeconds != nil { + ok := object.Key("RetryGracePeriodSeconds") + ok.Integer(*v.RetryGracePeriodSeconds) + } + + return nil +} + +func awsAwsjson11_serializeDocumentResourceServerScopeListType(v []types.ResourceServerScopeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentResourceServerScopeType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentResourceServerScopeType(v *types.ResourceServerScopeType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ScopeDescription != nil { + ok := object.Key("ScopeDescription") + ok.String(*v.ScopeDescription) + } + + if v.ScopeName != nil { + ok := object.Key("ScopeName") + ok.String(*v.ScopeName) + } + + return nil +} + +func awsAwsjson11_serializeDocumentRiskExceptionConfigurationType(v *types.RiskExceptionConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.BlockedIPRangeList != nil { + ok := object.Key("BlockedIPRangeList") + if err := awsAwsjson11_serializeDocumentBlockedIPRangeListType(v.BlockedIPRangeList, ok); err != nil { + return err + } + } + + if v.SkippedIPRangeList != nil { + ok := object.Key("SkippedIPRangeList") + if err := awsAwsjson11_serializeDocumentSkippedIPRangeListType(v.SkippedIPRangeList, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentS3ConfigurationType(v *types.S3ConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.BucketArn != nil { + ok := object.Key("BucketArn") + ok.String(*v.BucketArn) + } + + return nil +} + +func awsAwsjson11_serializeDocumentSchemaAttributesListType(v []types.SchemaAttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + if err := awsAwsjson11_serializeDocumentSchemaAttributeType(&v[i], av); err != nil { + return err + } + } + return nil +} + +func awsAwsjson11_serializeDocumentSchemaAttributeType(v *types.SchemaAttributeType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.AttributeDataType) > 0 { + ok := object.Key("AttributeDataType") + ok.String(string(v.AttributeDataType)) + } + + if v.DeveloperOnlyAttribute != nil { + ok := object.Key("DeveloperOnlyAttribute") + ok.Boolean(*v.DeveloperOnlyAttribute) + } + + if v.Mutable != nil { + ok := object.Key("Mutable") + ok.Boolean(*v.Mutable) + } + + if v.Name != nil { + ok := object.Key("Name") + ok.String(*v.Name) + } + + if v.NumberAttributeConstraints != nil { + ok := object.Key("NumberAttributeConstraints") + if err := awsAwsjson11_serializeDocumentNumberAttributeConstraintsType(v.NumberAttributeConstraints, ok); err != nil { + return err + } + } + + if v.Required != nil { + ok := object.Key("Required") + ok.Boolean(*v.Required) + } + + if v.StringAttributeConstraints != nil { + ok := object.Key("StringAttributeConstraints") + if err := awsAwsjson11_serializeDocumentStringAttributeConstraintsType(v.StringAttributeConstraints, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentScopeListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentSearchedAttributeNamesListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentSignInPolicyType(v *types.SignInPolicyType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AllowedFirstAuthFactors != nil { + ok := object.Key("AllowedFirstAuthFactors") + if err := awsAwsjson11_serializeDocumentAllowedFirstAuthFactorsListType(v.AllowedFirstAuthFactors, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentSkippedIPRangeListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentSmsConfigurationType(v *types.SmsConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ExternalId != nil { + ok := object.Key("ExternalId") + ok.String(*v.ExternalId) + } + + if v.SnsCallerArn != nil { + ok := object.Key("SnsCallerArn") + ok.String(*v.SnsCallerArn) + } + + if v.SnsRegion != nil { + ok := object.Key("SnsRegion") + ok.String(*v.SnsRegion) + } + + return nil +} + +func awsAwsjson11_serializeDocumentSmsMfaConfigType(v *types.SmsMfaConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.SmsAuthenticationMessage != nil { + ok := object.Key("SmsAuthenticationMessage") + ok.String(*v.SmsAuthenticationMessage) + } + + if v.SmsConfiguration != nil { + ok := object.Key("SmsConfiguration") + if err := awsAwsjson11_serializeDocumentSmsConfigurationType(v.SmsConfiguration, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentSMSMfaSettingsType(v *types.SMSMfaSettingsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Enabled { + ok := object.Key("Enabled") + ok.Boolean(v.Enabled) + } + + if v.PreferredMfa { + ok := object.Key("PreferredMfa") + ok.Boolean(v.PreferredMfa) + } + + return nil +} + +func awsAwsjson11_serializeDocumentSoftwareTokenMfaConfigType(v *types.SoftwareTokenMfaConfigType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Enabled { + ok := object.Key("Enabled") + ok.Boolean(v.Enabled) + } + + return nil +} + +func awsAwsjson11_serializeDocumentSoftwareTokenMfaSettingsType(v *types.SoftwareTokenMfaSettingsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Enabled { + ok := object.Key("Enabled") + ok.Boolean(v.Enabled) + } + + if v.PreferredMfa { + ok := object.Key("PreferredMfa") + ok.Boolean(v.PreferredMfa) + } + + return nil +} + +func awsAwsjson11_serializeDocumentStringAttributeConstraintsType(v *types.StringAttributeConstraintsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxLength != nil { + ok := object.Key("MaxLength") + ok.String(*v.MaxLength) + } + + if v.MinLength != nil { + ok := object.Key("MinLength") + ok.String(*v.MinLength) + } + + return nil +} + +func awsAwsjson11_serializeDocumentSupportedIdentityProvidersListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentTokenValidityUnitsType(v *types.TokenValidityUnitsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.AccessToken) > 0 { + ok := object.Key("AccessToken") + ok.String(string(v.AccessToken)) + } + + if len(v.IdToken) > 0 { + ok := object.Key("IdToken") + ok.String(string(v.IdToken)) + } + + if len(v.RefreshToken) > 0 { + ok := object.Key("RefreshToken") + ok.String(string(v.RefreshToken)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentUserAttributeUpdateSettingsType(v *types.UserAttributeUpdateSettingsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AttributesRequireVerificationBeforeUpdate != nil { + ok := object.Key("AttributesRequireVerificationBeforeUpdate") + if err := awsAwsjson11_serializeDocumentAttributesRequireVerificationBeforeUpdateType(v.AttributesRequireVerificationBeforeUpdate, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentUserContextDataType(v *types.UserContextDataType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EncodedData != nil { + ok := object.Key("EncodedData") + ok.String(*v.EncodedData) + } + + if v.IpAddress != nil { + ok := object.Key("IpAddress") + ok.String(*v.IpAddress) + } + + return nil +} + +func awsAwsjson11_serializeDocumentUsernameAttributesListType(v []types.UsernameAttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentUsernameConfigurationType(v *types.UsernameConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CaseSensitive != nil { + ok := object.Key("CaseSensitive") + ok.Boolean(*v.CaseSensitive) + } + + return nil +} + +func awsAwsjson11_serializeDocumentUserPoolAddOnsType(v *types.UserPoolAddOnsType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AdvancedSecurityAdditionalFlows != nil { + ok := object.Key("AdvancedSecurityAdditionalFlows") + if err := awsAwsjson11_serializeDocumentAdvancedSecurityAdditionalFlowsType(v.AdvancedSecurityAdditionalFlows, ok); err != nil { + return err + } + } + + if len(v.AdvancedSecurityMode) > 0 { + ok := object.Key("AdvancedSecurityMode") + ok.String(string(v.AdvancedSecurityMode)) + } + + return nil +} + +func awsAwsjson11_serializeDocumentUserPoolPolicyType(v *types.UserPoolPolicyType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.PasswordPolicy != nil { + ok := object.Key("PasswordPolicy") + if err := awsAwsjson11_serializeDocumentPasswordPolicyType(v.PasswordPolicy, ok); err != nil { + return err + } + } + + if v.SignInPolicy != nil { + ok := object.Key("SignInPolicy") + if err := awsAwsjson11_serializeDocumentSignInPolicyType(v.SignInPolicy, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeDocumentUserPoolTagsListType(v []string, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + +func awsAwsjson11_serializeDocumentUserPoolTagsType(v map[string]string, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + for key := range v { + om := object.Key(key) + om.String(v[key]) + } + return nil +} + +func awsAwsjson11_serializeDocumentVerificationMessageTemplateType(v *types.VerificationMessageTemplateType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if len(v.DefaultEmailOption) > 0 { + ok := object.Key("DefaultEmailOption") + ok.String(string(v.DefaultEmailOption)) + } + + if v.EmailMessage != nil { + ok := object.Key("EmailMessage") + ok.String(*v.EmailMessage) + } + + if v.EmailMessageByLink != nil { + ok := object.Key("EmailMessageByLink") + ok.String(*v.EmailMessageByLink) + } + + if v.EmailSubject != nil { + ok := object.Key("EmailSubject") + ok.String(*v.EmailSubject) + } + + if v.EmailSubjectByLink != nil { + ok := object.Key("EmailSubjectByLink") + ok.String(*v.EmailSubjectByLink) + } + + if v.SmsMessage != nil { + ok := object.Key("SmsMessage") + ok.String(*v.SmsMessage) + } + + return nil +} + +func awsAwsjson11_serializeDocumentVerifiedAttributesListType(v []types.VerifiedAttributeType, value smithyjson.Value) error { + array := value.Array() + defer array.Close() + + for i := range v { + av := array.Value() + av.String(string(v[i])) + } + return nil +} + +func awsAwsjson11_serializeDocumentWebAuthnConfigurationType(v *types.WebAuthnConfigurationType, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.RelyingPartyId != nil { + ok := object.Key("RelyingPartyId") + ok.String(*v.RelyingPartyId) + } + + if len(v.UserVerification) > 0 { + ok := object.Key("UserVerification") + ok.String(string(v.UserVerification)) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAddCustomAttributesInput(v *AddCustomAttributesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CustomAttributes != nil { + ok := object.Key("CustomAttributes") + if err := awsAwsjson11_serializeDocumentCustomAttributesListType(v.CustomAttributes, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminAddUserToGroupInput(v *AdminAddUserToGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminConfirmSignUpInput(v *AdminConfirmSignUpInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminCreateUserInput(v *AdminCreateUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.DesiredDeliveryMediums != nil { + ok := object.Key("DesiredDeliveryMediums") + if err := awsAwsjson11_serializeDocumentDeliveryMediumListType(v.DesiredDeliveryMediums, ok); err != nil { + return err + } + } + + if v.ForceAliasCreation { + ok := object.Key("ForceAliasCreation") + ok.Boolean(v.ForceAliasCreation) + } + + if len(v.MessageAction) > 0 { + ok := object.Key("MessageAction") + ok.String(string(v.MessageAction)) + } + + if v.TemporaryPassword != nil { + ok := object.Key("TemporaryPassword") + ok.String(*v.TemporaryPassword) + } + + if v.UserAttributes != nil { + ok := object.Key("UserAttributes") + if err := awsAwsjson11_serializeDocumentAttributeListType(v.UserAttributes, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + if v.ValidationData != nil { + ok := object.Key("ValidationData") + if err := awsAwsjson11_serializeDocumentAttributeListType(v.ValidationData, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminDeleteUserAttributesInput(v *AdminDeleteUserAttributesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserAttributeNames != nil { + ok := object.Key("UserAttributeNames") + if err := awsAwsjson11_serializeDocumentAttributeNameListType(v.UserAttributeNames, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminDeleteUserInput(v *AdminDeleteUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminDisableProviderForUserInput(v *AdminDisableProviderForUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.User != nil { + ok := object.Key("User") + if err := awsAwsjson11_serializeDocumentProviderUserIdentifierType(v.User, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminDisableUserInput(v *AdminDisableUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminEnableUserInput(v *AdminEnableUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminForgetDeviceInput(v *AdminForgetDeviceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminGetDeviceInput(v *AdminGetDeviceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminGetUserInput(v *AdminGetUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminInitiateAuthInput(v *AdminInitiateAuthInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if len(v.AuthFlow) > 0 { + ok := object.Key("AuthFlow") + ok.String(string(v.AuthFlow)) + } + + if v.AuthParameters != nil { + ok := object.Key("AuthParameters") + if err := awsAwsjson11_serializeDocumentAuthParametersType(v.AuthParameters, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.ContextData != nil { + ok := object.Key("ContextData") + if err := awsAwsjson11_serializeDocumentContextDataType(v.ContextData, ok); err != nil { + return err + } + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminLinkProviderForUserInput(v *AdminLinkProviderForUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.DestinationUser != nil { + ok := object.Key("DestinationUser") + if err := awsAwsjson11_serializeDocumentProviderUserIdentifierType(v.DestinationUser, ok); err != nil { + return err + } + } + + if v.SourceUser != nil { + ok := object.Key("SourceUser") + if err := awsAwsjson11_serializeDocumentProviderUserIdentifierType(v.SourceUser, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminListDevicesInput(v *AdminListDevicesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Limit != nil { + ok := object.Key("Limit") + ok.Integer(*v.Limit) + } + + if v.PaginationToken != nil { + ok := object.Key("PaginationToken") + ok.String(*v.PaginationToken) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminListGroupsForUserInput(v *AdminListGroupsForUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Limit != nil { + ok := object.Key("Limit") + ok.Integer(*v.Limit) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminListUserAuthEventsInput(v *AdminListUserAuthEventsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminRemoveUserFromGroupInput(v *AdminRemoveUserFromGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminResetUserPasswordInput(v *AdminResetUserPasswordInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminRespondToAuthChallengeInput(v *AdminRespondToAuthChallengeInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if len(v.ChallengeName) > 0 { + ok := object.Key("ChallengeName") + ok.String(string(v.ChallengeName)) + } + + if v.ChallengeResponses != nil { + ok := object.Key("ChallengeResponses") + if err := awsAwsjson11_serializeDocumentChallengeResponsesType(v.ChallengeResponses, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.ContextData != nil { + ok := object.Key("ContextData") + if err := awsAwsjson11_serializeDocumentContextDataType(v.ContextData, ok); err != nil { + return err + } + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminSetUserMFAPreferenceInput(v *AdminSetUserMFAPreferenceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EmailMfaSettings != nil { + ok := object.Key("EmailMfaSettings") + if err := awsAwsjson11_serializeDocumentEmailMfaSettingsType(v.EmailMfaSettings, ok); err != nil { + return err + } + } + + if v.SMSMfaSettings != nil { + ok := object.Key("SMSMfaSettings") + if err := awsAwsjson11_serializeDocumentSMSMfaSettingsType(v.SMSMfaSettings, ok); err != nil { + return err + } + } + + if v.SoftwareTokenMfaSettings != nil { + ok := object.Key("SoftwareTokenMfaSettings") + if err := awsAwsjson11_serializeDocumentSoftwareTokenMfaSettingsType(v.SoftwareTokenMfaSettings, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminSetUserPasswordInput(v *AdminSetUserPasswordInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Password != nil { + ok := object.Key("Password") + ok.String(*v.Password) + } + + if v.Permanent { + ok := object.Key("Permanent") + ok.Boolean(v.Permanent) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminSetUserSettingsInput(v *AdminSetUserSettingsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MFAOptions != nil { + ok := object.Key("MFAOptions") + if err := awsAwsjson11_serializeDocumentMFAOptionListType(v.MFAOptions, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminUpdateAuthEventFeedbackInput(v *AdminUpdateAuthEventFeedbackInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EventId != nil { + ok := object.Key("EventId") + ok.String(*v.EventId) + } + + if len(v.FeedbackValue) > 0 { + ok := object.Key("FeedbackValue") + ok.String(string(v.FeedbackValue)) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminUpdateDeviceStatusInput(v *AdminUpdateDeviceStatusInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + if len(v.DeviceRememberedStatus) > 0 { + ok := object.Key("DeviceRememberedStatus") + ok.String(string(v.DeviceRememberedStatus)) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminUpdateUserAttributesInput(v *AdminUpdateUserAttributesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.UserAttributes != nil { + ok := object.Key("UserAttributes") + if err := awsAwsjson11_serializeDocumentAttributeListType(v.UserAttributes, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAdminUserGlobalSignOutInput(v *AdminUserGlobalSignOutInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentAssociateSoftwareTokenInput(v *AssociateSoftwareTokenInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentChangePasswordInput(v *ChangePasswordInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.PreviousPassword != nil { + ok := object.Key("PreviousPassword") + ok.String(*v.PreviousPassword) + } + + if v.ProposedPassword != nil { + ok := object.Key("ProposedPassword") + ok.String(*v.ProposedPassword) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCompleteWebAuthnRegistrationInput(v *CompleteWebAuthnRegistrationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.Credential != nil { + ok := object.Key("Credential") + if err := awsAwsjson11_serializeDocumentDocument(v.Credential, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentConfirmDeviceInput(v *ConfirmDeviceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + if v.DeviceName != nil { + ok := object.Key("DeviceName") + ok.String(*v.DeviceName) + } + + if v.DeviceSecretVerifierConfig != nil { + ok := object.Key("DeviceSecretVerifierConfig") + if err := awsAwsjson11_serializeDocumentDeviceSecretVerifierConfigType(v.DeviceSecretVerifierConfig, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentConfirmForgotPasswordInput(v *ConfirmForgotPasswordInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.ConfirmationCode != nil { + ok := object.Key("ConfirmationCode") + ok.String(*v.ConfirmationCode) + } + + if v.Password != nil { + ok := object.Key("Password") + ok.String(*v.Password) + } + + if v.SecretHash != nil { + ok := object.Key("SecretHash") + ok.String(*v.SecretHash) + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentConfirmSignUpInput(v *ConfirmSignUpInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.ConfirmationCode != nil { + ok := object.Key("ConfirmationCode") + ok.String(*v.ConfirmationCode) + } + + if v.ForceAliasCreation { + ok := object.Key("ForceAliasCreation") + ok.Boolean(v.ForceAliasCreation) + } + + if v.SecretHash != nil { + ok := object.Key("SecretHash") + ok.String(*v.SecretHash) + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateGroupInput(v *CreateGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Description != nil { + ok := object.Key("Description") + ok.String(*v.Description) + } + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.Precedence != nil { + ok := object.Key("Precedence") + ok.Integer(*v.Precedence) + } + + if v.RoleArn != nil { + ok := object.Key("RoleArn") + ok.String(*v.RoleArn) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateIdentityProviderInput(v *CreateIdentityProviderInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AttributeMapping != nil { + ok := object.Key("AttributeMapping") + if err := awsAwsjson11_serializeDocumentAttributeMappingType(v.AttributeMapping, ok); err != nil { + return err + } + } + + if v.IdpIdentifiers != nil { + ok := object.Key("IdpIdentifiers") + if err := awsAwsjson11_serializeDocumentIdpIdentifiersListType(v.IdpIdentifiers, ok); err != nil { + return err + } + } + + if v.ProviderDetails != nil { + ok := object.Key("ProviderDetails") + if err := awsAwsjson11_serializeDocumentProviderDetailsType(v.ProviderDetails, ok); err != nil { + return err + } + } + + if v.ProviderName != nil { + ok := object.Key("ProviderName") + ok.String(*v.ProviderName) + } + + if len(v.ProviderType) > 0 { + ok := object.Key("ProviderType") + ok.String(string(v.ProviderType)) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateManagedLoginBrandingInput(v *CreateManagedLoginBrandingInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Assets != nil { + ok := object.Key("Assets") + if err := awsAwsjson11_serializeDocumentAssetListType(v.Assets, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.Settings != nil { + ok := object.Key("Settings") + if err := awsAwsjson11_serializeDocumentDocument(v.Settings, ok); err != nil { + return err + } + } + + if v.UseCognitoProvidedValues { + ok := object.Key("UseCognitoProvidedValues") + ok.Boolean(v.UseCognitoProvidedValues) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateResourceServerInput(v *CreateResourceServerInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Identifier != nil { + ok := object.Key("Identifier") + ok.String(*v.Identifier) + } + + if v.Name != nil { + ok := object.Key("Name") + ok.String(*v.Name) + } + + if v.Scopes != nil { + ok := object.Key("Scopes") + if err := awsAwsjson11_serializeDocumentResourceServerScopeListType(v.Scopes, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateUserImportJobInput(v *CreateUserImportJobInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CloudWatchLogsRoleArn != nil { + ok := object.Key("CloudWatchLogsRoleArn") + ok.String(*v.CloudWatchLogsRoleArn) + } + + if v.JobName != nil { + ok := object.Key("JobName") + ok.String(*v.JobName) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateUserPoolClientInput(v *CreateUserPoolClientInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessTokenValidity != nil { + ok := object.Key("AccessTokenValidity") + ok.Integer(*v.AccessTokenValidity) + } + + if v.AllowedOAuthFlows != nil { + ok := object.Key("AllowedOAuthFlows") + if err := awsAwsjson11_serializeDocumentOAuthFlowsType(v.AllowedOAuthFlows, ok); err != nil { + return err + } + } + + if v.AllowedOAuthFlowsUserPoolClient { + ok := object.Key("AllowedOAuthFlowsUserPoolClient") + ok.Boolean(v.AllowedOAuthFlowsUserPoolClient) + } + + if v.AllowedOAuthScopes != nil { + ok := object.Key("AllowedOAuthScopes") + if err := awsAwsjson11_serializeDocumentScopeListType(v.AllowedOAuthScopes, ok); err != nil { + return err + } + } + + if v.AnalyticsConfiguration != nil { + ok := object.Key("AnalyticsConfiguration") + if err := awsAwsjson11_serializeDocumentAnalyticsConfigurationType(v.AnalyticsConfiguration, ok); err != nil { + return err + } + } + + if v.AuthSessionValidity != nil { + ok := object.Key("AuthSessionValidity") + ok.Integer(*v.AuthSessionValidity) + } + + if v.CallbackURLs != nil { + ok := object.Key("CallbackURLs") + if err := awsAwsjson11_serializeDocumentCallbackURLsListType(v.CallbackURLs, ok); err != nil { + return err + } + } + + if v.ClientName != nil { + ok := object.Key("ClientName") + ok.String(*v.ClientName) + } + + if v.DefaultRedirectURI != nil { + ok := object.Key("DefaultRedirectURI") + ok.String(*v.DefaultRedirectURI) + } + + if v.EnablePropagateAdditionalUserContextData != nil { + ok := object.Key("EnablePropagateAdditionalUserContextData") + ok.Boolean(*v.EnablePropagateAdditionalUserContextData) + } + + if v.EnableTokenRevocation != nil { + ok := object.Key("EnableTokenRevocation") + ok.Boolean(*v.EnableTokenRevocation) + } + + if v.ExplicitAuthFlows != nil { + ok := object.Key("ExplicitAuthFlows") + if err := awsAwsjson11_serializeDocumentExplicitAuthFlowsListType(v.ExplicitAuthFlows, ok); err != nil { + return err + } + } + + if v.GenerateSecret { + ok := object.Key("GenerateSecret") + ok.Boolean(v.GenerateSecret) + } + + if v.IdTokenValidity != nil { + ok := object.Key("IdTokenValidity") + ok.Integer(*v.IdTokenValidity) + } + + if v.LogoutURLs != nil { + ok := object.Key("LogoutURLs") + if err := awsAwsjson11_serializeDocumentLogoutURLsListType(v.LogoutURLs, ok); err != nil { + return err + } + } + + if len(v.PreventUserExistenceErrors) > 0 { + ok := object.Key("PreventUserExistenceErrors") + ok.String(string(v.PreventUserExistenceErrors)) + } + + if v.ReadAttributes != nil { + ok := object.Key("ReadAttributes") + if err := awsAwsjson11_serializeDocumentClientPermissionListType(v.ReadAttributes, ok); err != nil { + return err + } + } + + if v.RefreshTokenRotation != nil { + ok := object.Key("RefreshTokenRotation") + if err := awsAwsjson11_serializeDocumentRefreshTokenRotationType(v.RefreshTokenRotation, ok); err != nil { + return err + } + } + + if v.RefreshTokenValidity != 0 { + ok := object.Key("RefreshTokenValidity") + ok.Integer(v.RefreshTokenValidity) + } + + if v.SupportedIdentityProviders != nil { + ok := object.Key("SupportedIdentityProviders") + if err := awsAwsjson11_serializeDocumentSupportedIdentityProvidersListType(v.SupportedIdentityProviders, ok); err != nil { + return err + } + } + + if v.TokenValidityUnits != nil { + ok := object.Key("TokenValidityUnits") + if err := awsAwsjson11_serializeDocumentTokenValidityUnitsType(v.TokenValidityUnits, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + if v.WriteAttributes != nil { + ok := object.Key("WriteAttributes") + if err := awsAwsjson11_serializeDocumentClientPermissionListType(v.WriteAttributes, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateUserPoolDomainInput(v *CreateUserPoolDomainInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CustomDomainConfig != nil { + ok := object.Key("CustomDomainConfig") + if err := awsAwsjson11_serializeDocumentCustomDomainConfigType(v.CustomDomainConfig, ok); err != nil { + return err + } + } + + if v.Domain != nil { + ok := object.Key("Domain") + ok.String(*v.Domain) + } + + if v.ManagedLoginVersion != nil { + ok := object.Key("ManagedLoginVersion") + ok.Integer(*v.ManagedLoginVersion) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentCreateUserPoolInput(v *CreateUserPoolInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccountRecoverySetting != nil { + ok := object.Key("AccountRecoverySetting") + if err := awsAwsjson11_serializeDocumentAccountRecoverySettingType(v.AccountRecoverySetting, ok); err != nil { + return err + } + } + + if v.AdminCreateUserConfig != nil { + ok := object.Key("AdminCreateUserConfig") + if err := awsAwsjson11_serializeDocumentAdminCreateUserConfigType(v.AdminCreateUserConfig, ok); err != nil { + return err + } + } + + if v.AliasAttributes != nil { + ok := object.Key("AliasAttributes") + if err := awsAwsjson11_serializeDocumentAliasAttributesListType(v.AliasAttributes, ok); err != nil { + return err + } + } + + if v.AutoVerifiedAttributes != nil { + ok := object.Key("AutoVerifiedAttributes") + if err := awsAwsjson11_serializeDocumentVerifiedAttributesListType(v.AutoVerifiedAttributes, ok); err != nil { + return err + } + } + + if len(v.DeletionProtection) > 0 { + ok := object.Key("DeletionProtection") + ok.String(string(v.DeletionProtection)) + } + + if v.DeviceConfiguration != nil { + ok := object.Key("DeviceConfiguration") + if err := awsAwsjson11_serializeDocumentDeviceConfigurationType(v.DeviceConfiguration, ok); err != nil { + return err + } + } + + if v.EmailConfiguration != nil { + ok := object.Key("EmailConfiguration") + if err := awsAwsjson11_serializeDocumentEmailConfigurationType(v.EmailConfiguration, ok); err != nil { + return err + } + } + + if v.EmailVerificationMessage != nil { + ok := object.Key("EmailVerificationMessage") + ok.String(*v.EmailVerificationMessage) + } + + if v.EmailVerificationSubject != nil { + ok := object.Key("EmailVerificationSubject") + ok.String(*v.EmailVerificationSubject) + } + + if v.LambdaConfig != nil { + ok := object.Key("LambdaConfig") + if err := awsAwsjson11_serializeDocumentLambdaConfigType(v.LambdaConfig, ok); err != nil { + return err + } + } + + if len(v.MfaConfiguration) > 0 { + ok := object.Key("MfaConfiguration") + ok.String(string(v.MfaConfiguration)) + } + + if v.Policies != nil { + ok := object.Key("Policies") + if err := awsAwsjson11_serializeDocumentUserPoolPolicyType(v.Policies, ok); err != nil { + return err + } + } + + if v.PoolName != nil { + ok := object.Key("PoolName") + ok.String(*v.PoolName) + } + + if v.Schema != nil { + ok := object.Key("Schema") + if err := awsAwsjson11_serializeDocumentSchemaAttributesListType(v.Schema, ok); err != nil { + return err + } + } + + if v.SmsAuthenticationMessage != nil { + ok := object.Key("SmsAuthenticationMessage") + ok.String(*v.SmsAuthenticationMessage) + } + + if v.SmsConfiguration != nil { + ok := object.Key("SmsConfiguration") + if err := awsAwsjson11_serializeDocumentSmsConfigurationType(v.SmsConfiguration, ok); err != nil { + return err + } + } + + if v.SmsVerificationMessage != nil { + ok := object.Key("SmsVerificationMessage") + ok.String(*v.SmsVerificationMessage) + } + + if v.UserAttributeUpdateSettings != nil { + ok := object.Key("UserAttributeUpdateSettings") + if err := awsAwsjson11_serializeDocumentUserAttributeUpdateSettingsType(v.UserAttributeUpdateSettings, ok); err != nil { + return err + } + } + + if v.UsernameAttributes != nil { + ok := object.Key("UsernameAttributes") + if err := awsAwsjson11_serializeDocumentUsernameAttributesListType(v.UsernameAttributes, ok); err != nil { + return err + } + } + + if v.UsernameConfiguration != nil { + ok := object.Key("UsernameConfiguration") + if err := awsAwsjson11_serializeDocumentUsernameConfigurationType(v.UsernameConfiguration, ok); err != nil { + return err + } + } + + if v.UserPoolAddOns != nil { + ok := object.Key("UserPoolAddOns") + if err := awsAwsjson11_serializeDocumentUserPoolAddOnsType(v.UserPoolAddOns, ok); err != nil { + return err + } + } + + if v.UserPoolTags != nil { + ok := object.Key("UserPoolTags") + if err := awsAwsjson11_serializeDocumentUserPoolTagsType(v.UserPoolTags, ok); err != nil { + return err + } + } + + if len(v.UserPoolTier) > 0 { + ok := object.Key("UserPoolTier") + ok.String(string(v.UserPoolTier)) + } + + if v.VerificationMessageTemplate != nil { + ok := object.Key("VerificationMessageTemplate") + if err := awsAwsjson11_serializeDocumentVerificationMessageTemplateType(v.VerificationMessageTemplate, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteGroupInput(v *DeleteGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteIdentityProviderInput(v *DeleteIdentityProviderInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ProviderName != nil { + ok := object.Key("ProviderName") + ok.String(*v.ProviderName) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteManagedLoginBrandingInput(v *DeleteManagedLoginBrandingInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ManagedLoginBrandingId != nil { + ok := object.Key("ManagedLoginBrandingId") + ok.String(*v.ManagedLoginBrandingId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteResourceServerInput(v *DeleteResourceServerInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Identifier != nil { + ok := object.Key("Identifier") + ok.String(*v.Identifier) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteUserAttributesInput(v *DeleteUserAttributesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.UserAttributeNames != nil { + ok := object.Key("UserAttributeNames") + if err := awsAwsjson11_serializeDocumentAttributeNameListType(v.UserAttributeNames, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteUserInput(v *DeleteUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteUserPoolClientInput(v *DeleteUserPoolClientInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteUserPoolDomainInput(v *DeleteUserPoolDomainInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Domain != nil { + ok := object.Key("Domain") + ok.String(*v.Domain) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteUserPoolInput(v *DeleteUserPoolInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDeleteWebAuthnCredentialInput(v *DeleteWebAuthnCredentialInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.CredentialId != nil { + ok := object.Key("CredentialId") + ok.String(*v.CredentialId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeIdentityProviderInput(v *DescribeIdentityProviderInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ProviderName != nil { + ok := object.Key("ProviderName") + ok.String(*v.ProviderName) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeManagedLoginBrandingByClientInput(v *DescribeManagedLoginBrandingByClientInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ReturnMergedResources { + ok := object.Key("ReturnMergedResources") + ok.Boolean(v.ReturnMergedResources) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeManagedLoginBrandingInput(v *DescribeManagedLoginBrandingInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ManagedLoginBrandingId != nil { + ok := object.Key("ManagedLoginBrandingId") + ok.String(*v.ManagedLoginBrandingId) + } + + if v.ReturnMergedResources { + ok := object.Key("ReturnMergedResources") + ok.Boolean(v.ReturnMergedResources) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeResourceServerInput(v *DescribeResourceServerInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Identifier != nil { + ok := object.Key("Identifier") + ok.String(*v.Identifier) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeRiskConfigurationInput(v *DescribeRiskConfigurationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeUserImportJobInput(v *DescribeUserImportJobInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeUserPoolClientInput(v *DescribeUserPoolClientInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeUserPoolDomainInput(v *DescribeUserPoolDomainInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Domain != nil { + ok := object.Key("Domain") + ok.String(*v.Domain) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentDescribeUserPoolInput(v *DescribeUserPoolInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentForgetDeviceInput(v *ForgetDeviceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentForgotPasswordInput(v *ForgotPasswordInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.SecretHash != nil { + ok := object.Key("SecretHash") + ok.String(*v.SecretHash) + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetCSVHeaderInput(v *GetCSVHeaderInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetDeviceInput(v *GetDeviceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetGroupInput(v *GetGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetIdentityProviderByIdentifierInput(v *GetIdentityProviderByIdentifierInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.IdpIdentifier != nil { + ok := object.Key("IdpIdentifier") + ok.String(*v.IdpIdentifier) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetLogDeliveryConfigurationInput(v *GetLogDeliveryConfigurationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetSigningCertificateInput(v *GetSigningCertificateInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetTokensFromRefreshTokenInput(v *GetTokensFromRefreshTokenInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.ClientSecret != nil { + ok := object.Key("ClientSecret") + ok.String(*v.ClientSecret) + } + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + if v.RefreshToken != nil { + ok := object.Key("RefreshToken") + ok.String(*v.RefreshToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetUICustomizationInput(v *GetUICustomizationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetUserAttributeVerificationCodeInput(v *GetUserAttributeVerificationCodeInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.AttributeName != nil { + ok := object.Key("AttributeName") + ok.String(*v.AttributeName) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetUserAuthFactorsInput(v *GetUserAuthFactorsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetUserInput(v *GetUserInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGetUserPoolMfaConfigInput(v *GetUserPoolMfaConfigInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentGlobalSignOutInput(v *GlobalSignOutInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentInitiateAuthInput(v *InitiateAuthInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if len(v.AuthFlow) > 0 { + ok := object.Key("AuthFlow") + ok.String(string(v.AuthFlow)) + } + + if v.AuthParameters != nil { + ok := object.Key("AuthParameters") + if err := awsAwsjson11_serializeDocumentAuthParametersType(v.AuthParameters, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListDevicesInput(v *ListDevicesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.Limit != nil { + ok := object.Key("Limit") + ok.Integer(*v.Limit) + } + + if v.PaginationToken != nil { + ok := object.Key("PaginationToken") + ok.String(*v.PaginationToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListGroupsInput(v *ListGroupsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Limit != nil { + ok := object.Key("Limit") + ok.Integer(*v.Limit) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListIdentityProvidersInput(v *ListIdentityProvidersInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListResourceServersInput(v *ListResourceServersInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListTagsForResourceInput(v *ListTagsForResourceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ResourceArn != nil { + ok := object.Key("ResourceArn") + ok.String(*v.ResourceArn) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListUserImportJobsInput(v *ListUserImportJobsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.PaginationToken != nil { + ok := object.Key("PaginationToken") + ok.String(*v.PaginationToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListUserPoolClientsInput(v *ListUserPoolClientsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListUserPoolsInput(v *ListUserPoolsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListUsersInGroupInput(v *ListUsersInGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.Limit != nil { + ok := object.Key("Limit") + ok.Integer(*v.Limit) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListUsersInput(v *ListUsersInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AttributesToGet != nil { + ok := object.Key("AttributesToGet") + if err := awsAwsjson11_serializeDocumentSearchedAttributeNamesListType(v.AttributesToGet, ok); err != nil { + return err + } + } + + if v.Filter != nil { + ok := object.Key("Filter") + ok.String(*v.Filter) + } + + if v.Limit != nil { + ok := object.Key("Limit") + ok.Integer(*v.Limit) + } + + if v.PaginationToken != nil { + ok := object.Key("PaginationToken") + ok.String(*v.PaginationToken) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentListWebAuthnCredentialsInput(v *ListWebAuthnCredentialsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.MaxResults != nil { + ok := object.Key("MaxResults") + ok.Integer(*v.MaxResults) + } + + if v.NextToken != nil { + ok := object.Key("NextToken") + ok.String(*v.NextToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentResendConfirmationCodeInput(v *ResendConfirmationCodeInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.SecretHash != nil { + ok := object.Key("SecretHash") + ok.String(*v.SecretHash) + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentRespondToAuthChallengeInput(v *RespondToAuthChallengeInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if len(v.ChallengeName) > 0 { + ok := object.Key("ChallengeName") + ok.String(string(v.ChallengeName)) + } + + if v.ChallengeResponses != nil { + ok := object.Key("ChallengeResponses") + if err := awsAwsjson11_serializeDocumentChallengeResponsesType(v.ChallengeResponses, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentRevokeTokenInput(v *RevokeTokenInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientSecret != nil { + ok := object.Key("ClientSecret") + ok.String(*v.ClientSecret) + } + + if v.Token != nil { + ok := object.Key("Token") + ok.String(*v.Token) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSetLogDeliveryConfigurationInput(v *SetLogDeliveryConfigurationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.LogConfigurations != nil { + ok := object.Key("LogConfigurations") + if err := awsAwsjson11_serializeDocumentLogConfigurationListType(v.LogConfigurations, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSetRiskConfigurationInput(v *SetRiskConfigurationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccountTakeoverRiskConfiguration != nil { + ok := object.Key("AccountTakeoverRiskConfiguration") + if err := awsAwsjson11_serializeDocumentAccountTakeoverRiskConfigurationType(v.AccountTakeoverRiskConfiguration, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.CompromisedCredentialsRiskConfiguration != nil { + ok := object.Key("CompromisedCredentialsRiskConfiguration") + if err := awsAwsjson11_serializeDocumentCompromisedCredentialsRiskConfigurationType(v.CompromisedCredentialsRiskConfiguration, ok); err != nil { + return err + } + } + + if v.RiskExceptionConfiguration != nil { + ok := object.Key("RiskExceptionConfiguration") + if err := awsAwsjson11_serializeDocumentRiskExceptionConfigurationType(v.RiskExceptionConfiguration, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSetUICustomizationInput(v *SetUICustomizationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.CSS != nil { + ok := object.Key("CSS") + ok.String(*v.CSS) + } + + if v.ImageFile != nil { + ok := object.Key("ImageFile") + ok.Base64EncodeBytes(v.ImageFile) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSetUserMFAPreferenceInput(v *SetUserMFAPreferenceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.EmailMfaSettings != nil { + ok := object.Key("EmailMfaSettings") + if err := awsAwsjson11_serializeDocumentEmailMfaSettingsType(v.EmailMfaSettings, ok); err != nil { + return err + } + } + + if v.SMSMfaSettings != nil { + ok := object.Key("SMSMfaSettings") + if err := awsAwsjson11_serializeDocumentSMSMfaSettingsType(v.SMSMfaSettings, ok); err != nil { + return err + } + } + + if v.SoftwareTokenMfaSettings != nil { + ok := object.Key("SoftwareTokenMfaSettings") + if err := awsAwsjson11_serializeDocumentSoftwareTokenMfaSettingsType(v.SoftwareTokenMfaSettings, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSetUserPoolMfaConfigInput(v *SetUserPoolMfaConfigInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EmailMfaConfiguration != nil { + ok := object.Key("EmailMfaConfiguration") + if err := awsAwsjson11_serializeDocumentEmailMfaConfigType(v.EmailMfaConfiguration, ok); err != nil { + return err + } + } + + if len(v.MfaConfiguration) > 0 { + ok := object.Key("MfaConfiguration") + ok.String(string(v.MfaConfiguration)) + } + + if v.SmsMfaConfiguration != nil { + ok := object.Key("SmsMfaConfiguration") + if err := awsAwsjson11_serializeDocumentSmsMfaConfigType(v.SmsMfaConfiguration, ok); err != nil { + return err + } + } + + if v.SoftwareTokenMfaConfiguration != nil { + ok := object.Key("SoftwareTokenMfaConfiguration") + if err := awsAwsjson11_serializeDocumentSoftwareTokenMfaConfigType(v.SoftwareTokenMfaConfiguration, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + if v.WebAuthnConfiguration != nil { + ok := object.Key("WebAuthnConfiguration") + if err := awsAwsjson11_serializeDocumentWebAuthnConfigurationType(v.WebAuthnConfiguration, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSetUserSettingsInput(v *SetUserSettingsInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.MFAOptions != nil { + ok := object.Key("MFAOptions") + if err := awsAwsjson11_serializeDocumentMFAOptionListType(v.MFAOptions, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentSignUpInput(v *SignUpInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AnalyticsMetadata != nil { + ok := object.Key("AnalyticsMetadata") + if err := awsAwsjson11_serializeDocumentAnalyticsMetadataType(v.AnalyticsMetadata, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.Password != nil { + ok := object.Key("Password") + ok.String(*v.Password) + } + + if v.SecretHash != nil { + ok := object.Key("SecretHash") + ok.String(*v.SecretHash) + } + + if v.UserAttributes != nil { + ok := object.Key("UserAttributes") + if err := awsAwsjson11_serializeDocumentAttributeListType(v.UserAttributes, ok); err != nil { + return err + } + } + + if v.UserContextData != nil { + ok := object.Key("UserContextData") + if err := awsAwsjson11_serializeDocumentUserContextDataType(v.UserContextData, ok); err != nil { + return err + } + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.ValidationData != nil { + ok := object.Key("ValidationData") + if err := awsAwsjson11_serializeDocumentAttributeListType(v.ValidationData, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStartUserImportJobInput(v *StartUserImportJobInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStartWebAuthnRegistrationInput(v *StartWebAuthnRegistrationInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentStopUserImportJobInput(v *StopUserImportJobInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.JobId != nil { + ok := object.Key("JobId") + ok.String(*v.JobId) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentTagResourceInput(v *TagResourceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ResourceArn != nil { + ok := object.Key("ResourceArn") + ok.String(*v.ResourceArn) + } + + if v.Tags != nil { + ok := object.Key("Tags") + if err := awsAwsjson11_serializeDocumentUserPoolTagsType(v.Tags, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUntagResourceInput(v *UntagResourceInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ResourceArn != nil { + ok := object.Key("ResourceArn") + ok.String(*v.ResourceArn) + } + + if v.TagKeys != nil { + ok := object.Key("TagKeys") + if err := awsAwsjson11_serializeDocumentUserPoolTagsListType(v.TagKeys, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateAuthEventFeedbackInput(v *UpdateAuthEventFeedbackInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.EventId != nil { + ok := object.Key("EventId") + ok.String(*v.EventId) + } + + if v.FeedbackToken != nil { + ok := object.Key("FeedbackToken") + ok.String(*v.FeedbackToken) + } + + if len(v.FeedbackValue) > 0 { + ok := object.Key("FeedbackValue") + ok.String(string(v.FeedbackValue)) + } + + if v.Username != nil { + ok := object.Key("Username") + ok.String(*v.Username) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateDeviceStatusInput(v *UpdateDeviceStatusInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.DeviceKey != nil { + ok := object.Key("DeviceKey") + ok.String(*v.DeviceKey) + } + + if len(v.DeviceRememberedStatus) > 0 { + ok := object.Key("DeviceRememberedStatus") + ok.String(string(v.DeviceRememberedStatus)) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateGroupInput(v *UpdateGroupInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Description != nil { + ok := object.Key("Description") + ok.String(*v.Description) + } + + if v.GroupName != nil { + ok := object.Key("GroupName") + ok.String(*v.GroupName) + } + + if v.Precedence != nil { + ok := object.Key("Precedence") + ok.Integer(*v.Precedence) + } + + if v.RoleArn != nil { + ok := object.Key("RoleArn") + ok.String(*v.RoleArn) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateIdentityProviderInput(v *UpdateIdentityProviderInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AttributeMapping != nil { + ok := object.Key("AttributeMapping") + if err := awsAwsjson11_serializeDocumentAttributeMappingType(v.AttributeMapping, ok); err != nil { + return err + } + } + + if v.IdpIdentifiers != nil { + ok := object.Key("IdpIdentifiers") + if err := awsAwsjson11_serializeDocumentIdpIdentifiersListType(v.IdpIdentifiers, ok); err != nil { + return err + } + } + + if v.ProviderDetails != nil { + ok := object.Key("ProviderDetails") + if err := awsAwsjson11_serializeDocumentProviderDetailsType(v.ProviderDetails, ok); err != nil { + return err + } + } + + if v.ProviderName != nil { + ok := object.Key("ProviderName") + ok.String(*v.ProviderName) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateManagedLoginBrandingInput(v *UpdateManagedLoginBrandingInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Assets != nil { + ok := object.Key("Assets") + if err := awsAwsjson11_serializeDocumentAssetListType(v.Assets, ok); err != nil { + return err + } + } + + if v.ManagedLoginBrandingId != nil { + ok := object.Key("ManagedLoginBrandingId") + ok.String(*v.ManagedLoginBrandingId) + } + + if v.Settings != nil { + ok := object.Key("Settings") + if err := awsAwsjson11_serializeDocumentDocument(v.Settings, ok); err != nil { + return err + } + } + + if v.UseCognitoProvidedValues { + ok := object.Key("UseCognitoProvidedValues") + ok.Boolean(v.UseCognitoProvidedValues) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateResourceServerInput(v *UpdateResourceServerInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.Identifier != nil { + ok := object.Key("Identifier") + ok.String(*v.Identifier) + } + + if v.Name != nil { + ok := object.Key("Name") + ok.String(*v.Name) + } + + if v.Scopes != nil { + ok := object.Key("Scopes") + if err := awsAwsjson11_serializeDocumentResourceServerScopeListType(v.Scopes, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateUserAttributesInput(v *UpdateUserAttributesInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.ClientMetadata != nil { + ok := object.Key("ClientMetadata") + if err := awsAwsjson11_serializeDocumentClientMetadataType(v.ClientMetadata, ok); err != nil { + return err + } + } + + if v.UserAttributes != nil { + ok := object.Key("UserAttributes") + if err := awsAwsjson11_serializeDocumentAttributeListType(v.UserAttributes, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateUserPoolClientInput(v *UpdateUserPoolClientInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessTokenValidity != nil { + ok := object.Key("AccessTokenValidity") + ok.Integer(*v.AccessTokenValidity) + } + + if v.AllowedOAuthFlows != nil { + ok := object.Key("AllowedOAuthFlows") + if err := awsAwsjson11_serializeDocumentOAuthFlowsType(v.AllowedOAuthFlows, ok); err != nil { + return err + } + } + + if v.AllowedOAuthFlowsUserPoolClient { + ok := object.Key("AllowedOAuthFlowsUserPoolClient") + ok.Boolean(v.AllowedOAuthFlowsUserPoolClient) + } + + if v.AllowedOAuthScopes != nil { + ok := object.Key("AllowedOAuthScopes") + if err := awsAwsjson11_serializeDocumentScopeListType(v.AllowedOAuthScopes, ok); err != nil { + return err + } + } + + if v.AnalyticsConfiguration != nil { + ok := object.Key("AnalyticsConfiguration") + if err := awsAwsjson11_serializeDocumentAnalyticsConfigurationType(v.AnalyticsConfiguration, ok); err != nil { + return err + } + } + + if v.AuthSessionValidity != nil { + ok := object.Key("AuthSessionValidity") + ok.Integer(*v.AuthSessionValidity) + } + + if v.CallbackURLs != nil { + ok := object.Key("CallbackURLs") + if err := awsAwsjson11_serializeDocumentCallbackURLsListType(v.CallbackURLs, ok); err != nil { + return err + } + } + + if v.ClientId != nil { + ok := object.Key("ClientId") + ok.String(*v.ClientId) + } + + if v.ClientName != nil { + ok := object.Key("ClientName") + ok.String(*v.ClientName) + } + + if v.DefaultRedirectURI != nil { + ok := object.Key("DefaultRedirectURI") + ok.String(*v.DefaultRedirectURI) + } + + if v.EnablePropagateAdditionalUserContextData != nil { + ok := object.Key("EnablePropagateAdditionalUserContextData") + ok.Boolean(*v.EnablePropagateAdditionalUserContextData) + } + + if v.EnableTokenRevocation != nil { + ok := object.Key("EnableTokenRevocation") + ok.Boolean(*v.EnableTokenRevocation) + } + + if v.ExplicitAuthFlows != nil { + ok := object.Key("ExplicitAuthFlows") + if err := awsAwsjson11_serializeDocumentExplicitAuthFlowsListType(v.ExplicitAuthFlows, ok); err != nil { + return err + } + } + + if v.IdTokenValidity != nil { + ok := object.Key("IdTokenValidity") + ok.Integer(*v.IdTokenValidity) + } + + if v.LogoutURLs != nil { + ok := object.Key("LogoutURLs") + if err := awsAwsjson11_serializeDocumentLogoutURLsListType(v.LogoutURLs, ok); err != nil { + return err + } + } + + if len(v.PreventUserExistenceErrors) > 0 { + ok := object.Key("PreventUserExistenceErrors") + ok.String(string(v.PreventUserExistenceErrors)) + } + + if v.ReadAttributes != nil { + ok := object.Key("ReadAttributes") + if err := awsAwsjson11_serializeDocumentClientPermissionListType(v.ReadAttributes, ok); err != nil { + return err + } + } + + if v.RefreshTokenRotation != nil { + ok := object.Key("RefreshTokenRotation") + if err := awsAwsjson11_serializeDocumentRefreshTokenRotationType(v.RefreshTokenRotation, ok); err != nil { + return err + } + } + + if v.RefreshTokenValidity != 0 { + ok := object.Key("RefreshTokenValidity") + ok.Integer(v.RefreshTokenValidity) + } + + if v.SupportedIdentityProviders != nil { + ok := object.Key("SupportedIdentityProviders") + if err := awsAwsjson11_serializeDocumentSupportedIdentityProvidersListType(v.SupportedIdentityProviders, ok); err != nil { + return err + } + } + + if v.TokenValidityUnits != nil { + ok := object.Key("TokenValidityUnits") + if err := awsAwsjson11_serializeDocumentTokenValidityUnitsType(v.TokenValidityUnits, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + if v.WriteAttributes != nil { + ok := object.Key("WriteAttributes") + if err := awsAwsjson11_serializeDocumentClientPermissionListType(v.WriteAttributes, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateUserPoolDomainInput(v *UpdateUserPoolDomainInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.CustomDomainConfig != nil { + ok := object.Key("CustomDomainConfig") + if err := awsAwsjson11_serializeDocumentCustomDomainConfigType(v.CustomDomainConfig, ok); err != nil { + return err + } + } + + if v.Domain != nil { + ok := object.Key("Domain") + ok.String(*v.Domain) + } + + if v.ManagedLoginVersion != nil { + ok := object.Key("ManagedLoginVersion") + ok.Integer(*v.ManagedLoginVersion) + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentUpdateUserPoolInput(v *UpdateUserPoolInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccountRecoverySetting != nil { + ok := object.Key("AccountRecoverySetting") + if err := awsAwsjson11_serializeDocumentAccountRecoverySettingType(v.AccountRecoverySetting, ok); err != nil { + return err + } + } + + if v.AdminCreateUserConfig != nil { + ok := object.Key("AdminCreateUserConfig") + if err := awsAwsjson11_serializeDocumentAdminCreateUserConfigType(v.AdminCreateUserConfig, ok); err != nil { + return err + } + } + + if v.AutoVerifiedAttributes != nil { + ok := object.Key("AutoVerifiedAttributes") + if err := awsAwsjson11_serializeDocumentVerifiedAttributesListType(v.AutoVerifiedAttributes, ok); err != nil { + return err + } + } + + if len(v.DeletionProtection) > 0 { + ok := object.Key("DeletionProtection") + ok.String(string(v.DeletionProtection)) + } + + if v.DeviceConfiguration != nil { + ok := object.Key("DeviceConfiguration") + if err := awsAwsjson11_serializeDocumentDeviceConfigurationType(v.DeviceConfiguration, ok); err != nil { + return err + } + } + + if v.EmailConfiguration != nil { + ok := object.Key("EmailConfiguration") + if err := awsAwsjson11_serializeDocumentEmailConfigurationType(v.EmailConfiguration, ok); err != nil { + return err + } + } + + if v.EmailVerificationMessage != nil { + ok := object.Key("EmailVerificationMessage") + ok.String(*v.EmailVerificationMessage) + } + + if v.EmailVerificationSubject != nil { + ok := object.Key("EmailVerificationSubject") + ok.String(*v.EmailVerificationSubject) + } + + if v.LambdaConfig != nil { + ok := object.Key("LambdaConfig") + if err := awsAwsjson11_serializeDocumentLambdaConfigType(v.LambdaConfig, ok); err != nil { + return err + } + } + + if len(v.MfaConfiguration) > 0 { + ok := object.Key("MfaConfiguration") + ok.String(string(v.MfaConfiguration)) + } + + if v.Policies != nil { + ok := object.Key("Policies") + if err := awsAwsjson11_serializeDocumentUserPoolPolicyType(v.Policies, ok); err != nil { + return err + } + } + + if v.PoolName != nil { + ok := object.Key("PoolName") + ok.String(*v.PoolName) + } + + if v.SmsAuthenticationMessage != nil { + ok := object.Key("SmsAuthenticationMessage") + ok.String(*v.SmsAuthenticationMessage) + } + + if v.SmsConfiguration != nil { + ok := object.Key("SmsConfiguration") + if err := awsAwsjson11_serializeDocumentSmsConfigurationType(v.SmsConfiguration, ok); err != nil { + return err + } + } + + if v.SmsVerificationMessage != nil { + ok := object.Key("SmsVerificationMessage") + ok.String(*v.SmsVerificationMessage) + } + + if v.UserAttributeUpdateSettings != nil { + ok := object.Key("UserAttributeUpdateSettings") + if err := awsAwsjson11_serializeDocumentUserAttributeUpdateSettingsType(v.UserAttributeUpdateSettings, ok); err != nil { + return err + } + } + + if v.UserPoolAddOns != nil { + ok := object.Key("UserPoolAddOns") + if err := awsAwsjson11_serializeDocumentUserPoolAddOnsType(v.UserPoolAddOns, ok); err != nil { + return err + } + } + + if v.UserPoolId != nil { + ok := object.Key("UserPoolId") + ok.String(*v.UserPoolId) + } + + if v.UserPoolTags != nil { + ok := object.Key("UserPoolTags") + if err := awsAwsjson11_serializeDocumentUserPoolTagsType(v.UserPoolTags, ok); err != nil { + return err + } + } + + if len(v.UserPoolTier) > 0 { + ok := object.Key("UserPoolTier") + ok.String(string(v.UserPoolTier)) + } + + if v.VerificationMessageTemplate != nil { + ok := object.Key("VerificationMessageTemplate") + if err := awsAwsjson11_serializeDocumentVerificationMessageTemplateType(v.VerificationMessageTemplate, ok); err != nil { + return err + } + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentVerifySoftwareTokenInput(v *VerifySoftwareTokenInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.FriendlyDeviceName != nil { + ok := object.Key("FriendlyDeviceName") + ok.String(*v.FriendlyDeviceName) + } + + if v.Session != nil { + ok := object.Key("Session") + ok.String(*v.Session) + } + + if v.UserCode != nil { + ok := object.Key("UserCode") + ok.String(*v.UserCode) + } + + return nil +} + +func awsAwsjson11_serializeOpDocumentVerifyUserAttributeInput(v *VerifyUserAttributeInput, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.AccessToken != nil { + ok := object.Key("AccessToken") + ok.String(*v.AccessToken) + } + + if v.AttributeName != nil { + ok := object.Key("AttributeName") + ok.String(*v.AttributeName) + } + + if v.Code != nil { + ok := object.Key("Code") + ok.String(*v.Code) + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/enums.go new file mode 100644 index 00000000..6d422954 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/enums.go @@ -0,0 +1,1089 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +type AccountTakeoverEventActionType string + +// Enum values for AccountTakeoverEventActionType +const ( + AccountTakeoverEventActionTypeBlock AccountTakeoverEventActionType = "BLOCK" + AccountTakeoverEventActionTypeMfaIfConfigured AccountTakeoverEventActionType = "MFA_IF_CONFIGURED" + AccountTakeoverEventActionTypeMfaRequired AccountTakeoverEventActionType = "MFA_REQUIRED" + AccountTakeoverEventActionTypeNoAction AccountTakeoverEventActionType = "NO_ACTION" +) + +// Values returns all known values for AccountTakeoverEventActionType. Note that +// this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AccountTakeoverEventActionType) Values() []AccountTakeoverEventActionType { + return []AccountTakeoverEventActionType{ + "BLOCK", + "MFA_IF_CONFIGURED", + "MFA_REQUIRED", + "NO_ACTION", + } +} + +type AdvancedSecurityEnabledModeType string + +// Enum values for AdvancedSecurityEnabledModeType +const ( + AdvancedSecurityEnabledModeTypeAudit AdvancedSecurityEnabledModeType = "AUDIT" + AdvancedSecurityEnabledModeTypeEnforced AdvancedSecurityEnabledModeType = "ENFORCED" +) + +// Values returns all known values for AdvancedSecurityEnabledModeType. Note that +// this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AdvancedSecurityEnabledModeType) Values() []AdvancedSecurityEnabledModeType { + return []AdvancedSecurityEnabledModeType{ + "AUDIT", + "ENFORCED", + } +} + +type AdvancedSecurityModeType string + +// Enum values for AdvancedSecurityModeType +const ( + AdvancedSecurityModeTypeOff AdvancedSecurityModeType = "OFF" + AdvancedSecurityModeTypeAudit AdvancedSecurityModeType = "AUDIT" + AdvancedSecurityModeTypeEnforced AdvancedSecurityModeType = "ENFORCED" +) + +// Values returns all known values for AdvancedSecurityModeType. Note that this +// can be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AdvancedSecurityModeType) Values() []AdvancedSecurityModeType { + return []AdvancedSecurityModeType{ + "OFF", + "AUDIT", + "ENFORCED", + } +} + +type AliasAttributeType string + +// Enum values for AliasAttributeType +const ( + AliasAttributeTypePhoneNumber AliasAttributeType = "phone_number" + AliasAttributeTypeEmail AliasAttributeType = "email" + AliasAttributeTypePreferredUsername AliasAttributeType = "preferred_username" +) + +// Values returns all known values for AliasAttributeType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AliasAttributeType) Values() []AliasAttributeType { + return []AliasAttributeType{ + "phone_number", + "email", + "preferred_username", + } +} + +type AssetCategoryType string + +// Enum values for AssetCategoryType +const ( + AssetCategoryTypeFaviconIco AssetCategoryType = "FAVICON_ICO" + AssetCategoryTypeFaviconSvg AssetCategoryType = "FAVICON_SVG" + AssetCategoryTypeEmailGraphic AssetCategoryType = "EMAIL_GRAPHIC" + AssetCategoryTypeSmsGraphic AssetCategoryType = "SMS_GRAPHIC" + AssetCategoryTypeAuthAppGraphic AssetCategoryType = "AUTH_APP_GRAPHIC" + AssetCategoryTypePasswordGraphic AssetCategoryType = "PASSWORD_GRAPHIC" + AssetCategoryTypePasskeyGraphic AssetCategoryType = "PASSKEY_GRAPHIC" + AssetCategoryTypePageHeaderLogo AssetCategoryType = "PAGE_HEADER_LOGO" + AssetCategoryTypePageHeaderBackground AssetCategoryType = "PAGE_HEADER_BACKGROUND" + AssetCategoryTypePageFooterLogo AssetCategoryType = "PAGE_FOOTER_LOGO" + AssetCategoryTypePageFooterBackground AssetCategoryType = "PAGE_FOOTER_BACKGROUND" + AssetCategoryTypePageBackground AssetCategoryType = "PAGE_BACKGROUND" + AssetCategoryTypeFormBackground AssetCategoryType = "FORM_BACKGROUND" + AssetCategoryTypeFormLogo AssetCategoryType = "FORM_LOGO" + AssetCategoryTypeIdpButtonIcon AssetCategoryType = "IDP_BUTTON_ICON" +) + +// Values returns all known values for AssetCategoryType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AssetCategoryType) Values() []AssetCategoryType { + return []AssetCategoryType{ + "FAVICON_ICO", + "FAVICON_SVG", + "EMAIL_GRAPHIC", + "SMS_GRAPHIC", + "AUTH_APP_GRAPHIC", + "PASSWORD_GRAPHIC", + "PASSKEY_GRAPHIC", + "PAGE_HEADER_LOGO", + "PAGE_HEADER_BACKGROUND", + "PAGE_FOOTER_LOGO", + "PAGE_FOOTER_BACKGROUND", + "PAGE_BACKGROUND", + "FORM_BACKGROUND", + "FORM_LOGO", + "IDP_BUTTON_ICON", + } +} + +type AssetExtensionType string + +// Enum values for AssetExtensionType +const ( + AssetExtensionTypeIco AssetExtensionType = "ICO" + AssetExtensionTypeJpeg AssetExtensionType = "JPEG" + AssetExtensionTypePng AssetExtensionType = "PNG" + AssetExtensionTypeSvg AssetExtensionType = "SVG" + AssetExtensionTypeWebp AssetExtensionType = "WEBP" +) + +// Values returns all known values for AssetExtensionType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AssetExtensionType) Values() []AssetExtensionType { + return []AssetExtensionType{ + "ICO", + "JPEG", + "PNG", + "SVG", + "WEBP", + } +} + +type AttributeDataType string + +// Enum values for AttributeDataType +const ( + AttributeDataTypeString AttributeDataType = "String" + AttributeDataTypeNumber AttributeDataType = "Number" + AttributeDataTypeDatetime AttributeDataType = "DateTime" + AttributeDataTypeBoolean AttributeDataType = "Boolean" +) + +// Values returns all known values for AttributeDataType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AttributeDataType) Values() []AttributeDataType { + return []AttributeDataType{ + "String", + "Number", + "DateTime", + "Boolean", + } +} + +type AuthFactorType string + +// Enum values for AuthFactorType +const ( + AuthFactorTypePassword AuthFactorType = "PASSWORD" + AuthFactorTypeEmailOtp AuthFactorType = "EMAIL_OTP" + AuthFactorTypeSmsOtp AuthFactorType = "SMS_OTP" + AuthFactorTypeWebAuthn AuthFactorType = "WEB_AUTHN" +) + +// Values returns all known values for AuthFactorType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AuthFactorType) Values() []AuthFactorType { + return []AuthFactorType{ + "PASSWORD", + "EMAIL_OTP", + "SMS_OTP", + "WEB_AUTHN", + } +} + +type AuthFlowType string + +// Enum values for AuthFlowType +const ( + AuthFlowTypeUserSrpAuth AuthFlowType = "USER_SRP_AUTH" + AuthFlowTypeRefreshTokenAuth AuthFlowType = "REFRESH_TOKEN_AUTH" + AuthFlowTypeRefreshToken AuthFlowType = "REFRESH_TOKEN" + AuthFlowTypeCustomAuth AuthFlowType = "CUSTOM_AUTH" + AuthFlowTypeAdminNoSrpAuth AuthFlowType = "ADMIN_NO_SRP_AUTH" + AuthFlowTypeUserPasswordAuth AuthFlowType = "USER_PASSWORD_AUTH" + AuthFlowTypeAdminUserPasswordAuth AuthFlowType = "ADMIN_USER_PASSWORD_AUTH" + AuthFlowTypeUserAuth AuthFlowType = "USER_AUTH" +) + +// Values returns all known values for AuthFlowType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (AuthFlowType) Values() []AuthFlowType { + return []AuthFlowType{ + "USER_SRP_AUTH", + "REFRESH_TOKEN_AUTH", + "REFRESH_TOKEN", + "CUSTOM_AUTH", + "ADMIN_NO_SRP_AUTH", + "USER_PASSWORD_AUTH", + "ADMIN_USER_PASSWORD_AUTH", + "USER_AUTH", + } +} + +type ChallengeName string + +// Enum values for ChallengeName +const ( + ChallengeNamePassword ChallengeName = "Password" + ChallengeNameMfa ChallengeName = "Mfa" +) + +// Values returns all known values for ChallengeName. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ChallengeName) Values() []ChallengeName { + return []ChallengeName{ + "Password", + "Mfa", + } +} + +type ChallengeNameType string + +// Enum values for ChallengeNameType +const ( + ChallengeNameTypeSmsMfa ChallengeNameType = "SMS_MFA" + ChallengeNameTypeEmailOtp ChallengeNameType = "EMAIL_OTP" + ChallengeNameTypeSoftwareTokenMfa ChallengeNameType = "SOFTWARE_TOKEN_MFA" + ChallengeNameTypeSelectMfaType ChallengeNameType = "SELECT_MFA_TYPE" + ChallengeNameTypeMfaSetup ChallengeNameType = "MFA_SETUP" + ChallengeNameTypePasswordVerifier ChallengeNameType = "PASSWORD_VERIFIER" + ChallengeNameTypeCustomChallenge ChallengeNameType = "CUSTOM_CHALLENGE" + ChallengeNameTypeSelectChallenge ChallengeNameType = "SELECT_CHALLENGE" + ChallengeNameTypeDeviceSrpAuth ChallengeNameType = "DEVICE_SRP_AUTH" + ChallengeNameTypeDevicePasswordVerifier ChallengeNameType = "DEVICE_PASSWORD_VERIFIER" + ChallengeNameTypeAdminNoSrpAuth ChallengeNameType = "ADMIN_NO_SRP_AUTH" + ChallengeNameTypeNewPasswordRequired ChallengeNameType = "NEW_PASSWORD_REQUIRED" + ChallengeNameTypeSmsOtp ChallengeNameType = "SMS_OTP" + ChallengeNameTypePassword ChallengeNameType = "PASSWORD" + ChallengeNameTypeWebAuthn ChallengeNameType = "WEB_AUTHN" + ChallengeNameTypePasswordSrp ChallengeNameType = "PASSWORD_SRP" +) + +// Values returns all known values for ChallengeNameType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ChallengeNameType) Values() []ChallengeNameType { + return []ChallengeNameType{ + "SMS_MFA", + "EMAIL_OTP", + "SOFTWARE_TOKEN_MFA", + "SELECT_MFA_TYPE", + "MFA_SETUP", + "PASSWORD_VERIFIER", + "CUSTOM_CHALLENGE", + "SELECT_CHALLENGE", + "DEVICE_SRP_AUTH", + "DEVICE_PASSWORD_VERIFIER", + "ADMIN_NO_SRP_AUTH", + "NEW_PASSWORD_REQUIRED", + "SMS_OTP", + "PASSWORD", + "WEB_AUTHN", + "PASSWORD_SRP", + } +} + +type ChallengeResponse string + +// Enum values for ChallengeResponse +const ( + ChallengeResponseSuccess ChallengeResponse = "Success" + ChallengeResponseFailure ChallengeResponse = "Failure" +) + +// Values returns all known values for ChallengeResponse. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ChallengeResponse) Values() []ChallengeResponse { + return []ChallengeResponse{ + "Success", + "Failure", + } +} + +type ColorSchemeModeType string + +// Enum values for ColorSchemeModeType +const ( + ColorSchemeModeTypeLight ColorSchemeModeType = "LIGHT" + ColorSchemeModeTypeDark ColorSchemeModeType = "DARK" + ColorSchemeModeTypeDynamic ColorSchemeModeType = "DYNAMIC" +) + +// Values returns all known values for ColorSchemeModeType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ColorSchemeModeType) Values() []ColorSchemeModeType { + return []ColorSchemeModeType{ + "LIGHT", + "DARK", + "DYNAMIC", + } +} + +type CompromisedCredentialsEventActionType string + +// Enum values for CompromisedCredentialsEventActionType +const ( + CompromisedCredentialsEventActionTypeBlock CompromisedCredentialsEventActionType = "BLOCK" + CompromisedCredentialsEventActionTypeNoAction CompromisedCredentialsEventActionType = "NO_ACTION" +) + +// Values returns all known values for CompromisedCredentialsEventActionType. Note +// that this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (CompromisedCredentialsEventActionType) Values() []CompromisedCredentialsEventActionType { + return []CompromisedCredentialsEventActionType{ + "BLOCK", + "NO_ACTION", + } +} + +type CustomEmailSenderLambdaVersionType string + +// Enum values for CustomEmailSenderLambdaVersionType +const ( + CustomEmailSenderLambdaVersionTypeV10 CustomEmailSenderLambdaVersionType = "V1_0" +) + +// Values returns all known values for CustomEmailSenderLambdaVersionType. Note +// that this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (CustomEmailSenderLambdaVersionType) Values() []CustomEmailSenderLambdaVersionType { + return []CustomEmailSenderLambdaVersionType{ + "V1_0", + } +} + +type CustomSMSSenderLambdaVersionType string + +// Enum values for CustomSMSSenderLambdaVersionType +const ( + CustomSMSSenderLambdaVersionTypeV10 CustomSMSSenderLambdaVersionType = "V1_0" +) + +// Values returns all known values for CustomSMSSenderLambdaVersionType. Note that +// this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (CustomSMSSenderLambdaVersionType) Values() []CustomSMSSenderLambdaVersionType { + return []CustomSMSSenderLambdaVersionType{ + "V1_0", + } +} + +type DefaultEmailOptionType string + +// Enum values for DefaultEmailOptionType +const ( + DefaultEmailOptionTypeConfirmWithLink DefaultEmailOptionType = "CONFIRM_WITH_LINK" + DefaultEmailOptionTypeConfirmWithCode DefaultEmailOptionType = "CONFIRM_WITH_CODE" +) + +// Values returns all known values for DefaultEmailOptionType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (DefaultEmailOptionType) Values() []DefaultEmailOptionType { + return []DefaultEmailOptionType{ + "CONFIRM_WITH_LINK", + "CONFIRM_WITH_CODE", + } +} + +type DeletionProtectionType string + +// Enum values for DeletionProtectionType +const ( + DeletionProtectionTypeActive DeletionProtectionType = "ACTIVE" + DeletionProtectionTypeInactive DeletionProtectionType = "INACTIVE" +) + +// Values returns all known values for DeletionProtectionType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (DeletionProtectionType) Values() []DeletionProtectionType { + return []DeletionProtectionType{ + "ACTIVE", + "INACTIVE", + } +} + +type DeliveryMediumType string + +// Enum values for DeliveryMediumType +const ( + DeliveryMediumTypeSms DeliveryMediumType = "SMS" + DeliveryMediumTypeEmail DeliveryMediumType = "EMAIL" +) + +// Values returns all known values for DeliveryMediumType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (DeliveryMediumType) Values() []DeliveryMediumType { + return []DeliveryMediumType{ + "SMS", + "EMAIL", + } +} + +type DeviceRememberedStatusType string + +// Enum values for DeviceRememberedStatusType +const ( + DeviceRememberedStatusTypeRemembered DeviceRememberedStatusType = "remembered" + DeviceRememberedStatusTypeNotRemembered DeviceRememberedStatusType = "not_remembered" +) + +// Values returns all known values for DeviceRememberedStatusType. Note that this +// can be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (DeviceRememberedStatusType) Values() []DeviceRememberedStatusType { + return []DeviceRememberedStatusType{ + "remembered", + "not_remembered", + } +} + +type DomainStatusType string + +// Enum values for DomainStatusType +const ( + DomainStatusTypeCreating DomainStatusType = "CREATING" + DomainStatusTypeDeleting DomainStatusType = "DELETING" + DomainStatusTypeUpdating DomainStatusType = "UPDATING" + DomainStatusTypeActive DomainStatusType = "ACTIVE" + DomainStatusTypeFailed DomainStatusType = "FAILED" +) + +// Values returns all known values for DomainStatusType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (DomainStatusType) Values() []DomainStatusType { + return []DomainStatusType{ + "CREATING", + "DELETING", + "UPDATING", + "ACTIVE", + "FAILED", + } +} + +type EmailSendingAccountType string + +// Enum values for EmailSendingAccountType +const ( + EmailSendingAccountTypeCognitoDefault EmailSendingAccountType = "COGNITO_DEFAULT" + EmailSendingAccountTypeDeveloper EmailSendingAccountType = "DEVELOPER" +) + +// Values returns all known values for EmailSendingAccountType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (EmailSendingAccountType) Values() []EmailSendingAccountType { + return []EmailSendingAccountType{ + "COGNITO_DEFAULT", + "DEVELOPER", + } +} + +type EventFilterType string + +// Enum values for EventFilterType +const ( + EventFilterTypeSignIn EventFilterType = "SIGN_IN" + EventFilterTypePasswordChange EventFilterType = "PASSWORD_CHANGE" + EventFilterTypeSignUp EventFilterType = "SIGN_UP" +) + +// Values returns all known values for EventFilterType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (EventFilterType) Values() []EventFilterType { + return []EventFilterType{ + "SIGN_IN", + "PASSWORD_CHANGE", + "SIGN_UP", + } +} + +type EventResponseType string + +// Enum values for EventResponseType +const ( + EventResponseTypePass EventResponseType = "Pass" + EventResponseTypeFail EventResponseType = "Fail" + EventResponseTypeInProgress EventResponseType = "InProgress" +) + +// Values returns all known values for EventResponseType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (EventResponseType) Values() []EventResponseType { + return []EventResponseType{ + "Pass", + "Fail", + "InProgress", + } +} + +type EventSourceName string + +// Enum values for EventSourceName +const ( + EventSourceNameUserNotification EventSourceName = "userNotification" + EventSourceNameUserAuthEvents EventSourceName = "userAuthEvents" +) + +// Values returns all known values for EventSourceName. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (EventSourceName) Values() []EventSourceName { + return []EventSourceName{ + "userNotification", + "userAuthEvents", + } +} + +type EventType string + +// Enum values for EventType +const ( + EventTypeSignIn EventType = "SignIn" + EventTypeSignUp EventType = "SignUp" + EventTypeForgotPassword EventType = "ForgotPassword" + EventTypePasswordChange EventType = "PasswordChange" + EventTypeResendCode EventType = "ResendCode" +) + +// Values returns all known values for EventType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (EventType) Values() []EventType { + return []EventType{ + "SignIn", + "SignUp", + "ForgotPassword", + "PasswordChange", + "ResendCode", + } +} + +type ExplicitAuthFlowsType string + +// Enum values for ExplicitAuthFlowsType +const ( + ExplicitAuthFlowsTypeAdminNoSrpAuth ExplicitAuthFlowsType = "ADMIN_NO_SRP_AUTH" + ExplicitAuthFlowsTypeCustomAuthFlowOnly ExplicitAuthFlowsType = "CUSTOM_AUTH_FLOW_ONLY" + ExplicitAuthFlowsTypeUserPasswordAuth ExplicitAuthFlowsType = "USER_PASSWORD_AUTH" + ExplicitAuthFlowsTypeAllowAdminUserPasswordAuth ExplicitAuthFlowsType = "ALLOW_ADMIN_USER_PASSWORD_AUTH" + ExplicitAuthFlowsTypeAllowCustomAuth ExplicitAuthFlowsType = "ALLOW_CUSTOM_AUTH" + ExplicitAuthFlowsTypeAllowUserPasswordAuth ExplicitAuthFlowsType = "ALLOW_USER_PASSWORD_AUTH" + ExplicitAuthFlowsTypeAllowUserSrpAuth ExplicitAuthFlowsType = "ALLOW_USER_SRP_AUTH" + ExplicitAuthFlowsTypeAllowRefreshTokenAuth ExplicitAuthFlowsType = "ALLOW_REFRESH_TOKEN_AUTH" + ExplicitAuthFlowsTypeAllowUserAuth ExplicitAuthFlowsType = "ALLOW_USER_AUTH" +) + +// Values returns all known values for ExplicitAuthFlowsType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (ExplicitAuthFlowsType) Values() []ExplicitAuthFlowsType { + return []ExplicitAuthFlowsType{ + "ADMIN_NO_SRP_AUTH", + "CUSTOM_AUTH_FLOW_ONLY", + "USER_PASSWORD_AUTH", + "ALLOW_ADMIN_USER_PASSWORD_AUTH", + "ALLOW_CUSTOM_AUTH", + "ALLOW_USER_PASSWORD_AUTH", + "ALLOW_USER_SRP_AUTH", + "ALLOW_REFRESH_TOKEN_AUTH", + "ALLOW_USER_AUTH", + } +} + +type FeatureType string + +// Enum values for FeatureType +const ( + FeatureTypeEnabled FeatureType = "ENABLED" + FeatureTypeDisabled FeatureType = "DISABLED" +) + +// Values returns all known values for FeatureType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (FeatureType) Values() []FeatureType { + return []FeatureType{ + "ENABLED", + "DISABLED", + } +} + +type FeedbackValueType string + +// Enum values for FeedbackValueType +const ( + FeedbackValueTypeValid FeedbackValueType = "Valid" + FeedbackValueTypeInvalid FeedbackValueType = "Invalid" +) + +// Values returns all known values for FeedbackValueType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (FeedbackValueType) Values() []FeedbackValueType { + return []FeedbackValueType{ + "Valid", + "Invalid", + } +} + +type IdentityProviderTypeType string + +// Enum values for IdentityProviderTypeType +const ( + IdentityProviderTypeTypeSaml IdentityProviderTypeType = "SAML" + IdentityProviderTypeTypeFacebook IdentityProviderTypeType = "Facebook" + IdentityProviderTypeTypeGoogle IdentityProviderTypeType = "Google" + IdentityProviderTypeTypeLoginWithAmazon IdentityProviderTypeType = "LoginWithAmazon" + IdentityProviderTypeTypeSignInWithApple IdentityProviderTypeType = "SignInWithApple" + IdentityProviderTypeTypeOidc IdentityProviderTypeType = "OIDC" +) + +// Values returns all known values for IdentityProviderTypeType. Note that this +// can be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (IdentityProviderTypeType) Values() []IdentityProviderTypeType { + return []IdentityProviderTypeType{ + "SAML", + "Facebook", + "Google", + "LoginWithAmazon", + "SignInWithApple", + "OIDC", + } +} + +type LogLevel string + +// Enum values for LogLevel +const ( + LogLevelError LogLevel = "ERROR" + LogLevelInfo LogLevel = "INFO" +) + +// Values returns all known values for LogLevel. Note that this can be expanded in +// the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (LogLevel) Values() []LogLevel { + return []LogLevel{ + "ERROR", + "INFO", + } +} + +type MessageActionType string + +// Enum values for MessageActionType +const ( + MessageActionTypeResend MessageActionType = "RESEND" + MessageActionTypeSuppress MessageActionType = "SUPPRESS" +) + +// Values returns all known values for MessageActionType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (MessageActionType) Values() []MessageActionType { + return []MessageActionType{ + "RESEND", + "SUPPRESS", + } +} + +type OAuthFlowType string + +// Enum values for OAuthFlowType +const ( + OAuthFlowTypeCode OAuthFlowType = "code" + OAuthFlowTypeImplicit OAuthFlowType = "implicit" + OAuthFlowTypeClientCredentials OAuthFlowType = "client_credentials" +) + +// Values returns all known values for OAuthFlowType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (OAuthFlowType) Values() []OAuthFlowType { + return []OAuthFlowType{ + "code", + "implicit", + "client_credentials", + } +} + +type PreTokenGenerationLambdaVersionType string + +// Enum values for PreTokenGenerationLambdaVersionType +const ( + PreTokenGenerationLambdaVersionTypeV10 PreTokenGenerationLambdaVersionType = "V1_0" + PreTokenGenerationLambdaVersionTypeV20 PreTokenGenerationLambdaVersionType = "V2_0" + PreTokenGenerationLambdaVersionTypeV30 PreTokenGenerationLambdaVersionType = "V3_0" +) + +// Values returns all known values for PreTokenGenerationLambdaVersionType. Note +// that this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (PreTokenGenerationLambdaVersionType) Values() []PreTokenGenerationLambdaVersionType { + return []PreTokenGenerationLambdaVersionType{ + "V1_0", + "V2_0", + "V3_0", + } +} + +type PreventUserExistenceErrorTypes string + +// Enum values for PreventUserExistenceErrorTypes +const ( + PreventUserExistenceErrorTypesLegacy PreventUserExistenceErrorTypes = "LEGACY" + PreventUserExistenceErrorTypesEnabled PreventUserExistenceErrorTypes = "ENABLED" +) + +// Values returns all known values for PreventUserExistenceErrorTypes. Note that +// this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (PreventUserExistenceErrorTypes) Values() []PreventUserExistenceErrorTypes { + return []PreventUserExistenceErrorTypes{ + "LEGACY", + "ENABLED", + } +} + +type RecoveryOptionNameType string + +// Enum values for RecoveryOptionNameType +const ( + RecoveryOptionNameTypeVerifiedEmail RecoveryOptionNameType = "verified_email" + RecoveryOptionNameTypeVerifiedPhoneNumber RecoveryOptionNameType = "verified_phone_number" + RecoveryOptionNameTypeAdminOnly RecoveryOptionNameType = "admin_only" +) + +// Values returns all known values for RecoveryOptionNameType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (RecoveryOptionNameType) Values() []RecoveryOptionNameType { + return []RecoveryOptionNameType{ + "verified_email", + "verified_phone_number", + "admin_only", + } +} + +type RiskDecisionType string + +// Enum values for RiskDecisionType +const ( + RiskDecisionTypeNoRisk RiskDecisionType = "NoRisk" + RiskDecisionTypeAccountTakeover RiskDecisionType = "AccountTakeover" + RiskDecisionTypeBlock RiskDecisionType = "Block" +) + +// Values returns all known values for RiskDecisionType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (RiskDecisionType) Values() []RiskDecisionType { + return []RiskDecisionType{ + "NoRisk", + "AccountTakeover", + "Block", + } +} + +type RiskLevelType string + +// Enum values for RiskLevelType +const ( + RiskLevelTypeLow RiskLevelType = "Low" + RiskLevelTypeMedium RiskLevelType = "Medium" + RiskLevelTypeHigh RiskLevelType = "High" +) + +// Values returns all known values for RiskLevelType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (RiskLevelType) Values() []RiskLevelType { + return []RiskLevelType{ + "Low", + "Medium", + "High", + } +} + +type StatusType string + +// Enum values for StatusType +const ( + StatusTypeEnabled StatusType = "Enabled" + StatusTypeDisabled StatusType = "Disabled" +) + +// Values returns all known values for StatusType. Note that this can be expanded +// in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (StatusType) Values() []StatusType { + return []StatusType{ + "Enabled", + "Disabled", + } +} + +type TimeUnitsType string + +// Enum values for TimeUnitsType +const ( + TimeUnitsTypeSeconds TimeUnitsType = "seconds" + TimeUnitsTypeMinutes TimeUnitsType = "minutes" + TimeUnitsTypeHours TimeUnitsType = "hours" + TimeUnitsTypeDays TimeUnitsType = "days" +) + +// Values returns all known values for TimeUnitsType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (TimeUnitsType) Values() []TimeUnitsType { + return []TimeUnitsType{ + "seconds", + "minutes", + "hours", + "days", + } +} + +type UserImportJobStatusType string + +// Enum values for UserImportJobStatusType +const ( + UserImportJobStatusTypeCreated UserImportJobStatusType = "Created" + UserImportJobStatusTypePending UserImportJobStatusType = "Pending" + UserImportJobStatusTypeInProgress UserImportJobStatusType = "InProgress" + UserImportJobStatusTypeStopping UserImportJobStatusType = "Stopping" + UserImportJobStatusTypeExpired UserImportJobStatusType = "Expired" + UserImportJobStatusTypeStopped UserImportJobStatusType = "Stopped" + UserImportJobStatusTypeFailed UserImportJobStatusType = "Failed" + UserImportJobStatusTypeSucceeded UserImportJobStatusType = "Succeeded" +) + +// Values returns all known values for UserImportJobStatusType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UserImportJobStatusType) Values() []UserImportJobStatusType { + return []UserImportJobStatusType{ + "Created", + "Pending", + "InProgress", + "Stopping", + "Expired", + "Stopped", + "Failed", + "Succeeded", + } +} + +type UsernameAttributeType string + +// Enum values for UsernameAttributeType +const ( + UsernameAttributeTypePhoneNumber UsernameAttributeType = "phone_number" + UsernameAttributeTypeEmail UsernameAttributeType = "email" +) + +// Values returns all known values for UsernameAttributeType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UsernameAttributeType) Values() []UsernameAttributeType { + return []UsernameAttributeType{ + "phone_number", + "email", + } +} + +type UserPoolMfaType string + +// Enum values for UserPoolMfaType +const ( + UserPoolMfaTypeOff UserPoolMfaType = "OFF" + UserPoolMfaTypeOn UserPoolMfaType = "ON" + UserPoolMfaTypeOptional UserPoolMfaType = "OPTIONAL" +) + +// Values returns all known values for UserPoolMfaType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UserPoolMfaType) Values() []UserPoolMfaType { + return []UserPoolMfaType{ + "OFF", + "ON", + "OPTIONAL", + } +} + +type UserPoolTierType string + +// Enum values for UserPoolTierType +const ( + UserPoolTierTypeLite UserPoolTierType = "LITE" + UserPoolTierTypeEssentials UserPoolTierType = "ESSENTIALS" + UserPoolTierTypePlus UserPoolTierType = "PLUS" +) + +// Values returns all known values for UserPoolTierType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UserPoolTierType) Values() []UserPoolTierType { + return []UserPoolTierType{ + "LITE", + "ESSENTIALS", + "PLUS", + } +} + +type UserStatusType string + +// Enum values for UserStatusType +const ( + UserStatusTypeUnconfirmed UserStatusType = "UNCONFIRMED" + UserStatusTypeConfirmed UserStatusType = "CONFIRMED" + UserStatusTypeArchived UserStatusType = "ARCHIVED" + UserStatusTypeCompromised UserStatusType = "COMPROMISED" + UserStatusTypeUnknown UserStatusType = "UNKNOWN" + UserStatusTypeResetRequired UserStatusType = "RESET_REQUIRED" + UserStatusTypeForceChangePassword UserStatusType = "FORCE_CHANGE_PASSWORD" + UserStatusTypeExternalProvider UserStatusType = "EXTERNAL_PROVIDER" +) + +// Values returns all known values for UserStatusType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UserStatusType) Values() []UserStatusType { + return []UserStatusType{ + "UNCONFIRMED", + "CONFIRMED", + "ARCHIVED", + "COMPROMISED", + "UNKNOWN", + "RESET_REQUIRED", + "FORCE_CHANGE_PASSWORD", + "EXTERNAL_PROVIDER", + } +} + +type UserVerificationType string + +// Enum values for UserVerificationType +const ( + UserVerificationTypeRequired UserVerificationType = "required" + UserVerificationTypePreferred UserVerificationType = "preferred" +) + +// Values returns all known values for UserVerificationType. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (UserVerificationType) Values() []UserVerificationType { + return []UserVerificationType{ + "required", + "preferred", + } +} + +type VerifiedAttributeType string + +// Enum values for VerifiedAttributeType +const ( + VerifiedAttributeTypePhoneNumber VerifiedAttributeType = "phone_number" + VerifiedAttributeTypeEmail VerifiedAttributeType = "email" +) + +// Values returns all known values for VerifiedAttributeType. Note that this can +// be expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (VerifiedAttributeType) Values() []VerifiedAttributeType { + return []VerifiedAttributeType{ + "phone_number", + "email", + } +} + +type VerifySoftwareTokenResponseType string + +// Enum values for VerifySoftwareTokenResponseType +const ( + VerifySoftwareTokenResponseTypeSuccess VerifySoftwareTokenResponseType = "SUCCESS" + VerifySoftwareTokenResponseTypeError VerifySoftwareTokenResponseType = "ERROR" +) + +// Values returns all known values for VerifySoftwareTokenResponseType. Note that +// this can be expanded in the future, and so it is only as up to date as the +// client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (VerifySoftwareTokenResponseType) Values() []VerifySoftwareTokenResponseType { + return []VerifySoftwareTokenResponseType{ + "SUCCESS", + "ERROR", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/errors.go new file mode 100644 index 00000000..3bca4e05 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/errors.go @@ -0,0 +1,1478 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +import ( + "fmt" + smithy "github.com/aws/smithy-go" +) + +// This exception is thrown when a user tries to confirm the account with an email +// address or phone number that has already been supplied as an alias for a +// different user profile. This exception indicates that an account with this email +// address or phone already exists in a user pool that you've configured to use +// email address or phone number as a sign-in alias. +type AliasExistsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *AliasExistsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *AliasExistsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *AliasExistsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "AliasExistsException" + } + return *e.ErrorCodeOverride +} +func (e *AliasExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a verification code fails to deliver successfully. +type CodeDeliveryFailureException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *CodeDeliveryFailureException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *CodeDeliveryFailureException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *CodeDeliveryFailureException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "CodeDeliveryFailureException" + } + return *e.ErrorCodeOverride +} +func (e *CodeDeliveryFailureException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown if the provided code doesn't match what the server was +// expecting. +type CodeMismatchException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *CodeMismatchException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *CodeMismatchException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *CodeMismatchException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "CodeMismatchException" + } + return *e.ErrorCodeOverride +} +func (e *CodeMismatchException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown if two or more modifications are happening +// concurrently. +type ConcurrentModificationException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ConcurrentModificationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ConcurrentModificationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ConcurrentModificationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ConcurrentModificationException" + } + return *e.ErrorCodeOverride +} +func (e *ConcurrentModificationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a user attempts to confirm a device with a device +// key that already exists. +type DeviceKeyExistsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *DeviceKeyExistsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *DeviceKeyExistsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *DeviceKeyExistsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "DeviceKeyExistsException" + } + return *e.ErrorCodeOverride +} +func (e *DeviceKeyExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the provider is already supported by the user +// pool. +type DuplicateProviderException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *DuplicateProviderException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *DuplicateProviderException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *DuplicateProviderException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "DuplicateProviderException" + } + return *e.ErrorCodeOverride +} +func (e *DuplicateProviderException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when there is a code mismatch and the service fails to +// configure the software token TOTP multi-factor authentication (MFA). +type EnableSoftwareTokenMFAException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *EnableSoftwareTokenMFAException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *EnableSoftwareTokenMFAException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *EnableSoftwareTokenMFAException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "EnableSoftwareTokenMFAException" + } + return *e.ErrorCodeOverride +} +func (e *EnableSoftwareTokenMFAException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown if a code has expired. +type ExpiredCodeException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ExpiredCodeException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ExpiredCodeException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ExpiredCodeException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ExpiredCodeException" + } + return *e.ErrorCodeOverride +} +func (e *ExpiredCodeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a feature you attempted to configure isn't +// available in your current feature plan. +type FeatureUnavailableInTierException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *FeatureUnavailableInTierException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *FeatureUnavailableInTierException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *FeatureUnavailableInTierException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "FeatureUnavailableInTierException" + } + return *e.ErrorCodeOverride +} +func (e *FeatureUnavailableInTierException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when WAF doesn't allow your request based on a web ACL +// that's associated with your user pool. +type ForbiddenException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ForbiddenException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ForbiddenException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ForbiddenException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ForbiddenException" + } + return *e.ErrorCodeOverride +} +func (e *ForbiddenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when Amazon Cognito encounters a group that already +// exists in the user pool. +type GroupExistsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *GroupExistsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *GroupExistsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *GroupExistsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "GroupExistsException" + } + return *e.ErrorCodeOverride +} +func (e *GroupExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when Amazon Cognito encounters an internal error. +type InternalErrorException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InternalErrorException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InternalErrorException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InternalErrorException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InternalErrorException" + } + return *e.ErrorCodeOverride +} +func (e *InternalErrorException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } + +// This exception is thrown when Amazon Cognito isn't allowed to use your email +// identity. HTTP status code: 400. +type InvalidEmailRoleAccessPolicyException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidEmailRoleAccessPolicyException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidEmailRoleAccessPolicyException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidEmailRoleAccessPolicyException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidEmailRoleAccessPolicyException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidEmailRoleAccessPolicyException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when Amazon Cognito encounters an invalid Lambda +// response. +type InvalidLambdaResponseException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidLambdaResponseException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidLambdaResponseException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidLambdaResponseException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidLambdaResponseException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidLambdaResponseException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the specified OAuth flow is not valid. +type InvalidOAuthFlowException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidOAuthFlowException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidOAuthFlowException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidOAuthFlowException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidOAuthFlowException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidOAuthFlowException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the Amazon Cognito service encounters an invalid +// parameter. +type InvalidParameterException struct { + Message *string + + ErrorCodeOverride *string + + ReasonCode *string + + noSmithyDocumentSerde +} + +func (e *InvalidParameterException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidParameterException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidParameterException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidParameterException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidParameterException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when Amazon Cognito encounters an invalid password. +type InvalidPasswordException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidPasswordException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidPasswordException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidPasswordException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidPasswordException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidPasswordException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is returned when the role provided for SMS configuration doesn't +// have permission to publish using Amazon SNS. +type InvalidSmsRoleAccessPolicyException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidSmsRoleAccessPolicyException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidSmsRoleAccessPolicyException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidSmsRoleAccessPolicyException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidSmsRoleAccessPolicyException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidSmsRoleAccessPolicyException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when the trust relationship is not valid for the role +// provided for SMS configuration. This can happen if you don't trust +// cognito-idp.amazonaws.com or the external ID provided in the role does not match +// what is provided in the SMS configuration for the user pool. +type InvalidSmsRoleTrustRelationshipException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidSmsRoleTrustRelationshipException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidSmsRoleTrustRelationshipException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidSmsRoleTrustRelationshipException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidSmsRoleTrustRelationshipException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidSmsRoleTrustRelationshipException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when the user pool configuration is not valid. +type InvalidUserPoolConfigurationException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *InvalidUserPoolConfigurationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InvalidUserPoolConfigurationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InvalidUserPoolConfigurationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InvalidUserPoolConfigurationException" + } + return *e.ErrorCodeOverride +} +func (e *InvalidUserPoolConfigurationException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when a user exceeds the limit for a requested Amazon +// Web Services resource. +type LimitExceededException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *LimitExceededException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *LimitExceededException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *LimitExceededException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "LimitExceededException" + } + return *e.ErrorCodeOverride +} +func (e *LimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when you attempt to apply a managed login branding +// style to an app client that already has an assigned style. +type ManagedLoginBrandingExistsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ManagedLoginBrandingExistsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ManagedLoginBrandingExistsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ManagedLoginBrandingExistsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ManagedLoginBrandingExistsException" + } + return *e.ErrorCodeOverride +} +func (e *ManagedLoginBrandingExistsException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when Amazon Cognito can't find a multi-factor +// authentication (MFA) method. +type MFAMethodNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *MFAMethodNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *MFAMethodNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *MFAMethodNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "MFAMethodNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *MFAMethodNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a user isn't authorized. +type NotAuthorizedException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *NotAuthorizedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *NotAuthorizedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *NotAuthorizedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "NotAuthorizedException" + } + return *e.ErrorCodeOverride +} +func (e *NotAuthorizedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The message returned when a user's new password matches a previous password and +// doesn't comply with the password-history policy. +type PasswordHistoryPolicyViolationException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *PasswordHistoryPolicyViolationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *PasswordHistoryPolicyViolationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *PasswordHistoryPolicyViolationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "PasswordHistoryPolicyViolationException" + } + return *e.ErrorCodeOverride +} +func (e *PasswordHistoryPolicyViolationException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when a password reset is required. +type PasswordResetRequiredException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *PasswordResetRequiredException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *PasswordResetRequiredException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *PasswordResetRequiredException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "PasswordResetRequiredException" + } + return *e.ErrorCodeOverride +} +func (e *PasswordResetRequiredException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a precondition is not met. +type PreconditionNotMetException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *PreconditionNotMetException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *PreconditionNotMetException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *PreconditionNotMetException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "PreconditionNotMetException" + } + return *e.ErrorCodeOverride +} +func (e *PreconditionNotMetException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is throw when your application requests token refresh with a +// refresh token that has been invalidated by refresh-token rotation. +type RefreshTokenReuseException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *RefreshTokenReuseException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *RefreshTokenReuseException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *RefreshTokenReuseException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "RefreshTokenReuseException" + } + return *e.ErrorCodeOverride +} +func (e *RefreshTokenReuseException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the Amazon Cognito service can't find the +// requested resource. +type ResourceNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ResourceNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ResourceNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ResourceNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *ResourceNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the specified scope doesn't exist. +type ScopeDoesNotExistException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ScopeDoesNotExistException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ScopeDoesNotExistException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ScopeDoesNotExistException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ScopeDoesNotExistException" + } + return *e.ErrorCodeOverride +} +func (e *ScopeDoesNotExistException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the software token time-based one-time password +// (TOTP) multi-factor authentication (MFA) isn't activated for the user pool. +type SoftwareTokenMFANotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *SoftwareTokenMFANotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *SoftwareTokenMFANotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *SoftwareTokenMFANotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "SoftwareTokenMFANotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *SoftwareTokenMFANotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when you've attempted to change your feature plan but +// the operation isn't permitted. +type TierChangeNotAllowedException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *TierChangeNotAllowedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *TierChangeNotAllowedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *TierChangeNotAllowedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "TierChangeNotAllowedException" + } + return *e.ErrorCodeOverride +} +func (e *TierChangeNotAllowedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the user has made too many failed attempts for a +// given action, such as sign-in. +type TooManyFailedAttemptsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *TooManyFailedAttemptsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *TooManyFailedAttemptsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *TooManyFailedAttemptsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "TooManyFailedAttemptsException" + } + return *e.ErrorCodeOverride +} +func (e *TooManyFailedAttemptsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the user has made too many requests for a given +// operation. +type TooManyRequestsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *TooManyRequestsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *TooManyRequestsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *TooManyRequestsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "TooManyRequestsException" + } + return *e.ErrorCodeOverride +} +func (e *TooManyRequestsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Exception that is thrown when the request isn't authorized. This can happen due +// to an invalid access token in the request. +type UnauthorizedException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnauthorizedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnauthorizedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnauthorizedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnauthorizedException" + } + return *e.ErrorCodeOverride +} +func (e *UnauthorizedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when Amazon Cognito encounters an unexpected exception +// with Lambda. +type UnexpectedLambdaException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnexpectedLambdaException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnexpectedLambdaException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnexpectedLambdaException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnexpectedLambdaException" + } + return *e.ErrorCodeOverride +} +func (e *UnexpectedLambdaException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the specified identifier isn't supported. +type UnsupportedIdentityProviderException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnsupportedIdentityProviderException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnsupportedIdentityProviderException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnsupportedIdentityProviderException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnsupportedIdentityProviderException" + } + return *e.ErrorCodeOverride +} +func (e *UnsupportedIdentityProviderException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// Exception that is thrown when you attempt to perform an operation that isn't +// enabled for the user pool client. +type UnsupportedOperationException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnsupportedOperationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnsupportedOperationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnsupportedOperationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnsupportedOperationException" + } + return *e.ErrorCodeOverride +} +func (e *UnsupportedOperationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Exception that is thrown when an unsupported token is passed to an operation. +type UnsupportedTokenTypeException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnsupportedTokenTypeException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnsupportedTokenTypeException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnsupportedTokenTypeException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnsupportedTokenTypeException" + } + return *e.ErrorCodeOverride +} +func (e *UnsupportedTokenTypeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The request failed because the user is in an unsupported state. +type UnsupportedUserStateException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UnsupportedUserStateException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UnsupportedUserStateException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UnsupportedUserStateException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UnsupportedUserStateException" + } + return *e.ErrorCodeOverride +} +func (e *UnsupportedUserStateException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when you're trying to modify a user pool while a user +// import job is in progress for that pool. +type UserImportInProgressException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UserImportInProgressException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UserImportInProgressException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UserImportInProgressException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UserImportInProgressException" + } + return *e.ErrorCodeOverride +} +func (e *UserImportInProgressException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the Amazon Cognito service encounters a user +// validation exception with the Lambda service. +type UserLambdaValidationException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UserLambdaValidationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UserLambdaValidationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UserLambdaValidationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UserLambdaValidationException" + } + return *e.ErrorCodeOverride +} +func (e *UserLambdaValidationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when Amazon Cognito encounters a user name that +// already exists in the user pool. +type UsernameExistsException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UsernameExistsException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UsernameExistsException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UsernameExistsException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UsernameExistsException" + } + return *e.ErrorCodeOverride +} +func (e *UsernameExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a user isn't confirmed successfully. +type UserNotConfirmedException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UserNotConfirmedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UserNotConfirmedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UserNotConfirmedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UserNotConfirmedException" + } + return *e.ErrorCodeOverride +} +func (e *UserNotConfirmedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a user isn't found. +type UserNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UserNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UserNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UserNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UserNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *UserNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when user pool add-ons aren't enabled. +type UserPoolAddOnNotEnabledException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UserPoolAddOnNotEnabledException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UserPoolAddOnNotEnabledException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UserPoolAddOnNotEnabledException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UserPoolAddOnNotEnabledException" + } + return *e.ErrorCodeOverride +} +func (e *UserPoolAddOnNotEnabledException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a user pool tag can't be set or updated. +type UserPoolTaggingException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *UserPoolTaggingException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *UserPoolTaggingException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *UserPoolTaggingException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "UserPoolTaggingException" + } + return *e.ErrorCodeOverride +} +func (e *UserPoolTaggingException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the challenge from StartWebAuthn registration has +// expired. +type WebAuthnChallengeNotFoundException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnChallengeNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnChallengeNotFoundException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnChallengeNotFoundException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnChallengeNotFoundException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnChallengeNotFoundException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when the access token is for a different client than +// the one in the original StartWebAuthnRegistration request. +type WebAuthnClientMismatchException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnClientMismatchException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnClientMismatchException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnClientMismatchException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnClientMismatchException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnClientMismatchException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when a user pool doesn't have a configured relying +// party id or a user pool domain. +type WebAuthnConfigurationMissingException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnConfigurationMissingException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnConfigurationMissingException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnConfigurationMissingException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnConfigurationMissingException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnConfigurationMissingException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when a user presents passkey credentials from an +// unsupported device or provider. +type WebAuthnCredentialNotSupportedException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnCredentialNotSupportedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnCredentialNotSupportedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnCredentialNotSupportedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnCredentialNotSupportedException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnCredentialNotSupportedException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + +// This exception is thrown when the passkey feature isn't enabled for the user +// pool. +type WebAuthnNotEnabledException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnNotEnabledException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnNotEnabledException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnNotEnabledException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnNotEnabledException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnNotEnabledException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the passkey credential's registration origin does +// not align with the user pool relying party id. +type WebAuthnOriginNotAllowedException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnOriginNotAllowedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnOriginNotAllowedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnOriginNotAllowedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnOriginNotAllowedException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnOriginNotAllowedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// This exception is thrown when the given passkey credential is associated with a +// different relying party ID than the user pool relying party ID. +type WebAuthnRelyingPartyMismatchException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *WebAuthnRelyingPartyMismatchException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *WebAuthnRelyingPartyMismatchException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *WebAuthnRelyingPartyMismatchException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "WebAuthnRelyingPartyMismatchException" + } + return *e.ErrorCodeOverride +} +func (e *WebAuthnRelyingPartyMismatchException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/types.go new file mode 100644 index 00000000..63db9dcc --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types/types.go @@ -0,0 +1,2873 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +import ( + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document" + smithydocument "github.com/aws/smithy-go/document" + "time" +) + +// The settings for user message delivery in forgot-password operations. Contains +// preference for email or SMS message delivery of password reset codes, or for +// admin-only password reset. +type AccountRecoverySettingType struct { + + // The list of options and priorities for user message delivery in forgot-password + // operations. Sets or displays user pool preferences for email or SMS message + // priority, whether users should fall back to a second delivery method, and + // whether passwords should only be reset by administrators. + RecoveryMechanisms []RecoveryOptionType + + noSmithyDocumentSerde +} + +// A list of account-takeover actions for each level of risk that Amazon Cognito +// might assess with threat protection features. +type AccountTakeoverActionsType struct { + + // The action that you assign to a high-risk assessment by threat protection. + HighAction *AccountTakeoverActionType + + // The action that you assign to a low-risk assessment by threat protection. + LowAction *AccountTakeoverActionType + + // The action that you assign to a medium-risk assessment by threat protection. + MediumAction *AccountTakeoverActionType + + noSmithyDocumentSerde +} + +// The automated response to a risk level for adaptive authentication in +// full-function, or ENFORCED , mode. You can assign an action to each risk level +// that threat protection evaluates. +type AccountTakeoverActionType struct { + + // The action to take for the attempted account takeover action for the associated + // risk level. Valid values are as follows: + // + // - BLOCK : Block the request. + // + // - MFA_IF_CONFIGURED : Present an MFA challenge if possible. MFA is possible if + // the user pool has active MFA methods that the user can set up. For example, if + // the user pool only supports SMS message MFA but the user doesn't have a phone + // number attribute, MFA setup isn't possible. If MFA setup isn't possible, allow + // the request. + // + // - MFA_REQUIRED : Present an MFA challenge if possible. Block the request if a + // user hasn't set up MFA. To sign in with required MFA, users must have an email + // address or phone number attribute, or a registered TOTP factor. + // + // - NO_ACTION : Take no action. Permit sign-in. + // + // This member is required. + EventAction AccountTakeoverEventActionType + + // Determines whether Amazon Cognito sends a user a notification message when your + // user pools assesses a user's session at the associated risk level. + // + // This member is required. + Notify bool + + noSmithyDocumentSerde +} + +// The settings for automated responses and notification templates for adaptive +// authentication with threat protection features. +type AccountTakeoverRiskConfigurationType struct { + + // A list of account-takeover actions for each level of risk that Amazon Cognito + // might assess with threat protection. + // + // This member is required. + Actions *AccountTakeoverActionsType + + // The settings for composing and sending an email message when threat protection + // assesses a risk level with adaptive authentication. When you choose to notify + // users in AccountTakeoverRiskConfiguration , Amazon Cognito sends an email + // message using the method and template that you set with this data type. + NotifyConfiguration *NotifyConfigurationType + + noSmithyDocumentSerde +} + +// The settings for administrator creation of users in a user pool. Contains +// settings for allowing user sign-up, customizing invitation messages to new +// users, and the amount of time before temporary passwords expire. +type AdminCreateUserConfigType struct { + + // The setting for allowing self-service sign-up. When true , only administrators + // can create new user profiles. When false , users can register themselves and + // create a new user profile with the SignUp operation. + AllowAdminCreateUserOnly bool + + // The template for the welcome message to new users. This template must include + // the {####} temporary password placeholder if you are creating users with + // passwords. If your users don't have passwords, you can omit the placeholder. + // + // See also [Customizing User Invitation Messages]. + // + // [Customizing User Invitation Messages]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-customizations.html#cognito-user-pool-settings-user-invitation-message-customization + InviteMessageTemplate *MessageTemplateType + + // This parameter is no longer in use. + // + // The password expiration limit in days for administrator-created users. When + // this time expires, the user can't sign in with their temporary password. To + // reset the account after that time limit, you must call AdminCreateUser again, + // specifying RESEND for the MessageAction parameter. + // + // The default value for this parameter is 7. + UnusedAccountValidityDays int32 + + noSmithyDocumentSerde +} + +// Threat protection configuration options for additional authentication types in +// your user pool, including custom authentication. +type AdvancedSecurityAdditionalFlowsType struct { + + // The operating mode of threat protection in custom authentication with [Custom authentication challenge Lambda triggers]. + // + // [Custom authentication challenge Lambda triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html + CustomAuthMode AdvancedSecurityEnabledModeType + + noSmithyDocumentSerde +} + +// The settings for Amazon Pinpoint analytics configuration. With an analytics +// configuration, your application can collect user-activity metrics for user +// notifications with a Amazon Pinpoint campaign. +// +// Amazon Pinpoint isn't available in all Amazon Web Services Regions. For a list +// of available Regions, see [Amazon Cognito and Amazon Pinpoint Region availability]. +// +// [Amazon Cognito and Amazon Pinpoint Region availability]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html#cognito-user-pools-find-region-mappings +type AnalyticsConfigurationType struct { + + // The Amazon Resource Name (ARN) of an Amazon Pinpoint project that you want to + // connect to your user pool app client. Amazon Cognito publishes events to the + // Amazon Pinpoint project that ApplicationArn declares. You can also configure + // your application to pass an endpoint ID in the AnalyticsMetadata parameter of + // sign-in operations. The endpoint ID is information about the destination for + // push notifications + ApplicationArn *string + + // Your Amazon Pinpoint project ID. + ApplicationId *string + + // The [external ID] of the role that Amazon Cognito assumes to send analytics data to Amazon + // Pinpoint. + // + // [external ID]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html + ExternalId *string + + // The ARN of an Identity and Access Management role that has the permissions + // required for Amazon Cognito to publish events to Amazon Pinpoint analytics. + RoleArn *string + + // If UserDataShared is true , Amazon Cognito includes user data in the events that + // it publishes to Amazon Pinpoint analytics. + UserDataShared bool + + noSmithyDocumentSerde +} + +// Information that your application adds to authentication requests. Applies an +// endpoint ID to the analytics data that your user pool sends to Amazon Pinpoint. +// +// An endpoint ID uniquely identifies a mobile device, email address or phone +// number that can receive messages from Amazon Pinpoint analytics. For more +// information about Amazon Web Services Regions that can contain Amazon Pinpoint +// resources for use with Amazon Cognito user pools, see [Using Amazon Pinpoint analytics with Amazon Cognito user pools]. +// +// [Using Amazon Pinpoint analytics with Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html +type AnalyticsMetadataType struct { + + // The endpoint ID. Information that you want to pass to Amazon Pinpoint about + // where to send notifications. + AnalyticsEndpointId *string + + noSmithyDocumentSerde +} + +// An image file from a managed login branding style in a user pool. +type AssetType struct { + + // The category that the image corresponds to in your managed login configuration. + // Managed login has asset categories for different types of logos, backgrounds, + // and icons. + // + // This member is required. + Category AssetCategoryType + + // The display-mode target of the asset: light, dark, or browser-adaptive. For + // example, Amazon Cognito displays a dark-mode image only when the browser or + // application is in dark mode, but displays a browser-adaptive file in all + // contexts. + // + // This member is required. + ColorMode ColorSchemeModeType + + // The file type of the image file. + // + // This member is required. + Extension AssetExtensionType + + // The image file, in Base64-encoded binary. + Bytes []byte + + // The ID of the asset. + ResourceId *string + + noSmithyDocumentSerde +} + +// The name and value of a user attribute. +type AttributeType struct { + + // The name of the attribute. + // + // This member is required. + Name *string + + // The value of the attribute. + Value *string + + noSmithyDocumentSerde +} + +// The object that your application receives after authentication. Contains tokens +// and information for device authentication. +type AuthenticationResultType struct { + + // Your user's access token. + AccessToken *string + + // The expiration period of the authentication result in seconds. + ExpiresIn int32 + + // Your user's ID token. + IdToken *string + + // The new device metadata from an authentication result. + NewDeviceMetadata *NewDeviceMetadataType + + // Your user's refresh token. + RefreshToken *string + + // The intended use of the token, for example Bearer . + TokenType *string + + noSmithyDocumentSerde +} + +// One authentication event that Amazon Cognito logged in a user pool with threat +// protection active. Contains user and device metadata and a risk assessment from +// your user pool. +type AuthEventType struct { + + // A list of the challenges that the user was requested to answer, for example + // Password , and the result, for example Success . + ChallengeResponses []ChallengeResponseType + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // The user context data captured at the time of an event request. This value + // provides additional information about the client from which event the request is + // received. + EventContextData *EventContextDataType + + // The UpdateAuthEventFeedback or AdminUpdateAuthEventFeedback feedback that you + // or your user provided in response to the event. A value of Valid indicates that + // you disagreed with the level of risk that your user pool assigned, and evaluated + // a session to be valid, or likely safe. A value of Invalid indicates that you + // agreed with the user pool risk level and evaluated a session to be invalid, or + // likely malicious. + EventFeedback *EventFeedbackType + + // The event ID. + EventId *string + + // The event response. + EventResponse EventResponseType + + // The threat evaluation from your user pool about an event. Contains information + // about whether your user pool detected compromised credentials, whether the event + // triggered an automated response, and the level of risk. + EventRisk *EventRiskType + + // The type of authentication event. + EventType EventType + + noSmithyDocumentSerde +} + +// The responses to the challenge that you received in the previous request. Each +// challenge has its own required response parameters. The following examples are +// partial JSON request bodies that highlight challenge-response parameters. +// +// You must provide a SECRET_HASH parameter in all challenge responses to an app +// client that has a client secret. Include a DEVICE_KEY for device authentication. +// +// SELECT_CHALLENGE "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { +// "USERNAME": "[username]", "ANSWER": "[Challenge name]"} +// +// Available challenges are PASSWORD , PASSWORD_SRP , EMAIL_OTP , SMS_OTP , and +// WEB_AUTHN . +// +// Complete authentication in the SELECT_CHALLENGE response for PASSWORD , +// PASSWORD_SRP , and WEB_AUTHN : +// +// - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": +// "WEB_AUTHN", "USERNAME": "[username]", "CREDENTIAL": +// "[AuthenticationResponseJSON]"} +// +// See [AuthenticationResponseJSON]. +// +// - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": +// "PASSWORD", "USERNAME": "[username]", "PASSWORD": "[password]"} +// +// - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": +// "PASSWORD_SRP", "USERNAME": "[username]", "SRP_A": "[SRP_A]"} +// +// For SMS_OTP and EMAIL_OTP , respond with the username and answer. Your user pool +// will send a code for the user to submit in the next challenge response. +// +// - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": +// "SMS_OTP", "USERNAME": "[username]"} +// +// - "ChallengeName": "SELECT_CHALLENGE", "ChallengeResponses": { "ANSWER": +// "EMAIL_OTP", "USERNAME": "[username]"} +// +// SMS_OTP "ChallengeName": "SMS_OTP", "ChallengeResponses": {"SMS_OTP_CODE": +// "[code]", "USERNAME": "[username]"} +// +// EMAIL_OTP "ChallengeName": "EMAIL_OTP", "ChallengeResponses": +// {"EMAIL_OTP_CODE": "[code]", "USERNAME": "[username]"} +// +// SMS_MFA "ChallengeName": "SMS_MFA", "ChallengeResponses": {"SMS_MFA_CODE": +// "[code]", "USERNAME": "[username]"} +// +// PASSWORD_VERIFIER This challenge response is part of the SRP flow. Amazon +// Cognito requires that your application respond to this challenge within a few +// seconds. When the response time exceeds this period, your user pool returns a +// NotAuthorizedException error. +// +// "ChallengeName": "PASSWORD_VERIFIER", "ChallengeResponses": +// {"PASSWORD_CLAIM_SIGNATURE": "[claim_signature]", "PASSWORD_CLAIM_SECRET_BLOCK": +// "[secret_block]", "TIMESTAMP": [timestamp], "USERNAME": "[username]"} +// +// Add "DEVICE_KEY" when you sign in with a remembered device. +// +// CUSTOM_CHALLENGE "ChallengeName": "CUSTOM_CHALLENGE", "ChallengeResponses": +// {"USERNAME": "[username]", "ANSWER": "[challenge_answer]"} +// +// Add "DEVICE_KEY" when you sign in with a remembered device. +// +// NEW_PASSWORD_REQUIRED "ChallengeName": "NEW_PASSWORD_REQUIRED", +// "ChallengeResponses": {"NEW_PASSWORD": "[new_password]", "USERNAME": +// "[username]"} +// +// To set any required attributes that InitiateAuth returned in an +// requiredAttributes parameter, add "userAttributes.[attribute_name]": +// "[attribute_value]" . This parameter can also set values for writable attributes +// that aren't required by your user pool. +// +// In a NEW_PASSWORD_REQUIRED challenge response, you can't modify a required +// attribute that already has a value. In AdminRespondToAuthChallenge or +// RespondToAuthChallenge , set a value for any keys that Amazon Cognito returned +// in the requiredAttributes parameter, then use the AdminUpdateUserAttributes or +// UpdateUserAttributes API operation to modify the value of any additional +// attributes. +// +// SOFTWARE_TOKEN_MFA "ChallengeName": "SOFTWARE_TOKEN_MFA", "ChallengeResponses": +// {"USERNAME": "[username]", "SOFTWARE_TOKEN_MFA_CODE": [authenticator_code]} +// +// DEVICE_SRP_AUTH "ChallengeName": "DEVICE_SRP_AUTH", "ChallengeResponses": +// {"USERNAME": "[username]", "DEVICE_KEY": "[device_key]", "SRP_A": "[srp_a]"} +// +// DEVICE_PASSWORD_VERIFIER "ChallengeName": "DEVICE_PASSWORD_VERIFIER", +// "ChallengeResponses": {"DEVICE_KEY": "[device_key]", "PASSWORD_CLAIM_SIGNATURE": +// "[claim_signature]", "PASSWORD_CLAIM_SECRET_BLOCK": "[secret_block]", +// "TIMESTAMP": [timestamp], "USERNAME": "[username]"} +// +// MFA_SETUP "ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": +// "[username]"}, "SESSION": "[Session ID from VerifySoftwareToken]" +// +// SELECT_MFA_TYPE "ChallengeName": "SELECT_MFA_TYPE", "ChallengeResponses": +// {"USERNAME": "[username]", "ANSWER": "[SMS_MFA or SOFTWARE_TOKEN_MFA]"} +// +// For more information about SECRET_HASH , see [Computing secret hash values]. For information about DEVICE_KEY +// , see [Working with user devices in your user pool]. +// +// [Computing secret hash values]: https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash +// [AuthenticationResponseJSON]: https://www.w3.org/TR/WebAuthn-3/#dictdef-authenticationresponsejson +// [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +type ChallengeResponseType struct { + + // The type of challenge that your previous authentication request returned in the + // parameter ChallengeName , for example SMS_MFA . + ChallengeName ChallengeName + + // The set of key-value pairs that provides a response to the requested challenge. + ChallengeResponse ChallengeResponse + + noSmithyDocumentSerde +} + +// Configuration for the CloudWatch log group destination of user pool detailed +// activity logging, or of user activity log export with threat protection. +type CloudWatchLogsConfigurationType struct { + + // The Amazon Resource Name (arn) of a CloudWatch Logs log group where your user + // pool sends logs. The log group must not be encrypted with Key Management Service + // and must be in the same Amazon Web Services account as your user pool. + // + // To send logs to log groups with a resource policy of a size greater than 5120 + // characters, configure a log group with a path that starts with /aws/vendedlogs . + // For more information, see [Enabling logging from certain Amazon Web Services services]. + // + // [Enabling logging from certain Amazon Web Services services]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html + LogGroupArn *string + + noSmithyDocumentSerde +} + +// The delivery details for an email or SMS message that Amazon Cognito sent for +// authentication or verification. +type CodeDeliveryDetailsType struct { + + // The name of the attribute that Amazon Cognito verifies with the code. + AttributeName *string + + // The method that Amazon Cognito used to send the code. + DeliveryMedium DeliveryMediumType + + // The email address or phone number destination where Amazon Cognito sent the + // code. + Destination *string + + noSmithyDocumentSerde +} + +// Settings for user pool actions when Amazon Cognito detects compromised +// credentials with threat protection in full-function ENFORCED mode. +type CompromisedCredentialsActionsType struct { + + // The action that Amazon Cognito takes when it detects compromised credentials. + // + // This member is required. + EventAction CompromisedCredentialsEventActionType + + noSmithyDocumentSerde +} + +// Settings for compromised-credentials actions and authentication-event sources +// with threat protection in full-function ENFORCED mode. +type CompromisedCredentialsRiskConfigurationType struct { + + // Settings for the actions that you want your user pool to take when Amazon + // Cognito detects compromised credentials. + // + // This member is required. + Actions *CompromisedCredentialsActionsType + + // Settings for the sign-in activity where you want to configure + // compromised-credentials actions. Defaults to all events. + EventFilter []EventFilterType + + noSmithyDocumentSerde +} + +// Contextual user data used for evaluating the risk of an authentication event by +// user pool threat protection. +type ContextDataType struct { + + // The HTTP headers from your user's authentication request. + // + // This member is required. + HttpHeaders []HttpHeader + + // The source IP address of your user's device. + // + // This member is required. + IpAddress *string + + // The name of your application's service endpoint. + // + // This member is required. + ServerName *string + + // The path of your application's service endpoint. + // + // This member is required. + ServerPath *string + + // Encoded device-fingerprint details that your app collected with the Amazon + // Cognito context data collection library. For more information, see [Adding user device and session data to API requests]. + // + // [Adding user device and session data to API requests]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-device-fingerprint + EncodedData *string + + noSmithyDocumentSerde +} + +// The configuration for a hosted UI custom domain. +type CustomDomainConfigType struct { + + // The Amazon Resource Name (ARN) of an Certificate Manager SSL certificate. You + // use this certificate for the subdomain of your custom domain. + // + // This member is required. + CertificateArn *string + + noSmithyDocumentSerde +} + +// The properties of a custom email sender Lambda trigger. +type CustomEmailLambdaVersionConfigType struct { + + // The Amazon Resource Name (ARN) of the function that you want to assign to your + // Lambda trigger. + // + // This member is required. + LambdaArn *string + + // The user pool trigger version of the request that Amazon Cognito sends to your + // Lambda function. Higher-numbered versions add fields that support new features. + // + // You must use a LambdaVersion of V1_0 with a custom sender function. + // + // This member is required. + LambdaVersion CustomEmailSenderLambdaVersionType + + noSmithyDocumentSerde +} + +// The properties of a custom SMS sender Lambda trigger. +type CustomSMSLambdaVersionConfigType struct { + + // The Amazon Resource Name (ARN) of the function that you want to assign to your + // Lambda trigger. + // + // This member is required. + LambdaArn *string + + // The user pool trigger version of the request that Amazon Cognito sends to your + // Lambda function. Higher-numbered versions add fields that support new features. + // + // You must use a LambdaVersion of V1_0 with a custom sender function. + // + // This member is required. + LambdaVersion CustomSMSSenderLambdaVersionType + + noSmithyDocumentSerde +} + +// The device-remembering configuration for a user pool. +// +// When you provide a value for any property of DeviceConfiguration , you activate +// the device remembering for the user pool. +type DeviceConfigurationType struct { + + // When true, a remembered device can sign in with device authentication instead + // of SMS and time-based one-time password (TOTP) factors for multi-factor + // authentication (MFA). + // + // Whether or not ChallengeRequiredOnNewDevice is true, users who sign in with + // devices that have not been confirmed or remembered must still provide a second + // factor in a user pool that requires MFA. + ChallengeRequiredOnNewDevice bool + + // When true, Amazon Cognito doesn't automatically remember a user's device when + // your app sends a ConfirmDevice API request. In your app, create a prompt for + // your user to choose whether they want to remember their device. Return the + // user's choice in an UpdateDeviceStatus API request. + // + // When DeviceOnlyRememberedOnUserPrompt is false , Amazon Cognito immediately + // remembers devices that you register in a ConfirmDevice API request. + DeviceOnlyRememberedOnUserPrompt bool + + noSmithyDocumentSerde +} + +// A Secure Remote Password (SRP) value that your application generates when you +// register a user's device. For more information, see [Getting a device key]. +// +// [Getting a device key]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html#user-pools-remembered-devices-getting-a-device-key +type DeviceSecretVerifierConfigType struct { + + // A password verifier for a user's device. Used in SRP authentication. + PasswordVerifier *string + + // The salt that you want to use in SRP authentication with the user's device. + Salt *string + + noSmithyDocumentSerde +} + +// Information about a user's device that they've registered for device SRP +// authentication in your application. For more information, see [Working with user devices in your user pool]. +// +// [Working with user devices in your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +type DeviceType struct { + + // Metadata about a user's device, like name and last-access source IP. + DeviceAttributes []AttributeType + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + DeviceCreateDate *time.Time + + // The device key, for example + // us-west-2_EXAMPLE-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 . + DeviceKey *string + + // The date when the user last signed in with the device. + DeviceLastAuthenticatedDate *time.Time + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + DeviceLastModifiedDate *time.Time + + noSmithyDocumentSerde +} + +// A container for information about the user pool domain associated with the +// hosted UI and OAuth endpoints. +type DomainDescriptionType struct { + + // The Amazon Web Services account that you created the user pool in. + AWSAccountId *string + + // The Amazon CloudFront endpoint that hosts your custom domain. + CloudFrontDistribution *string + + // The configuration for a custom domain that hosts the sign-up and sign-in + // webpages for your application. + CustomDomainConfig *CustomDomainConfigType + + // The domain string. For custom domains, this is the fully-qualified domain name, + // such as auth.example.com . For Amazon Cognito prefix domains, this is the prefix + // alone, such as auth . + Domain *string + + // The version of managed login branding that you want to apply to your domain. A + // value of 1 indicates hosted UI (classic) branding and a version of 2 indicates + // managed login branding. + // + // Managed login requires that your user pool be configured for any [feature plan] other than + // Lite . + // + // [feature plan]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sign-in-feature-plans.html + ManagedLoginVersion *int32 + + // The Amazon S3 bucket where the static files for this domain are stored. + S3Bucket *string + + // The domain status. + Status DomainStatusType + + // The ID of the user pool that the domain is attached to. + UserPoolId *string + + // The app version. + Version *string + + noSmithyDocumentSerde +} + +// The email configuration of your user pool. The email configuration type sets +// your preferred sending method, Amazon Web Services Region, and sender for +// messages from your user pool. +// +// Amazon Cognito can send email messages with Amazon Simple Email Service +// resources in the Amazon Web Services Region where you created your user pool, +// and in alternate Regions in some cases. For more information on the supported +// Regions, see [Email settings for Amazon Cognito user pools]. +// +// [Email settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html +type EmailConfigurationType struct { + + // The set of configuration rules that can be applied to emails sent using Amazon + // Simple Email Service. A configuration set is applied to an email by including a + // reference to the configuration set in the headers of the email. Once applied, + // all of the rules in that configuration set are applied to the email. + // Configuration sets can be used to apply the following types of rules to emails: + // + // Event publishing Amazon Simple Email Service can track the number of send, + // delivery, open, click, bounce, and complaint events for each email sent. Use + // event publishing to send information about these events to other Amazon Web + // Services services such as and Amazon CloudWatch + // + // IP pool management When leasing dedicated IP addresses with Amazon Simple Email + // Service, you can create groups of IP addresses, called dedicated IP pools. You + // can then associate the dedicated IP pools with configuration sets. + ConfigurationSet *string + + // Specifies whether Amazon Cognito uses its built-in functionality to send your + // users email messages, or uses your Amazon Simple Email Service email + // configuration. Specify one of the following values: + // + // COGNITO_DEFAULT When Amazon Cognito emails your users, it uses its built-in + // email functionality. When you use the default option, Amazon Cognito allows only + // a limited number of emails each day for your user pool. For typical production + // environments, the default email limit is less than the required delivery volume. + // To achieve a higher delivery volume, specify DEVELOPER to use your Amazon SES + // email configuration. + // + // To look up the email delivery limit for the default option, see [Limits] in the Amazon + // Cognito Developer Guide. + // + // The default FROM address is no-reply@verificationemail.com . To customize the + // FROM address, provide the Amazon Resource Name (ARN) of an Amazon SES verified + // email address for the SourceArn parameter. + // + // DEVELOPER When Amazon Cognito emails your users, it uses your Amazon SES + // configuration. Amazon Cognito calls Amazon SES on your behalf to send email from + // your verified email address. When you use this option, the email delivery limits + // are the same limits that apply to your Amazon SES verified email address in your + // Amazon Web Services account. + // + // If you use this option, provide the ARN of an Amazon SES verified email address + // for the SourceArn parameter. + // + // Before Amazon Cognito can email your users, it requires additional permissions + // to call Amazon SES on your behalf. When you update your user pool with this + // option, Amazon Cognito creates a service-linked role, which is a type of role in + // your Amazon Web Services account. This role contains the permissions that allow + // you to access Amazon SES and send email messages from your email address. For + // more information about the service-linked role that Amazon Cognito creates, see [Using Service-Linked Roles for Amazon Cognito] + // in the Amazon Cognito Developer Guide. + // + // [Limits]: https://docs.aws.amazon.com/cognito/latest/developerguide/limits.html + // [Using Service-Linked Roles for Amazon Cognito]: https://docs.aws.amazon.com/cognito/latest/developerguide/using-service-linked-roles.html + EmailSendingAccount EmailSendingAccountType + + // Either the sender’s email address or the sender’s name with their email + // address. For example, testuser@example.com or Test User . This address appears + // before the body of the email. + From *string + + // The destination to which the receiver of the email should reply. + ReplyToEmailAddress *string + + // The ARN of a verified email address or an address from a verified domain in + // Amazon SES. You can set a SourceArn email from a verified domain only with an + // API request. You can set a verified email address, but not an address in a + // verified domain, in the Amazon Cognito console. Amazon Cognito uses the email + // address that you provide in one of the following ways, depending on the value + // that you specify for the EmailSendingAccount parameter: + // + // - If you specify COGNITO_DEFAULT , Amazon Cognito uses this address as the + // custom FROM address when it emails your users using its built-in email account. + // + // - If you specify DEVELOPER , Amazon Cognito emails your users with this + // address by calling Amazon SES on your behalf. + // + // The Region value of the SourceArn parameter must indicate a supported Amazon + // Web Services Region of your user pool. Typically, the Region in the SourceArn + // and the user pool Region are the same. For more information, see [Amazon SES email configuration regions]in the [Amazon Cognito Developer Guide]. + // + // [Amazon SES email configuration regions]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html#user-pool-email-developer-region-mapping + // [Amazon Cognito Developer Guide]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html + SourceArn *string + + noSmithyDocumentSerde +} + +// Sets or shows configuration for user pool email message MFA and sign-in with +// one-time passwords (OTPs). Includes the subject and body of the email message +// template for sign-in and MFA messages. To activate this setting, your user pool +// must be in the [Essentials tier]or higher. +// +// [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html +type EmailMfaConfigType struct { + + // The template for the email messages that your user pool sends to users with + // codes for MFA and sign-in with email OTPs. The message must contain the {####} + // placeholder. In the message, Amazon Cognito replaces this placeholder with the + // code. If you don't provide this parameter, Amazon Cognito sends messages in the + // default format. + Message *string + + // The subject of the email messages that your user pool sends to users with codes + // for MFA and email OTP sign-in. + Subject *string + + noSmithyDocumentSerde +} + +// User preferences for multi-factor authentication with email messages. Activates +// or deactivates email MFA and sets it as the preferred MFA method when multiple +// methods are available. To activate this setting, your user pool must be in the [Essentials tier] +// or higher. +// +// [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html +type EmailMfaSettingsType struct { + + // Specifies whether email message MFA is active for a user. When the value of + // this parameter is Enabled , the user will be prompted for MFA during all sign-in + // attempts, unless device tracking is turned on and the device has been trusted. + Enabled bool + + // Specifies whether email message MFA is the user's preferred method. + PreferredMfa bool + + noSmithyDocumentSerde +} + +// The context data that your application submitted in an authentication request +// with threat protection, as displayed in an AdminListUserAuthEvents response. +type EventContextDataType struct { + + // The user's city. + City *string + + // The user's country. + Country *string + + // The user's device name. + DeviceName *string + + // The source IP address of your user's device. + IpAddress *string + + // The user's time zone. + Timezone *string + + noSmithyDocumentSerde +} + +// The feedback that your application submitted to a threat protection event log, +// as displayed in an AdminListUserAuthEvents response. +type EventFeedbackType struct { + + // Your feedback to the authentication event. When you provide a FeedbackValue + // value of valid , you tell Amazon Cognito that you trust a user session where + // Amazon Cognito has evaluated some level of risk. When you provide a + // FeedbackValue value of invalid , you tell Amazon Cognito that you don't trust a + // user session, or you don't believe that Amazon Cognito evaluated a high-enough + // risk level. + // + // This member is required. + FeedbackValue FeedbackValueType + + // The submitter of the event feedback. For example, if you submit event feedback + // in the Amazon Cognito console, this value is Admin . + // + // This member is required. + Provider *string + + // The date that you or your user submitted the feedback. + FeedbackDate *time.Time + + noSmithyDocumentSerde +} + +// The risk evaluation by adaptive authentication, as displayed in an +// AdminListUserAuthEvents response. Contains evaluations of +// compromised-credentials detection and assessed risk level and action taken by +// adaptive authentication. +type EventRiskType struct { + + // Indicates whether compromised credentials were detected during an + // authentication event. + CompromisedCredentialsDetected *bool + + // The action taken by adaptive authentication. If NoRisk , your user pool took no + // action. If AccountTakeover , your user pool applied the adaptive authentication + // automated response that you configured. If Block , your user pool prevented the + // attempt. + RiskDecision RiskDecisionType + + // The risk level that adaptive authentication assessed for the authentication + // event. + RiskLevel RiskLevelType + + noSmithyDocumentSerde +} + +// Configuration for the Amazon Data Firehose stream destination of user activity +// log export with threat protection. +type FirehoseConfigurationType struct { + + // The ARN of an Amazon Data Firehose stream that's the destination for threat + // protection log export. + StreamArn *string + + noSmithyDocumentSerde +} + +// A user pool group. Contains details about the group and the way that it +// contributes to IAM role decisions with identity pools. Identity pools can make +// decisions about the IAM role to assign based on groups: users get credentials +// for the role associated with their highest-priority group. +type GroupType struct { + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // A friendly description of the group. + Description *string + + // The name of the group. + GroupName *string + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // A non-negative integer value that specifies the precedence of this group + // relative to the other groups that a user can belong to in the user pool. Zero is + // the highest precedence value. Groups with lower Precedence values take + // precedence over groups with higher ornull Precedence values. If a user belongs + // to two or more groups, it is the group with the lowest precedence value whose + // role ARN is given in the user's tokens for the cognito:roles and + // cognito:preferred_role claims. + // + // Two groups can have the same Precedence value. If this happens, neither group + // takes precedence over the other. If two groups with the same Precedence have + // the same role ARN, that role is used in the cognito:preferred_role claim in + // tokens for users in each group. If the two groups have different role ARNs, the + // cognito:preferred_role claim isn't set in users' tokens. + // + // The default Precedence value is null . + Precedence *int32 + + // The ARN of the IAM role associated with the group. If a group has the highest + // priority of a user's groups, users who authenticate with an identity pool get + // credentials for the RoleArn that's associated with the group. + RoleArn *string + + // The ID of the user pool that contains the group. + UserPoolId *string + + noSmithyDocumentSerde +} + +// The HTTP header in the ContextData parameter. +type HttpHeader struct { + + // The header name. + HeaderName *string + + // The header value. + HeaderValue *string + + noSmithyDocumentSerde +} + +// A user pool identity provider (IdP). Contains information about a third-party +// IdP to a user pool, the attributes that it populates to user profiles, and the +// trust relationship between the IdP and your user pool. +type IdentityProviderType struct { + + // A mapping of IdP attributes to standard and custom user pool attributes. + AttributeMapping map[string]string + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // A list of IdP identifiers. IdP identifiers are strings that represent friendly + // names or domain names of IdPs, for example MyIdP or auth.example.com . You can + // choose to route user authorization requests to the right IdP with either IdP + // identifiers or IdP names. For more information, see identity_provider and + // idp_identifier at [Authorize endpoint]. + // + // [Authorize endpoint]: https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html#get-authorize-request-parameters + IdpIdentifiers []string + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // The scopes, URLs, and identifiers for your external identity provider. The + // following examples describe the provider detail keys for each IdP type. These + // values and their schema are subject to change. Social IdP authorize_scopes + // values must match the values listed here. + // + // OpenID Connect (OIDC) Amazon Cognito accepts the following elements when it + // can't discover endpoint URLs from oidc_issuer : attributes_url , authorize_url , + // jwks_uri , token_url . + // + // Create or update request: "ProviderDetails": { "attributes_request_method": + // "GET", "attributes_url": "https://auth.example.com/userInfo", + // "authorize_scopes": "openid profile email", "authorize_url": + // "https://auth.example.com/authorize", "client_id": "1example23456789", + // "client_secret": "provider-app-client-secret", "jwks_uri": + // "https://auth.example.com/.well-known/jwks.json", "oidc_issuer": + // "https://auth.example.com", "token_url": "https://example.com/token" } + // + // Describe response: "ProviderDetails": { "attributes_request_method": "GET", + // "attributes_url": "https://auth.example.com/userInfo", + // "attributes_url_add_attributes": "false", "authorize_scopes": "openid profile + // email", "authorize_url": "https://auth.example.com/authorize", "client_id": + // "1example23456789", "client_secret": "provider-app-client-secret", "jwks_uri": + // "https://auth.example.com/.well-known/jwks.json", "oidc_issuer": + // "https://auth.example.com", "token_url": "https://example.com/token" } + // + // SAML Create or update request with Metadata URL: "ProviderDetails": { + // "IDPInit": "true", "IDPSignout": "true", "EncryptedResponses" : "true", + // "MetadataURL": "https://auth.example.com/sso/saml/metadata", + // "RequestSigningAlgorithm": "rsa-sha256" } + // + // Create or update request with Metadata file: "ProviderDetails": { "IDPInit": + // "true", "IDPSignout": "true", "EncryptedResponses" : "true", "MetadataFile": + // "[metadata XML]", "RequestSigningAlgorithm": "rsa-sha256" } + // + // The value of MetadataFile must be the plaintext metadata document with all + // quote (") characters escaped by backslashes. + // + // Describe response: "ProviderDetails": { "IDPInit": "true", "IDPSignout": + // "true", "EncryptedResponses" : "true", "ActiveEncryptionCertificate": + // "[certificate]", "MetadataURL": "https://auth.example.com/sso/saml/metadata", + // "RequestSigningAlgorithm": "rsa-sha256", "SLORedirectBindingURI": + // "https://auth.example.com/slo/saml", "SSORedirectBindingURI": + // "https://auth.example.com/sso/saml" } + // + // LoginWithAmazon Create or update request: "ProviderDetails": { + // "authorize_scopes": "profile postal_code", "client_id": + // "amzn1.application-oa2-client.1example23456789", "client_secret": + // "provider-app-client-secret" + // + // Describe response: "ProviderDetails": { "attributes_url": + // "https://api.amazon.com/user/profile", "attributes_url_add_attributes": "false", + // "authorize_scopes": "profile postal_code", "authorize_url": + // "https://www.amazon.com/ap/oa", "client_id": + // "amzn1.application-oa2-client.1example23456789", "client_secret": + // "provider-app-client-secret", "token_request_method": "POST", "token_url": + // "https://api.amazon.com/auth/o2/token" } + // + // Google Create or update request: "ProviderDetails": { "authorize_scopes": + // "email profile openid", "client_id": + // "1example23456789.apps.googleusercontent.com", "client_secret": + // "provider-app-client-secret" } + // + // Describe response: "ProviderDetails": { "attributes_url": + // "https://people.googleapis.com/v1/people/me?personFields=", + // "attributes_url_add_attributes": "true", "authorize_scopes": "email profile + // openid", "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth", + // "client_id": "1example23456789.apps.googleusercontent.com", "client_secret": + // "provider-app-client-secret", "oidc_issuer": "https://accounts.google.com", + // "token_request_method": "POST", "token_url": + // "https://www.googleapis.com/oauth2/v4/token" } + // + // SignInWithApple Create or update request: "ProviderDetails": { + // "authorize_scopes": "email name", "client_id": "com.example.cognito", + // "private_key": "1EXAMPLE", "key_id": "2EXAMPLE", "team_id": "3EXAMPLE" } + // + // Describe response: "ProviderDetails": { "attributes_url_add_attributes": + // "false", "authorize_scopes": "email name", "authorize_url": + // "https://appleid.apple.com/auth/authorize", "client_id": "com.example.cognito", + // "key_id": "1EXAMPLE", "oidc_issuer": "https://appleid.apple.com", "team_id": + // "2EXAMPLE", "token_request_method": "POST", "token_url": + // "https://appleid.apple.com/auth/token" } + // + // Facebook Create or update request: "ProviderDetails": { "api_version": "v17.0", + // "authorize_scopes": "public_profile, email", "client_id": "1example23456789", + // "client_secret": "provider-app-client-secret" } + // + // Describe response: "ProviderDetails": { "api_version": "v17.0", + // "attributes_url": "https://graph.facebook.com/v17.0/me?fields=", + // "attributes_url_add_attributes": "true", "authorize_scopes": "public_profile, + // email", "authorize_url": "https://www.facebook.com/v17.0/dialog/oauth", + // "client_id": "1example23456789", "client_secret": "provider-app-client-secret", + // "token_request_method": "GET", "token_url": + // "https://graph.facebook.com/v17.0/oauth/access_token" } + ProviderDetails map[string]string + + // A friendly name for the IdP. + ProviderName *string + + // The type of IdP. Either SAML, OIDC, or a named social identity provider. + ProviderType IdentityProviderTypeType + + // The ID of the user pool associated with the IdP. + UserPoolId *string + + noSmithyDocumentSerde +} + +// A collection of user pool Lambda triggers. Amazon Cognito invokes triggers at +// several possible stages of user pool operations. Triggers can modify the outcome +// of the operations that invoked them. +type LambdaConfigType struct { + + // The configuration of a create auth challenge Lambda trigger, one of three + // triggers in the sequence of the [custom authentication challenge triggers]. + // + // [custom authentication challenge triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html + CreateAuthChallenge *string + + // The configuration of a custom email sender Lambda trigger. This trigger routes + // all email notifications from a user pool to a Lambda function that delivers the + // message using custom logic. + CustomEmailSender *CustomEmailLambdaVersionConfigType + + // A custom message Lambda trigger. This trigger is an opportunity to customize + // all SMS and email messages from your user pool. When a custom message trigger is + // active, your user pool routes all messages to a Lambda function that returns a + // runtime-customized message subject and body for your user pool to deliver to a + // user. + CustomMessage *string + + // The configuration of a custom SMS sender Lambda trigger. This trigger routes + // all SMS notifications from a user pool to a Lambda function that delivers the + // message using custom logic. + CustomSMSSender *CustomSMSLambdaVersionConfigType + + // The configuration of a define auth challenge Lambda trigger, one of three + // triggers in the sequence of the [custom authentication challenge triggers]. + // + // [custom authentication challenge triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html + DefineAuthChallenge *string + + // The ARN of an [KMS key]. Amazon Cognito uses the key to encrypt codes and temporary + // passwords sent to custom sender Lambda triggers. + // + // [KMS key]: https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys + KMSKeyID *string + + // The configuration of a [post authentication Lambda trigger] in a user pool. This trigger can take custom actions + // after a user signs in. + // + // [post authentication Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html + PostAuthentication *string + + // The configuration of a [post confirmation Lambda trigger] in a user pool. This trigger can take custom actions + // after a user confirms their user account and their email address or phone + // number. + // + // [post confirmation Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html + PostConfirmation *string + + // The configuration of a [pre authentication trigger] in a user pool. This trigger can evaluate and modify + // user sign-in events. + // + // [pre authentication trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html + PreAuthentication *string + + // The configuration of a [pre sign-up Lambda trigger] in a user pool. This trigger evaluates new users and + // can bypass confirmation, [link a federated user profile], or block sign-up requests. + // + // [link a federated user profile]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation-consolidate-users.html + // [pre sign-up Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html + PreSignUp *string + + // The legacy configuration of a [pre token generation Lambda trigger] in a user pool. + // + // Set this parameter for legacy purposes. If you also set an ARN in + // PreTokenGenerationConfig , its value must be identical to PreTokenGeneration . + // For new instances of pre token generation triggers, set the LambdaArn of + // PreTokenGenerationConfig . + // + // [pre token generation Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html + PreTokenGeneration *string + + // The detailed configuration of a [pre token generation Lambda trigger] in a user pool. If you also set an ARN in + // PreTokenGeneration , its value must be identical to PreTokenGenerationConfig . + // + // [pre token generation Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html + PreTokenGenerationConfig *PreTokenGenerationVersionConfigType + + // The configuration of a [migrate user Lambda trigger] in a user pool. This trigger can create user profiles + // when users sign in or attempt to reset their password with credentials that + // don't exist yet. + // + // [migrate user Lambda trigger]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html + UserMigration *string + + // The configuration of a verify auth challenge Lambda trigger, one of three + // triggers in the sequence of the [custom authentication challenge triggers]. + // + // [custom authentication challenge triggers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html + VerifyAuthChallengeResponse *string + + noSmithyDocumentSerde +} + +// The configuration of user event logs to an external Amazon Web Services service +// like Amazon Data Firehose, Amazon S3, or Amazon CloudWatch Logs. +type LogConfigurationType struct { + + // The source of events that your user pool sends for logging. To send error-level + // logs about user notification activity, set to userNotification . To send + // info-level logs about threat-protection user activity in user pools with the + // Plus feature plan, set to userAuthEvents . + // + // This member is required. + EventSource EventSourceName + + // The errorlevel selection of logs that a user pool sends for detailed activity + // logging. To send userNotification activity with [information about message delivery], choose ERROR with + // CloudWatchLogsConfiguration . To send userAuthEvents activity with user logs + // from threat protection with the Plus feature plan, choose INFO with one of + // CloudWatchLogsConfiguration , FirehoseConfiguration , or S3Configuration . + // + // [information about message delivery]: https://docs.aws.amazon.com/cognito/latest/developerguide/exporting-quotas-and-usage.html + // + // This member is required. + LogLevel LogLevel + + // The CloudWatch log group destination of user pool detailed activity logs, or of + // user activity log export with threat protection. + CloudWatchLogsConfiguration *CloudWatchLogsConfigurationType + + // The Amazon Data Firehose stream destination of user activity log export with + // threat protection. To activate this setting, your user pool must be on the [Plus tier]. + // + // [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html + FirehoseConfiguration *FirehoseConfigurationType + + // The Amazon S3 bucket destination of user activity log export with threat + // protection. To activate this setting, your user pool must be on the [Plus tier]. + // + // [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html + S3Configuration *S3ConfigurationType + + noSmithyDocumentSerde +} + +// The logging parameters of a user pool, as returned in the response to a +// GetLogDeliveryConfiguration request. +type LogDeliveryConfigurationType struct { + + // A logging destination of a user pool. User pools can have multiple logging + // destinations for message-delivery and user-activity logs. + // + // This member is required. + LogConfigurations []LogConfigurationType + + // The ID of the user pool where you configured logging. + // + // This member is required. + UserPoolId *string + + noSmithyDocumentSerde +} + +// A managed login branding style that's assigned to a user pool app client. +type ManagedLoginBrandingType struct { + + // An array of image files that you want to apply to roles like backgrounds, + // logos, and icons. Each object must also indicate whether it is for dark mode, + // light mode, or browser-adaptive mode. + Assets []AssetType + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // The ID of the managed login branding style. + ManagedLoginBrandingId *string + + // A JSON file, encoded as a Document type, with the the settings that you want to + // apply to your style. + Settings document.Interface + + // When true, applies the default branding style options. This option reverts to + // default style options that are managed by Amazon Cognito. You can modify them + // later in the branding designer. + // + // When you specify true for this option, you must also omit values for Settings + // and Assets in the request. + UseCognitoProvidedValues bool + + // The user pool where the branding style is assigned. + UserPoolId *string + + noSmithyDocumentSerde +} + +// The message template structure. +type MessageTemplateType struct { + + // The message template for email messages. EmailMessage is allowed only if [EmailSendingAccount] is + // DEVELOPER. + // + // [EmailSendingAccount]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html#CognitoUserPools-Type-EmailConfigurationType-EmailSendingAccount + EmailMessage *string + + // The subject line for email messages. EmailSubject is allowed only if [EmailSendingAccount] is + // DEVELOPER. + // + // [EmailSendingAccount]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html#CognitoUserPools-Type-EmailConfigurationType-EmailSendingAccount + EmailSubject *string + + // The message template for SMS messages. + SMSMessage *string + + noSmithyDocumentSerde +} + +// This data type is no longer supported. Applies only to SMS multi-factor +// +// authentication (MFA) configurations. Does not apply to time-based one-time +// password (TOTP) software token MFA configurations. +type MFAOptionType struct { + + // The attribute name of the MFA option type. The only valid value is phone_number . + AttributeName *string + + // The delivery medium to send the MFA code. You can use this parameter to set + // only the SMS delivery medium value. + DeliveryMedium DeliveryMediumType + + noSmithyDocumentSerde +} + +// Information that your user pool responds with in AuthenticationResult when you +// configure it to remember devices and a user signs in with an unrecognized +// device. Amazon Cognito presents a new device key that you can use to set up [device authentication]in +// a "Remember me on this device" authentication model. +// +// [device authentication]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html +type NewDeviceMetadataType struct { + + // The device group key, an identifier used in generating the + // DEVICE_PASSWORD_VERIFIER for device SRP authentication. + DeviceGroupKey *string + + // The device key, an identifier used in generating the DEVICE_PASSWORD_VERIFIER + // for device SRP authentication. + DeviceKey *string + + noSmithyDocumentSerde +} + +// The configuration for Amazon SES email messages that threat protection sends to +// a user when your adaptive authentication automated response has a Notify action. +type NotifyConfigurationType struct { + + // The Amazon Resource Name (ARN) of the identity that is associated with the + // sending authorization policy. This identity permits Amazon Cognito to send for + // the email address specified in the From parameter. + // + // This member is required. + SourceArn *string + + // The template for the email message that your user pool sends when a detected + // risk event is blocked. + BlockEmail *NotifyEmailType + + // The email address that sends the email message. The address must be either + // individually verified with Amazon Simple Email Service, or from a domain that + // has been verified with Amazon SES. + From *string + + // The template for the email message that your user pool sends when MFA is + // challenged in response to a detected risk. + MfaEmail *NotifyEmailType + + // The template for the email message that your user pool sends when no action is + // taken in response to a detected risk. + NoActionEmail *NotifyEmailType + + // The reply-to email address of an email template. + ReplyTo *string + + noSmithyDocumentSerde +} + +// The template for email messages that threat protection sends to a user when +// your threat protection automated response has a Notify action. +type NotifyEmailType struct { + + // The subject of the threat protection email notification. + // + // This member is required. + Subject *string + + // The body of an email notification formatted in HTML. Choose an HtmlBody or a + // TextBody to send an HTML-formatted or plaintext message, respectively. + HtmlBody *string + + // The body of an email notification formatted in plaintext. Choose an HtmlBody or + // a TextBody to send an HTML-formatted or plaintext message, respectively. + TextBody *string + + noSmithyDocumentSerde +} + +// The minimum and maximum values of an attribute that is of the number type, for +// example custom:age . +type NumberAttributeConstraintsType struct { + + // The maximum length of a number attribute value. Must be a number less than or + // equal to 2^1023 , represented as a string with a length of 131072 characters or + // fewer. + MaxValue *string + + // The minimum value of an attribute that is of the number data type. + MinValue *string + + noSmithyDocumentSerde +} + +// The password policy settings for a user pool, including complexity, history, +// and length requirements. +type PasswordPolicyType struct { + + // The minimum length of the password in the policy that you have set. This value + // can't be less than 6. + MinimumLength *int32 + + // The number of previous passwords that you want Amazon Cognito to restrict each + // user from reusing. Users can't set a password that matches any of n previous + // passwords, where n is the value of PasswordHistorySize . + PasswordHistorySize *int32 + + // The requirement in a password policy that users must include at least one + // lowercase letter in their password. + RequireLowercase bool + + // The requirement in a password policy that users must include at least one + // number in their password. + RequireNumbers bool + + // The requirement in a password policy that users must include at least one + // symbol in their password. + RequireSymbols bool + + // The requirement in a password policy that users must include at least one + // uppercase letter in their password. + RequireUppercase bool + + // The number of days a temporary password is valid in the password policy. If the + // user doesn't sign in during this time, an administrator must reset their + // password. Defaults to 7 . If you submit a value of 0 , Amazon Cognito treats it + // as a null value and sets TemporaryPasswordValidityDays to its default value. + // + // When you set TemporaryPasswordValidityDays for a user pool, you can no longer + // set a value for the legacy UnusedAccountValidityDays parameter in that user + // pool. + TemporaryPasswordValidityDays int32 + + noSmithyDocumentSerde +} + +// The properties of a pre token generation Lambda trigger. +type PreTokenGenerationVersionConfigType struct { + + // The Amazon Resource Name (ARN) of the function that you want to assign to your + // Lambda trigger. + // + // This parameter and the PreTokenGeneration property of LambdaConfig have the + // same value. For new instances of pre token generation triggers, set LambdaArn . + // + // This member is required. + LambdaArn *string + + // The user pool trigger version of the request that Amazon Cognito sends to your + // Lambda function. Higher-numbered versions add fields that support new features. + // + // This member is required. + LambdaVersion PreTokenGenerationLambdaVersionType + + noSmithyDocumentSerde +} + +// The details of a user pool identity provider (IdP), including name and type. +type ProviderDescription struct { + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // The name of the IdP, for example MySAMLProvider . + ProviderName *string + + // The type of the provider, for example SAML . Amazon Cognito supports SAML 2.0, + // OIDC, and social IdPs. User pools list supported social IdPs by name in this + // response parameter: Facebook, Google, Login with Amazon, and Sign in with Apple. + ProviderType IdentityProviderTypeType + + noSmithyDocumentSerde +} + +// The characteristics of a source or destination user for linking a federated +// user profile to a local user profile. +type ProviderUserIdentifierType struct { + + // The name of the provider attribute to link to, such as NameID . + ProviderAttributeName *string + + // The value of the provider attribute to link to, such as xxxxx_account . + ProviderAttributeValue *string + + // The name of the provider, such as Facebook, Google, or Login with Amazon. + ProviderName *string + + noSmithyDocumentSerde +} + +// A recovery option for a user. The AccountRecoverySettingType data type is an +// array of this object. Each RecoveryOptionType has a priority property that +// determines whether it is a primary or secondary option. +// +// For example, if verified_email has a priority of 1 and verified_phone_number +// has a priority of 2 , your user pool sends account-recovery messages to a +// verified email address but falls back to an SMS message if the user has a +// verified phone number. The admin_only option prevents self-service account +// recovery. +type RecoveryOptionType struct { + + // The recovery method that this object sets a recovery option for. + // + // This member is required. + Name RecoveryOptionNameType + + // Your priority preference for using the specified attribute in account recovery. + // The highest priority is 1 . + // + // This member is required. + Priority *int32 + + noSmithyDocumentSerde +} + +// The configuration of your app client for refresh token rotation. When enabled, +// your app client issues new ID, access, and refresh tokens when users renew their +// sessions with refresh tokens. When disabled, token refresh issues only ID and +// access tokens. +type RefreshTokenRotationType struct { + + // The state of refresh token rotation for the current app client. + // + // This member is required. + Feature FeatureType + + // When you request a token refresh with GetTokensFromRefreshToken , the original + // refresh token that you're rotating out can remain valid for a period of time of + // up to 60 seconds. This allows for client-side retries. When + // RetryGracePeriodSeconds is 0 , the grace period is disabled and a successful + // request immediately invalidates the submitted refresh token. + RetryGracePeriodSeconds *int32 + + noSmithyDocumentSerde +} + +// One custom scope associated with a user pool resource server. This data type is +// a member of ResourceServerScopeType . For more information, see [Scopes, M2M, and API authorization with resource servers]. +// +// [Scopes, M2M, and API authorization with resource servers]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html +type ResourceServerScopeType struct { + + // A friendly description of a custom scope. + // + // This member is required. + ScopeDescription *string + + // The name of the scope. Amazon Cognito renders custom scopes in the format + // resourceServerIdentifier/ScopeName . For example, if this parameter is + // exampleScope in the resource server with the identifier exampleResourceServer , + // you request and receive the scope exampleResourceServer/exampleScope . + // + // This member is required. + ScopeName *string + + noSmithyDocumentSerde +} + +// The details of a resource server configuration and associated custom scopes in +// a user pool. +type ResourceServerType struct { + + // A unique resource server identifier for the resource server. The identifier can + // be an API friendly name like solar-system-data . You can also set an API URL + // like https://solar-system-data-api.example.com as your identifier. + // + // Amazon Cognito represents scopes in the access token in the format + // $resource-server-identifier/$scope . Longer scope-identifier strings increase + // the size of your access tokens. + Identifier *string + + // The name of the resource server. + Name *string + + // A list of scopes that are defined for the resource server. + Scopes []ResourceServerScopeType + + // The ID of the user pool that contains the resource server configuration. + UserPoolId *string + + noSmithyDocumentSerde +} + +// The settings of risk configuration for threat protection with threat protection +// in a user pool. +type RiskConfigurationType struct { + + // The settings for automated responses and notification templates for adaptive + // authentication with threat protection. + AccountTakeoverRiskConfiguration *AccountTakeoverRiskConfigurationType + + // The app client where this configuration is applied. When this parameter isn't + // present, the risk configuration applies to all user pool app clients that don't + // have client-level settings. + ClientId *string + + // Settings for compromised-credentials actions and authentication types with + // threat protection in full-function ENFORCED mode. + CompromisedCredentialsRiskConfiguration *CompromisedCredentialsRiskConfigurationType + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // Exceptions to the risk evaluation configuration, including always-allow and + // always-block IP address ranges. + RiskExceptionConfiguration *RiskExceptionConfigurationType + + // The ID of the user pool that has the risk configuration applied. + UserPoolId *string + + noSmithyDocumentSerde +} + +// Exceptions to the risk evaluation configuration, including always-allow and +// always-block IP address ranges. +type RiskExceptionConfigurationType struct { + + // An always-block IP address list. Overrides the risk decision and always blocks + // authentication requests. This parameter is displayed and set in CIDR notation. + BlockedIPRangeList []string + + // An always-allow IP address list. Risk detection isn't performed on the IP + // addresses in this range list. This parameter is displayed and set in CIDR + // notation. + SkippedIPRangeList []string + + noSmithyDocumentSerde +} + +// Configuration for the Amazon S3 bucket destination of user activity log export +// with threat protection. +type S3ConfigurationType struct { + + // The ARN of an Amazon S3 bucket that's the destination for threat protection log + // export. + BucketArn *string + + noSmithyDocumentSerde +} + +// A list of the user attributes and their properties in your user pool. The +// attribute schema contains standard attributes, custom attributes with a custom: +// prefix, and developer attributes with a dev: prefix. For more information, see [User pool attributes]. +// +// Developer-only dev: attributes are a legacy feature of user pools, and are +// read-only to all app clients. You can create and update developer-only +// attributes only with IAM-authenticated API operations. Use app client read/write +// permissions instead. +// +// [User pool attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html +type SchemaAttributeType struct { + + // The data format of the values for your attribute. When you choose an + // AttributeDataType , Amazon Cognito validates the input against the data type. A + // custom attribute value in your user's ID token is always a string, for example + // "custom:isMember" : "true" or "custom:YearsAsMember" : "12" . + AttributeDataType AttributeDataType + + // You should use [WriteAttributes] in the user pool client to control how attributes can be + // mutated for new use cases instead of using DeveloperOnlyAttribute . + // + // Specifies whether the attribute type is developer only. This attribute can only + // be modified by an administrator. Users won't be able to modify this attribute + // using their access token. For example, DeveloperOnlyAttribute can be modified + // using AdminUpdateUserAttributes but can't be updated using UpdateUserAttributes. + // + // [WriteAttributes]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserPoolClientType.html#CognitoUserPools-Type-UserPoolClientType-WriteAttributes + DeveloperOnlyAttribute *bool + + // Specifies whether the value of the attribute can be changed. + // + // Any user pool attribute whose value you map from an IdP attribute must be + // mutable, with a parameter value of true . Amazon Cognito updates mapped + // attributes when users sign in to your application through an IdP. If an + // attribute is immutable, Amazon Cognito throws an error when it attempts to + // update the attribute. For more information, see [Specifying Identity Provider Attribute Mappings for Your User Pool]. + // + // [Specifying Identity Provider Attribute Mappings for Your User Pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html + Mutable *bool + + // The name of your user pool attribute. When you create or update a user pool, + // adding a schema attribute creates a custom or developer-only attribute. When you + // add an attribute with a Name value of MyAttribute , Amazon Cognito creates the + // custom attribute custom:MyAttribute . When DeveloperOnlyAttribute is true , + // Amazon Cognito creates your attribute as dev:MyAttribute . In an operation that + // describes a user pool, Amazon Cognito returns this value as value for standard + // attributes, custom:value for custom attributes, and dev:value for + // developer-only attributes.. + Name *string + + // Specifies the constraints for an attribute of the number type. + NumberAttributeConstraints *NumberAttributeConstraintsType + + // Specifies whether a user pool attribute is required. If the attribute is + // required and the user doesn't provide a value, registration or sign-in will + // fail. + Required *bool + + // Specifies the constraints for an attribute of the string type. + StringAttributeConstraints *StringAttributeConstraintsType + + noSmithyDocumentSerde +} + +// The policy for allowed types of authentication in a user pool. To activate this +// setting, your user pool must be in the [Essentials tier]or higher. +// +// [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html +type SignInPolicyType struct { + + // The sign-in methods that a user pool supports as the first factor. You can + // permit users to start authentication with a standard username and password, or + // with other one-time password and hardware factors. + AllowedFirstAuthFactors []AuthFactorType + + noSmithyDocumentSerde +} + +// User pool configuration for delivery of SMS messages with Amazon Simple +// Notification Service. To send SMS messages with Amazon SNS in the Amazon Web +// Services Region that you want, the Amazon Cognito user pool uses an Identity and +// Access Management (IAM) role in your Amazon Web Services account. +type SmsConfigurationType struct { + + // The Amazon Resource Name (ARN) of the Amazon SNS caller. This is the ARN of the + // IAM role in your Amazon Web Services account that Amazon Cognito will use to + // send SMS messages. SMS messages are subject to a [spending limit]. + // + // [spending limit]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html + // + // This member is required. + SnsCallerArn *string + + // The external ID provides additional security for your IAM role. You can use an + // ExternalId with the IAM role that you use with Amazon SNS to send SMS messages + // for your user pool. If you provide an ExternalId , your Amazon Cognito user pool + // includes it in the request to assume your IAM role. You can configure the role + // trust policy to require that Amazon Cognito, and any principal, provide the + // ExternalID . If you use the Amazon Cognito Management Console to create a role + // for SMS multi-factor authentication (MFA), Amazon Cognito creates a role with + // the required permissions and a trust policy that demonstrates use of the + // ExternalId . + // + // For more information about the ExternalId of a role, see [How to use an external ID when granting access to your Amazon Web Services resources to a third party]. + // + // [How to use an external ID when granting access to your Amazon Web Services resources to a third party]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html + ExternalId *string + + // The Amazon Web Services Region to use with Amazon SNS integration. You can + // choose the same Region as your user pool, or a supported Legacy Amazon SNS + // alternate Region. + // + // Amazon Cognito resources in the Asia Pacific (Seoul) Amazon Web Services Region + // must use your Amazon SNS configuration in the Asia Pacific (Tokyo) Region. For + // more information, see [SMS message settings for Amazon Cognito user pools]. + // + // [SMS message settings for Amazon Cognito user pools]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html + SnsRegion *string + + noSmithyDocumentSerde +} + +// The configuration of multi-factor authentication (MFA) with SMS messages in a +// user pool. +type SmsMfaConfigType struct { + + // The SMS authentication message that will be sent to users with the code they + // must sign in with. The message must contain the {####} placeholder. Your user + // pool replaces the placeholder with the MFA code. If this parameter isn't + // provided, your user pool sends a default message. + SmsAuthenticationMessage *string + + // User pool configuration for delivery of SMS messages with Amazon Simple + // Notification Service. To send SMS messages with Amazon SNS in the Amazon Web + // Services Region that you want, the Amazon Cognito user pool uses an Identity and + // Access Management (IAM) role in your Amazon Web Services account. + // + // You can set SmsConfiguration in CreateUserPool and UpdateUserPool , or in + // SetUserPoolMfaConfig . + SmsConfiguration *SmsConfigurationType + + noSmithyDocumentSerde +} + +// A user's preference for using SMS message multi-factor authentication (MFA). +// Turns SMS MFA on and off, and can set SMS as preferred when other MFA options +// are available. You can't turn off SMS MFA for any of your users when MFA is +// required in your user pool; you can only set the type that your user prefers. +type SMSMfaSettingsType struct { + + // Specifies whether SMS message MFA is activated. If an MFA type is activated for + // a user, the user will be prompted for MFA during all sign-in attempts, unless + // device tracking is turned on and the device has been trusted. + Enabled bool + + // Specifies whether SMS is the preferred MFA method. If true, your user pool + // prompts the specified user for a code delivered by SMS message after + // username-password sign-in succeeds. + PreferredMfa bool + + noSmithyDocumentSerde +} + +// Settings for time-based one-time password (TOTP) multi-factor authentication +// (MFA) in a user pool. Enables and disables availability of this feature. +type SoftwareTokenMfaConfigType struct { + + // The activation state of TOTP MFA. + Enabled bool + + noSmithyDocumentSerde +} + +// A user's preference for using time-based one-time password (TOTP) multi-factor +// authentication (MFA). Turns TOTP MFA on and off, and can set TOTP as preferred +// when other MFA options are available. You can't turn off TOTP MFA for any of +// your users when MFA is required in your user pool; you can only set the type +// that your user prefers. +type SoftwareTokenMfaSettingsType struct { + + // Specifies whether software token MFA is activated. If an MFA type is activated + // for a user, the user will be prompted for MFA during all sign-in attempts, + // unless device tracking is turned on and the device has been trusted. + Enabled bool + + // Specifies whether software token MFA is the preferred MFA method. + PreferredMfa bool + + noSmithyDocumentSerde +} + +// The minimum and maximum length values of an attribute that is of the string +// type, for example custom:department . +type StringAttributeConstraintsType struct { + + // The maximum length of a string attribute value. Must be a number less than or + // equal to 2^1023 , represented as a string with a length of 131072 characters or + // fewer. + MaxLength *string + + // The minimum length of a string attribute value. + MinLength *string + + noSmithyDocumentSerde +} + +// The time units that, with IdTokenValidity , AccessTokenValidity , and +// RefreshTokenValidity , set and display the duration of ID, access, and refresh +// tokens for an app client. You can assign a separate token validity unit to each +// type of token. +type TokenValidityUnitsType struct { + + // A time unit for the value that you set in the AccessTokenValidity parameter. + // The default AccessTokenValidity time unit is hours . AccessTokenValidity + // duration can range from five minutes to one day. + AccessToken TimeUnitsType + + // A time unit for the value that you set in the IdTokenValidity parameter. The + // default IdTokenValidity time unit is hours . IdTokenValidity duration can range + // from five minutes to one day. + IdToken TimeUnitsType + + // A time unit for the value that you set in the RefreshTokenValidity parameter. + // The default RefreshTokenValidity time unit is days . RefreshTokenValidity + // duration can range from 60 minutes to 10 years. + RefreshToken TimeUnitsType + + noSmithyDocumentSerde +} + +// A container for the UI customization information for the hosted UI in a user +// pool. +type UICustomizationType struct { + + // The CSS values in the UI customization. + CSS *string + + // The CSS version number. + CSSVersion *string + + // The app client ID for your UI customization. When this value isn't present, the + // customization applies to all user pool app clients that don't have client-level + // settings.. + ClientId *string + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // A URL path to the hosted logo image of your UI customization. + ImageUrl *string + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // The ID of the user pool with hosted UI customizations. + UserPoolId *string + + noSmithyDocumentSerde +} + +// The settings for updates to user attributes. These settings include the +// property AttributesRequireVerificationBeforeUpdate , a user-pool setting that +// tells Amazon Cognito how to handle changes to the value of your users' email +// address and phone number attributes. For more information, see [Verifying updates to email addresses and phone numbers]. +// +// [Verifying updates to email addresses and phone numbers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html#user-pool-settings-verifications-verify-attribute-updates +type UserAttributeUpdateSettingsType struct { + + // Requires that your user verifies their email address, phone number, or both + // before Amazon Cognito updates the value of that attribute. When you update a + // user attribute that has this option activated, Amazon Cognito sends a + // verification message to the new phone number or email address. Amazon Cognito + // doesn’t change the value of the attribute until your user responds to the + // verification message and confirms the new value. + // + // When AttributesRequireVerificationBeforeUpdate is false, your user pool doesn't + // require that your users verify attribute changes before Amazon Cognito updates + // them. In a user pool where AttributesRequireVerificationBeforeUpdate is false, + // API operations that change attribute values can immediately update a user’s + // email or phone_number attribute. + AttributesRequireVerificationBeforeUpdate []VerifiedAttributeType + + noSmithyDocumentSerde +} + +// Contextual data, such as the user's device fingerprint, IP address, or +// location, used for evaluating the risk of an unexpected event by Amazon Cognito +// threat protection. +type UserContextDataType struct { + + // Encoded device-fingerprint details that your app collected with the Amazon + // Cognito context data collection library. For more information, see [Adding user device and session data to API requests]. + // + // [Adding user device and session data to API requests]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-device-fingerprint + EncodedData *string + + // The source IP address of your user's device. + IpAddress *string + + noSmithyDocumentSerde +} + +// A user import job in a user pool. Describes the status of user import with a +// CSV file. For more information, see [Importing users into user pools from a CSV file]. +// +// [Importing users into user pools from a CSV file]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html +type UserImportJobType struct { + + // The role Amazon Resource Name (ARN) for the Amazon CloudWatch Logging role for + // the user import job. For more information, see "Creating the CloudWatch Logs IAM + // Role" in the Amazon Cognito Developer Guide. + CloudWatchLogsRoleArn *string + + // The date when the user import job was completed. + CompletionDate *time.Time + + // The message returned when the user import job is completed. + CompletionMessage *string + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // The number of users that couldn't be imported. + FailedUsers int64 + + // The number of users that were successfully imported. + ImportedUsers int64 + + // The ID of the user import job. + JobId *string + + // The friendly name of the user import job. + JobName *string + + // The pre-signed URL target for uploading the CSV file. + PreSignedUrl *string + + // The number of users that were skipped. + SkippedUsers int64 + + // The date when the user import job was started. + StartDate *time.Time + + // The status of the user import job. One of the following: + // + // - Created - The job was created but not started. + // + // - Pending - A transition state. You have started the job, but it has not begun + // importing users yet. + // + // - InProgress - The job has started, and users are being imported. + // + // - Stopping - You have stopped the job, but the job has not stopped importing + // users yet. + // + // - Stopped - You have stopped the job, and the job has stopped importing users. + // + // - Succeeded - The job has completed successfully. + // + // - Failed - The job has stopped due to an error. + // + // - Expired - You created a job, but did not start the job within 24-48 hours. + // All data associated with the job was deleted, and the job can't be started. + Status UserImportJobStatusType + + // The ID of the user pool that the users are being imported into. + UserPoolId *string + + noSmithyDocumentSerde +} + +// The configuration of a user pool for username case sensitivity. +type UsernameConfigurationType struct { + + // Specifies whether user name case sensitivity will be applied for all users in + // the user pool through Amazon Cognito APIs. For most use cases, set case + // sensitivity to False (case insensitive) as a best practice. When usernames and + // email addresses are case insensitive, users can sign in as the same user when + // they enter a different capitalization of their user name. + // + // Valid values include: + // + // true Enables case sensitivity for all username input. When this option is set + // to true , users must sign in using the exact capitalization of their given + // username, such as “UserName”. This is the default value. + // + // false Enables case insensitivity for all username input. For example, when this + // option is set to false , users can sign in using username , USERNAME , or + // UserName . This option also enables both preferred_username and email alias to + // be case insensitive, in addition to the username attribute. + // + // This member is required. + CaseSensitive *bool + + noSmithyDocumentSerde +} + +// Contains settings for activation of threat protection, including the operating +// mode and additional authentication types. To log user security information but +// take no action, set to AUDIT . To configure automatic security responses to +// potentially unwanted traffic to your user pool, set to ENFORCED . +// +// For more information, see [Adding advanced security to a user pool]. To activate this setting, your user pool must be on +// the [Plus tier]. +// +// [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html +// [Adding advanced security to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-advanced-security.html +type UserPoolAddOnsType struct { + + // The operating mode of threat protection for standard authentication types in + // your user pool, including username-password and secure remote password (SRP) + // authentication. + // + // This member is required. + AdvancedSecurityMode AdvancedSecurityModeType + + // Threat protection configuration options for additional authentication types in + // your user pool, including custom authentication. + AdvancedSecurityAdditionalFlows *AdvancedSecurityAdditionalFlowsType + + noSmithyDocumentSerde +} + +// A short description of a user pool app client. +type UserPoolClientDescription struct { + + // The app client ID. + ClientId *string + + // The app client name. + ClientName *string + + // The ID of the user pool that's associated with the app client. + UserPoolId *string + + noSmithyDocumentSerde +} + +// The configuration of a user pool client. +type UserPoolClientType struct { + + // The access token time limit. After this limit expires, your user can't use + // their access token. To specify the time unit for AccessTokenValidity as seconds + // , minutes , hours , or days , set a TokenValidityUnits value in your API + // request. + // + // For example, when you set AccessTokenValidity to 10 and TokenValidityUnits to + // hours , your user can authorize access with their access token for 10 hours. + // + // The default time unit for AccessTokenValidity in an API request is hours. Valid + // range is displayed below in seconds. + // + // If you don't specify otherwise in the configuration of your app client, your + // access tokens are valid for one hour. + AccessTokenValidity *int32 + + // The OAuth grant types that you want your app client to generate. To create an + // app client that generates client credentials grants, you must add + // client_credentials as the only allowed OAuth flow. + // + // code Use a code grant flow, which provides an authorization code as the + // response. This code can be exchanged for access tokens with the /oauth2/token + // endpoint. + // + // implicit Issue the access token (and, optionally, ID token, based on scopes) + // directly to your user. + // + // client_credentials Issue the access token from the /oauth2/token endpoint + // directly to a non-person user using a combination of the client ID and client + // secret. + AllowedOAuthFlows []OAuthFlowType + + // Set to true to use OAuth 2.0 authorization server features in your app client. + // + // This parameter must have a value of true before you can configure the following + // features in your app client. + // + // - CallBackURLs : Callback URLs. + // + // - LogoutURLs : Sign-out redirect URLs. + // + // - AllowedOAuthScopes : OAuth 2.0 scopes. + // + // - AllowedOAuthFlows : Support for authorization code, implicit, and client + // credentials OAuth 2.0 grants. + // + // To use authorization server features, configure one of these features in the + // Amazon Cognito console or set AllowedOAuthFlowsUserPoolClient to true in a + // CreateUserPoolClient or UpdateUserPoolClient API request. If you don't set a + // value for AllowedOAuthFlowsUserPoolClient in a request with the CLI or SDKs, it + // defaults to false . When false , only SDK-based API sign-in is permitted. + AllowedOAuthFlowsUserPoolClient *bool + + // The OAuth 2.0 scopes that you want your app client to support. Can include + // standard OAuth scopes like phone , email , openid , and profile . Can also + // include the aws.cognito.signin.user.admin scope that authorizes user profile + // self-service operations and custom scopes from resource servers. + AllowedOAuthScopes []string + + // The user pool analytics configuration for collecting metrics and sending them + // to your Amazon Pinpoint campaign. + // + // In Amazon Web Services Regions where Amazon Pinpoint isn't available, user + // pools only support sending events to Amazon Pinpoint projects in Amazon Web + // Services Region us-east-1. In Regions where Amazon Pinpoint is available, user + // pools support sending events to Amazon Pinpoint projects within that same + // Region. + AnalyticsConfiguration *AnalyticsConfigurationType + + // Amazon Cognito creates a session token for each API request in an + // authentication flow. AuthSessionValidity is the duration, in minutes, of that + // session token. Your user pool native user must respond to each authentication + // challenge before the session expires. + AuthSessionValidity *int32 + + // A list of allowed redirect (callback) URLs for the IdPs. + // + // A redirect URI must: + // + // - Be an absolute URI. + // + // - Be registered with the authorization server. + // + // - Not include a fragment component. + // + // See [OAuth 2.0 - Redirection Endpoint]. + // + // Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing + // purposes only. + // + // App callback URLs such as myapp://example are also supported. + // + // [OAuth 2.0 - Redirection Endpoint]: https://tools.ietf.org/html/rfc6749#section-3.1.2 + CallbackURLs []string + + // The ID of the app client. + ClientId *string + + // The name of the app client. + ClientName *string + + // The app client secret. + ClientSecret *string + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // The default redirect URI. Must be in the CallbackURLs list. + // + // A redirect URI must: + // + // - Be an absolute URI. + // + // - Be registered with the authorization server. + // + // - Not include a fragment component. + // + // See [OAuth 2.0 - Redirection Endpoint]. + // + // Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing + // purposes only. + // + // App callback URLs such as myapp://example are also supported. + // + // [OAuth 2.0 - Redirection Endpoint]: https://tools.ietf.org/html/rfc6749#section-3.1.2 + DefaultRedirectURI *string + + // When EnablePropagateAdditionalUserContextData is true, Amazon Cognito accepts + // an IpAddress value that you send in the UserContextData parameter. The + // UserContextData parameter sends information to Amazon Cognito threat protection + // for risk analysis. You can send UserContextData when you sign in Amazon Cognito + // native users with the InitiateAuth and RespondToAuthChallenge API operations. + // + // When EnablePropagateAdditionalUserContextData is false, you can't send your + // user's source IP address to Amazon Cognito threat protection with + // unauthenticated API operations. EnablePropagateAdditionalUserContextData + // doesn't affect whether you can send a source IP address in a ContextData + // parameter with the authenticated API operations AdminInitiateAuth and + // AdminRespondToAuthChallenge . + // + // You can only activate EnablePropagateAdditionalUserContextData in an app client + // that has a client secret. For more information about propagation of user context + // data, see [Adding user device and session data to API requests]. + // + // [Adding user device and session data to API requests]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-device-fingerprint + EnablePropagateAdditionalUserContextData *bool + + // Indicates whether token revocation is activated for the user pool client. When + // you create a new user pool client, token revocation is activated by default. + EnableTokenRevocation *bool + + // The [authentication flows] that you want your user pool client to support. For each app client in + // your user pool, you can sign in your users with any combination of one or more + // flows, including with a user name and Secure Remote Password (SRP), a user name + // and password, or a custom authentication process that you define with Lambda + // functions. + // + // If you don't specify a value for ExplicitAuthFlows , your app client supports + // ALLOW_REFRESH_TOKEN_AUTH , ALLOW_USER_SRP_AUTH , and ALLOW_CUSTOM_AUTH . + // + // The values for authentication flow options include the following. + // + // - ALLOW_USER_AUTH : Enable selection-based sign-in with USER_AUTH . This + // setting covers username-password, secure remote password (SRP), passwordless, + // and passkey authentication. This authentiation flow can do username-password and + // SRP authentication without other ExplicitAuthFlows permitting them. For + // example users can complete an SRP challenge through USER_AUTH without the flow + // USER_SRP_AUTH being active for the app client. This flow doesn't include + // CUSTOM_AUTH . + // + // To activate this setting, your user pool must be in the [Essentials tier]or higher. + // + // - ALLOW_ADMIN_USER_PASSWORD_AUTH : Enable admin based user password + // authentication flow ADMIN_USER_PASSWORD_AUTH . This setting replaces the + // ADMIN_NO_SRP_AUTH setting. With this authentication flow, your app passes a + // user name and password to Amazon Cognito in the request, instead of using the + // Secure Remote Password (SRP) protocol to securely transmit the password. + // + // - ALLOW_CUSTOM_AUTH : Enable Lambda trigger based authentication. + // + // - ALLOW_USER_PASSWORD_AUTH : Enable user password-based authentication. In + // this flow, Amazon Cognito receives the password in the request instead of using + // the SRP protocol to verify passwords. + // + // - ALLOW_USER_SRP_AUTH : Enable SRP-based authentication. + // + // - ALLOW_REFRESH_TOKEN_AUTH : Enable authflow to refresh tokens. + // + // In some environments, you will see the values ADMIN_NO_SRP_AUTH , + // CUSTOM_AUTH_FLOW_ONLY , or USER_PASSWORD_AUTH . You can't assign these legacy + // ExplicitAuthFlows values to user pool clients at the same time as values that + // begin with ALLOW_ , like ALLOW_USER_SRP_AUTH . + // + // [authentication flows]: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html + // [Essentials tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-essentials.html + ExplicitAuthFlows []ExplicitAuthFlowsType + + // The ID token time limit. After this limit expires, your user can't use their ID + // token. To specify the time unit for IdTokenValidity as seconds , minutes , hours + // , or days , set a TokenValidityUnits value in your API request. + // + // For example, when you set IdTokenValidity as 10 and TokenValidityUnits as hours + // , your user can authenticate their session with their ID token for 10 hours. + // + // The default time unit for IdTokenValidity in an API request is hours. Valid + // range is displayed below in seconds. + // + // If you don't specify otherwise in the configuration of your app client, your ID + // tokens are valid for one hour. + IdTokenValidity *int32 + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // A list of allowed logout URLs for the IdPs. + LogoutURLs []string + + // When ENABLED , suppresses messages that might indicate a valid user exists when + // someone attempts sign-in. This parameters sets your preference for the errors + // and responses that you want Amazon Cognito APIs to return during authentication, + // account confirmation, and password recovery when the user doesn't exist in the + // user pool. When set to ENABLED and the user doesn't exist, authentication + // returns an error indicating either the username or password was incorrect. + // Account confirmation and password recovery return a response indicating a code + // was sent to a simulated destination. When set to LEGACY , those APIs return a + // UserNotFoundException exception if the user doesn't exist in the user pool. + // + // Defaults to LEGACY . + PreventUserExistenceErrors PreventUserExistenceErrorTypes + + // The list of user attributes that you want your app client to have read access + // to. After your user authenticates in your app, their access token authorizes + // them to read their own attribute value for any attribute in this list. + // + // When you don't specify the ReadAttributes for your app client, your app can + // read the values of email_verified , phone_number_verified , and the standard + // attributes of your user pool. When your user pool app client has read access to + // these default attributes, ReadAttributes doesn't return any information. Amazon + // Cognito only populates ReadAttributes in the API response if you have specified + // your own custom set of read attributes. + ReadAttributes []string + + // The configuration of your app client for refresh token rotation. When enabled, + // your app client issues new ID, access, and refresh tokens when users renew their + // sessions with refresh tokens. When disabled, token refresh issues only ID and + // access tokens. + RefreshTokenRotation *RefreshTokenRotationType + + // The refresh token time limit. After this limit expires, your user can't use + // their refresh token. To specify the time unit for RefreshTokenValidity as + // seconds , minutes , hours , or days , set a TokenValidityUnits value in your + // API request. + // + // For example, when you set RefreshTokenValidity as 10 and TokenValidityUnits as + // days , your user can refresh their session and retrieve new access and ID tokens + // for 10 days. + // + // The default time unit for RefreshTokenValidity in an API request is days. You + // can't set RefreshTokenValidity to 0. If you do, Amazon Cognito overrides the + // value with the default value of 30 days. Valid range is displayed below in + // seconds. + // + // If you don't specify otherwise in the configuration of your app client, your + // refresh tokens are valid for 30 days. + RefreshTokenValidity int32 + + // A list of provider names for the identity providers (IdPs) that are supported + // on this client. The following are supported: COGNITO , Facebook , Google , + // SignInWithApple , and LoginWithAmazon . You can also specify the names that you + // configured for the SAML and OIDC IdPs in your user pool, for example MySAMLIdP + // or MyOIDCIdP . + // + // This parameter sets the IdPs that [managed login] will display on the login page for your app + // client. The removal of COGNITO from this list doesn't prevent authentication + // operations for local users with the user pools API in an Amazon Web Services + // SDK. The only way to prevent SDK-based authentication is to block access with a [WAF rule] + // . + // + // [WAF rule]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-waf.html + // [managed login]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html + SupportedIdentityProviders []string + + // The time units that, with IdTokenValidity , AccessTokenValidity , and + // RefreshTokenValidity , set and display the duration of ID, access, and refresh + // tokens for an app client. You can assign a separate token validity unit to each + // type of token. + TokenValidityUnits *TokenValidityUnitsType + + // The ID of the user pool associated with the app client. + UserPoolId *string + + // The list of user attributes that you want your app client to have write access + // to. After your user authenticates in your app, their access token authorizes + // them to set or modify their own attribute value for any attribute in this list. + // + // When you don't specify the WriteAttributes for your app client, your app can + // write the values of the Standard attributes of your user pool. When your user + // pool has write access to these default attributes, WriteAttributes doesn't + // return any information. Amazon Cognito only populates WriteAttributes in the + // API response if you have specified your own custom set of write attributes. + // + // If your app client allows users to sign in through an IdP, this array must + // include all attributes that you have mapped to IdP attributes. Amazon Cognito + // updates mapped attributes when users sign in to your application through an IdP. + // If your app client does not have write access to a mapped attribute, Amazon + // Cognito throws an error when it tries to update the attribute. For more + // information, see [Specifying IdP Attribute Mappings for Your user pool]. + // + // [Specifying IdP Attribute Mappings for Your user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html + WriteAttributes []string + + noSmithyDocumentSerde +} + +// A short description of a user pool. +type UserPoolDescriptionType struct { + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // The user pool ID. + Id *string + + // A collection of user pool Lambda triggers. Amazon Cognito invokes triggers at + // several possible stages of user pool operations. Triggers can modify the outcome + // of the operations that invoked them. + LambdaConfig *LambdaConfigType + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // The user pool name. + Name *string + + // The user pool status. + // + // Deprecated: This property is no longer available. + Status StatusType + + noSmithyDocumentSerde +} + +// A list of user pool policies. Contains the policy that sets password-complexity +// requirements. +type UserPoolPolicyType struct { + + // The password policy settings for a user pool, including complexity, history, + // and length requirements. + PasswordPolicy *PasswordPolicyType + + // The policy for allowed types of authentication in a user pool. + SignInPolicy *SignInPolicyType + + noSmithyDocumentSerde +} + +// The configuration of a user pool. +type UserPoolType struct { + + // The available verified method a user can use to recover their password when + // they call ForgotPassword . You can use this setting to define a preferred method + // when a user has more than one method available. With this setting, SMS doesn't + // qualify for a valid password recovery mechanism if the user also has SMS + // multi-factor authentication (MFA) activated. In the absence of this setting, + // Amazon Cognito uses the legacy behavior to determine the recovery method where + // SMS is preferred through email. + AccountRecoverySetting *AccountRecoverySettingType + + // The configuration for AdminCreateUser requests. + AdminCreateUserConfig *AdminCreateUserConfigType + + // Attributes supported as an alias for this user pool. An alias is an attribute + // that users can enter as an alternative username. Possible values: phone_number, + // email, or preferred_username. + AliasAttributes []AliasAttributeType + + // The Amazon Resource Name (ARN) of the user pool. + Arn *string + + // The attributes that are auto-verified in a user pool. + AutoVerifiedAttributes []VerifiedAttributeType + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + CreationDate *time.Time + + // A custom domain name that you provide to Amazon Cognito. This parameter applies + // only if you use a custom domain to host the sign-up and sign-in pages for your + // application. An example of a custom domain name might be auth.example.com . + // + // For more information about adding a custom domain to your user pool, see [Using Your Own Domain for the Hosted UI]. + // + // [Using Your Own Domain for the Hosted UI]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-add-custom-domain.html + CustomDomain *string + + // When active, DeletionProtection prevents accidental deletion of your user pool. + // Before you can delete a user pool that you have protected against deletion, you + // must deactivate this feature. + // + // When you try to delete a protected user pool in a DeleteUserPool API request, + // Amazon Cognito returns an InvalidParameterException error. To delete a + // protected user pool, send a new DeleteUserPool request after you deactivate + // deletion protection in an UpdateUserPool API request. + DeletionProtection DeletionProtectionType + + // The device-remembering configuration for a user pool. A null value indicates + // that you have deactivated device remembering in your user pool. + // + // When you provide a value for any DeviceConfiguration field, you activate the + // Amazon Cognito device-remembering feature. + DeviceConfiguration *DeviceConfigurationType + + // The domain prefix, if the user pool has a domain associated with it. + Domain *string + + // The email configuration of your user pool. The email configuration type sets + // your preferred sending method, Amazon Web Services Region, and sender for + // messages from your user pool. + EmailConfiguration *EmailConfigurationType + + // Deprecated. Review error codes from API requests with + // EventSource:cognito-idp.amazonaws.com in CloudTrail for information about + // problems with user pool email configuration. + EmailConfigurationFailure *string + + // This parameter is no longer used. + EmailVerificationMessage *string + + // This parameter is no longer used. + EmailVerificationSubject *string + + // A number estimating the size of the user pool. + EstimatedNumberOfUsers int32 + + // The ID of the user pool. + Id *string + + // A collection of user pool Lambda triggers. Amazon Cognito invokes triggers at + // several possible stages of user pool operations. Triggers can modify the outcome + // of the operations that invoked them. + LambdaConfig *LambdaConfigType + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + LastModifiedDate *time.Time + + // Can be one of the following values: + // + // - OFF - MFA tokens aren't required and can't be specified during user + // registration. + // + // - ON - MFA tokens are required for all user registrations. You can only + // specify required when you're initially creating a user pool. + // + // - OPTIONAL - Users have the option when registering to create an MFA token. + MfaConfiguration UserPoolMfaType + + // The name of the user pool. + Name *string + + // A list of user pool policies. Contains the policy that sets password-complexity + // requirements. + Policies *UserPoolPolicyType + + // A list of the user attributes and their properties in your user pool. The + // attribute schema contains standard attributes, custom attributes with a custom: + // prefix, and developer attributes with a dev: prefix. For more information, see [User pool attributes]. + // + // Developer-only attributes are a legacy feature of user pools, and are read-only + // to all app clients. You can create and update developer-only attributes only + // with IAM-authenticated API operations. Use app client read/write permissions + // instead. + // + // [User pool attributes]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html + SchemaAttributes []SchemaAttributeType + + // The contents of the SMS authentication message. + SmsAuthenticationMessage *string + + // User pool configuration for delivery of SMS messages with Amazon Simple + // Notification Service. To send SMS messages with Amazon SNS in the Amazon Web + // Services Region that you want, the Amazon Cognito user pool uses an Identity and + // Access Management (IAM) role in your Amazon Web Services account. + SmsConfiguration *SmsConfigurationType + + // The reason why the SMS configuration can't send the messages to your users. + // + // This message might include comma-separated values to describe why your SMS + // configuration can't send messages to user pool end users. + // + // InvalidSmsRoleAccessPolicyException The Identity and Access Management role + // that Amazon Cognito uses to send SMS messages isn't properly configured. For + // more information, see [SmsConfigurationType]. + // + // SNSSandbox The Amazon Web Services account is in the SNS SMS Sandbox and + // messages will only reach verified end users. This parameter won’t get populated + // with SNSSandbox if the user creating the user pool doesn’t have SNS permissions. + // To learn how to move your Amazon Web Services account out of the sandbox, see [Moving out of the SMS sandbox]. + // + // [Moving out of the SMS sandbox]: https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox-moving-to-production.html + // [SmsConfigurationType]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SmsConfigurationType.html + SmsConfigurationFailure *string + + // This parameter is no longer used. + SmsVerificationMessage *string + + // This parameter is no longer used. + // + // Deprecated: This property is no longer available. + Status StatusType + + // The settings for updates to user attributes. These settings include the + // property AttributesRequireVerificationBeforeUpdate , a user-pool setting that + // tells Amazon Cognito how to handle changes to the value of your users' email + // address and phone number attributes. For more information, see [Verifying updates to email addresses and phone numbers]. + // + // [Verifying updates to email addresses and phone numbers]: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html#user-pool-settings-verifications-verify-attribute-updates + UserAttributeUpdateSettings *UserAttributeUpdateSettingsType + + // Contains settings for activation of threat protection, including the operating + // mode and additional authentication types. To log user security information but + // take no action, set to AUDIT . To configure automatic security responses to + // potentially unwanted traffic to your user pool, set to ENFORCED . + // + // For more information, see [Adding advanced security to a user pool]. To activate this setting, your user pool must be on + // the [Plus tier]. + // + // [Plus tier]: https://docs.aws.amazon.com/cognito/latest/developerguide/feature-plans-features-plus.html + // [Adding advanced security to a user pool]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-advanced-security.html + UserPoolAddOns *UserPoolAddOnsType + + // The tags that are assigned to the user pool. A tag is a label that you can + // apply to user pools to categorize and manage them in different ways, such as by + // purpose, owner, environment, or other criteria. + UserPoolTags map[string]string + + // The user pool [feature plan], or tier. This parameter determines the eligibility of the user + // pool for features like managed login, access-token customization, and threat + // protection. Defaults to ESSENTIALS . + // + // [feature plan]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sign-in-feature-plans.html + UserPoolTier UserPoolTierType + + // Specifies whether a user can use an email address or phone number as a username + // when they sign up. + UsernameAttributes []UsernameAttributeType + + // Case sensitivity of the username input for the selected sign-in option. When + // case sensitivity is set to False (case insensitive), users can sign in with any + // combination of capital and lowercase letters. For example, username , USERNAME , + // or UserName , or for email, email@example.com or EMaiL@eXamplE.Com . For most + // use cases, set case sensitivity to False (case insensitive) as a best practice. + // When usernames and email addresses are case insensitive, Amazon Cognito treats + // any variation in case as the same user, and prevents a case variation from being + // assigned to the same attribute for a different user. + UsernameConfiguration *UsernameConfigurationType + + // The template for the verification message that your user pool delivers to users + // who set an email address or phone number attribute. + VerificationMessageTemplate *VerificationMessageTemplateType + + noSmithyDocumentSerde +} + +// A user profile in a Amazon Cognito user pool. +type UserType struct { + + // Names and values of a user's attributes, for example email . + Attributes []AttributeType + + // Indicates whether the user's account is enabled or disabled. + Enabled bool + + // The user's MFA configuration. + MFAOptions []MFAOptionType + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + UserCreateDate *time.Time + + // The date and time when the item was modified. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + UserLastModifiedDate *time.Time + + // The user status. This can be one of the following: + // + // - UNCONFIRMED : User has been created but not confirmed. + // + // - CONFIRMED : User has been confirmed. + // + // - EXTERNAL_PROVIDER : User signed in with a third-party IdP. + // + // - RESET_REQUIRED : User is confirmed, but the user must request a code and + // reset their password before they can sign in. + // + // - FORCE_CHANGE_PASSWORD : The user is confirmed and the user can sign in using + // a temporary password, but on first sign-in, the user must change their password + // to a new value before doing anything else. + // + // The statuses ARCHIVED , UNKNOWN , and COMPROMISED are no longer used. + UserStatus UserStatusType + + // The user's username. + Username *string + + noSmithyDocumentSerde +} + +// The template for the verification message that your user pool delivers to users +// who set an email address or phone number attribute. +type VerificationMessageTemplateType struct { + + // The configuration of verification emails to contain a clickable link or a + // verification code. + // + // For link, your template body must contain link text in the format {##Click + // here##} . "Click here" in the example is a customizable string. For code, your + // template body must contain a code placeholder in the format {####} . + DefaultEmailOption DefaultEmailOptionType + + // The template for email messages that Amazon Cognito sends to your users. You + // can set an EmailMessage template only if the value of [EmailSendingAccount] is DEVELOPER . When your [EmailSendingAccount] + // is DEVELOPER , your user pool sends email messages with your own Amazon SES + // configuration. + // + // [EmailSendingAccount]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html#CognitoUserPools-Type-EmailConfigurationType-EmailSendingAccount + EmailMessage *string + + // The email message template for sending a confirmation link to the user. You can + // set an EmailMessageByLink template only if the value of [EmailSendingAccount] is DEVELOPER . When + // your [EmailSendingAccount]is DEVELOPER , your user pool sends email messages with your own Amazon SES + // configuration. + // + // [EmailSendingAccount]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html#CognitoUserPools-Type-EmailConfigurationType-EmailSendingAccount + EmailMessageByLink *string + + // The subject line for the email message template. You can set an EmailSubject + // template only if the value of [EmailSendingAccount]is DEVELOPER . When your [EmailSendingAccount] is DEVELOPER , your user + // pool sends email messages with your own Amazon SES configuration. + // + // [EmailSendingAccount]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html#CognitoUserPools-Type-EmailConfigurationType-EmailSendingAccount + EmailSubject *string + + // The subject line for the email message template for sending a confirmation link + // to the user. You can set an EmailSubjectByLink template only if the value of [EmailSendingAccount] + // is DEVELOPER . When your [EmailSendingAccount] is DEVELOPER , your user pool sends email messages + // with your own Amazon SES configuration. + // + // [EmailSendingAccount]: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_EmailConfigurationType.html#CognitoUserPools-Type-EmailConfigurationType-EmailSendingAccount + EmailSubjectByLink *string + + // The template for SMS messages that Amazon Cognito sends to your users. + SmsMessage *string + + noSmithyDocumentSerde +} + +// Settings for authentication (MFA) with passkey, or webauthN, biometric and +// security-key devices in a user pool. Configures the following: +// +// - Configuration for requiring user-verification support in passkeys. +// +// - The user pool relying-party ID. This is the domain, typically your user +// pool domain, that user's passkey providers should trust as a receiver of passkey +// authentication. +// +// - The providers that you want to allow as origins for passkey authentication. +type WebAuthnConfigurationType struct { + + // Sets or displays the authentication domain, typically your user pool domain, + // that passkey providers must use as a relying party (RP) in their configuration. + // + // Under the following conditions, the passkey relying party ID must be the + // fully-qualified domain name of your custom domain: + // + // - The user pool is configured for passkey authentication. + // + // - The user pool has a custom domain, whether or not it also has a prefix + // domain. + // + // - Your application performs authentication with managed login or the classic + // hosted UI. + RelyingPartyId *string + + // When required , users can only register and sign in users with passkeys that are + // capable of [user verification]. When preferred , your user pool doesn't require the use of + // authenticators with user verification but encourages it. + // + // [user verification]: https://www.w3.org/TR/webauthn-2/#enum-userVerificationRequirement + UserVerification UserVerificationType + + noSmithyDocumentSerde +} + +// The details of a passkey, or webauthN, biometric or security-key authentication +// factor for a user. +type WebAuthnCredentialDescription struct { + + // Information about the transport methods of the passkey credential, for example + // USB or Bluetooth Low Energy. + // + // This member is required. + AuthenticatorTransports []string + + // The date and time when the item was created. Amazon Cognito returns this + // timestamp in UNIX epoch time format. Your SDK might render the output in a + // human-readable format like ISO 8601 or a Java Date object. + // + // This member is required. + CreatedAt *time.Time + + // The unique identifier of the passkey credential. + // + // This member is required. + CredentialId *string + + // An automatically-generated friendly name for the passkey credential. + // + // This member is required. + FriendlyCredentialName *string + + // The relying-party ID of the provider for the passkey credential. + // + // This member is required. + RelyingPartyId *string + + // The general category of the passkey authenticator. Can be a platform, or + // on-device authenticator like a built-in fingerprint scanner, or a cross-platform + // device that's not attached to the device like a Bluetooth security key. + AuthenticatorAttachment *string + + noSmithyDocumentSerde +} + +type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/validators.go new file mode 100644 index 00000000..a44802ce --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/validators.go @@ -0,0 +1,5409 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package cognitoidentityprovider + +import ( + "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types" + smithy "github.com/aws/smithy-go" + "github.com/aws/smithy-go/middleware" +) + +type validateOpAddCustomAttributes struct { +} + +func (*validateOpAddCustomAttributes) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAddCustomAttributes) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AddCustomAttributesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAddCustomAttributesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminAddUserToGroup struct { +} + +func (*validateOpAdminAddUserToGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminAddUserToGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminAddUserToGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminAddUserToGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminConfirmSignUp struct { +} + +func (*validateOpAdminConfirmSignUp) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminConfirmSignUp) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminConfirmSignUpInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminConfirmSignUpInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminCreateUser struct { +} + +func (*validateOpAdminCreateUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminCreateUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminCreateUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminCreateUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminDeleteUserAttributes struct { +} + +func (*validateOpAdminDeleteUserAttributes) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminDeleteUserAttributes) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminDeleteUserAttributesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminDeleteUserAttributesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminDeleteUser struct { +} + +func (*validateOpAdminDeleteUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminDeleteUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminDeleteUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminDeleteUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminDisableProviderForUser struct { +} + +func (*validateOpAdminDisableProviderForUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminDisableProviderForUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminDisableProviderForUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminDisableProviderForUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminDisableUser struct { +} + +func (*validateOpAdminDisableUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminDisableUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminDisableUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminDisableUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminEnableUser struct { +} + +func (*validateOpAdminEnableUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminEnableUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminEnableUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminEnableUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminForgetDevice struct { +} + +func (*validateOpAdminForgetDevice) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminForgetDevice) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminForgetDeviceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminForgetDeviceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminGetDevice struct { +} + +func (*validateOpAdminGetDevice) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminGetDevice) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminGetDeviceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminGetDeviceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminGetUser struct { +} + +func (*validateOpAdminGetUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminGetUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminGetUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminGetUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminInitiateAuth struct { +} + +func (*validateOpAdminInitiateAuth) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminInitiateAuth) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminInitiateAuthInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminInitiateAuthInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminLinkProviderForUser struct { +} + +func (*validateOpAdminLinkProviderForUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminLinkProviderForUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminLinkProviderForUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminLinkProviderForUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminListDevices struct { +} + +func (*validateOpAdminListDevices) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminListDevices) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminListDevicesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminListDevicesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminListGroupsForUser struct { +} + +func (*validateOpAdminListGroupsForUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminListGroupsForUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminListGroupsForUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminListGroupsForUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminListUserAuthEvents struct { +} + +func (*validateOpAdminListUserAuthEvents) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminListUserAuthEvents) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminListUserAuthEventsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminListUserAuthEventsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminRemoveUserFromGroup struct { +} + +func (*validateOpAdminRemoveUserFromGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminRemoveUserFromGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminRemoveUserFromGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminRemoveUserFromGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminResetUserPassword struct { +} + +func (*validateOpAdminResetUserPassword) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminResetUserPassword) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminResetUserPasswordInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminResetUserPasswordInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminRespondToAuthChallenge struct { +} + +func (*validateOpAdminRespondToAuthChallenge) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminRespondToAuthChallenge) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminRespondToAuthChallengeInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminRespondToAuthChallengeInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminSetUserMFAPreference struct { +} + +func (*validateOpAdminSetUserMFAPreference) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminSetUserMFAPreference) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminSetUserMFAPreferenceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminSetUserMFAPreferenceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminSetUserPassword struct { +} + +func (*validateOpAdminSetUserPassword) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminSetUserPassword) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminSetUserPasswordInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminSetUserPasswordInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminSetUserSettings struct { +} + +func (*validateOpAdminSetUserSettings) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminSetUserSettings) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminSetUserSettingsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminSetUserSettingsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminUpdateAuthEventFeedback struct { +} + +func (*validateOpAdminUpdateAuthEventFeedback) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminUpdateAuthEventFeedback) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminUpdateAuthEventFeedbackInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminUpdateAuthEventFeedbackInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminUpdateDeviceStatus struct { +} + +func (*validateOpAdminUpdateDeviceStatus) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminUpdateDeviceStatus) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminUpdateDeviceStatusInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminUpdateDeviceStatusInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminUpdateUserAttributes struct { +} + +func (*validateOpAdminUpdateUserAttributes) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminUpdateUserAttributes) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminUpdateUserAttributesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminUpdateUserAttributesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpAdminUserGlobalSignOut struct { +} + +func (*validateOpAdminUserGlobalSignOut) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpAdminUserGlobalSignOut) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*AdminUserGlobalSignOutInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpAdminUserGlobalSignOutInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpChangePassword struct { +} + +func (*validateOpChangePassword) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpChangePassword) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ChangePasswordInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpChangePasswordInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCompleteWebAuthnRegistration struct { +} + +func (*validateOpCompleteWebAuthnRegistration) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCompleteWebAuthnRegistration) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CompleteWebAuthnRegistrationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCompleteWebAuthnRegistrationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpConfirmDevice struct { +} + +func (*validateOpConfirmDevice) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpConfirmDevice) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ConfirmDeviceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpConfirmDeviceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpConfirmForgotPassword struct { +} + +func (*validateOpConfirmForgotPassword) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpConfirmForgotPassword) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ConfirmForgotPasswordInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpConfirmForgotPasswordInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpConfirmSignUp struct { +} + +func (*validateOpConfirmSignUp) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpConfirmSignUp) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ConfirmSignUpInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpConfirmSignUpInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateGroup struct { +} + +func (*validateOpCreateGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateIdentityProvider struct { +} + +func (*validateOpCreateIdentityProvider) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateIdentityProvider) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateIdentityProviderInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateIdentityProviderInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateManagedLoginBranding struct { +} + +func (*validateOpCreateManagedLoginBranding) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateManagedLoginBranding) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateManagedLoginBrandingInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateManagedLoginBrandingInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateResourceServer struct { +} + +func (*validateOpCreateResourceServer) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateResourceServer) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateResourceServerInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateResourceServerInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateUserImportJob struct { +} + +func (*validateOpCreateUserImportJob) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateUserImportJob) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateUserImportJobInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateUserImportJobInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateUserPoolClient struct { +} + +func (*validateOpCreateUserPoolClient) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateUserPoolClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateUserPoolClientInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateUserPoolClientInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateUserPoolDomain struct { +} + +func (*validateOpCreateUserPoolDomain) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateUserPoolDomain) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateUserPoolDomainInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateUserPoolDomainInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpCreateUserPool struct { +} + +func (*validateOpCreateUserPool) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateUserPool) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateUserPoolInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateUserPoolInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteGroup struct { +} + +func (*validateOpDeleteGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteIdentityProvider struct { +} + +func (*validateOpDeleteIdentityProvider) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteIdentityProvider) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteIdentityProviderInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteIdentityProviderInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteManagedLoginBranding struct { +} + +func (*validateOpDeleteManagedLoginBranding) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteManagedLoginBranding) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteManagedLoginBrandingInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteManagedLoginBrandingInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteResourceServer struct { +} + +func (*validateOpDeleteResourceServer) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteResourceServer) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteResourceServerInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteResourceServerInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteUserAttributes struct { +} + +func (*validateOpDeleteUserAttributes) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteUserAttributes) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteUserAttributesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteUserAttributesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteUser struct { +} + +func (*validateOpDeleteUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteUserPoolClient struct { +} + +func (*validateOpDeleteUserPoolClient) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteUserPoolClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteUserPoolClientInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteUserPoolClientInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteUserPoolDomain struct { +} + +func (*validateOpDeleteUserPoolDomain) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteUserPoolDomain) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteUserPoolDomainInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteUserPoolDomainInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteUserPool struct { +} + +func (*validateOpDeleteUserPool) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteUserPool) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteUserPoolInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteUserPoolInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDeleteWebAuthnCredential struct { +} + +func (*validateOpDeleteWebAuthnCredential) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDeleteWebAuthnCredential) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DeleteWebAuthnCredentialInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDeleteWebAuthnCredentialInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeIdentityProvider struct { +} + +func (*validateOpDescribeIdentityProvider) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeIdentityProvider) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeIdentityProviderInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeIdentityProviderInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeManagedLoginBrandingByClient struct { +} + +func (*validateOpDescribeManagedLoginBrandingByClient) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeManagedLoginBrandingByClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeManagedLoginBrandingByClientInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeManagedLoginBrandingByClientInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeManagedLoginBranding struct { +} + +func (*validateOpDescribeManagedLoginBranding) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeManagedLoginBranding) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeManagedLoginBrandingInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeManagedLoginBrandingInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeResourceServer struct { +} + +func (*validateOpDescribeResourceServer) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeResourceServer) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeResourceServerInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeResourceServerInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeRiskConfiguration struct { +} + +func (*validateOpDescribeRiskConfiguration) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeRiskConfiguration) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeRiskConfigurationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeRiskConfigurationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeUserImportJob struct { +} + +func (*validateOpDescribeUserImportJob) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeUserImportJob) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeUserImportJobInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeUserImportJobInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeUserPoolClient struct { +} + +func (*validateOpDescribeUserPoolClient) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeUserPoolClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeUserPoolClientInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeUserPoolClientInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeUserPoolDomain struct { +} + +func (*validateOpDescribeUserPoolDomain) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeUserPoolDomain) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeUserPoolDomainInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeUserPoolDomainInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpDescribeUserPool struct { +} + +func (*validateOpDescribeUserPool) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpDescribeUserPool) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*DescribeUserPoolInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpDescribeUserPoolInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpForgetDevice struct { +} + +func (*validateOpForgetDevice) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpForgetDevice) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ForgetDeviceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpForgetDeviceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpForgotPassword struct { +} + +func (*validateOpForgotPassword) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpForgotPassword) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ForgotPasswordInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpForgotPasswordInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetCSVHeader struct { +} + +func (*validateOpGetCSVHeader) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetCSVHeader) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetCSVHeaderInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetCSVHeaderInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetDevice struct { +} + +func (*validateOpGetDevice) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetDevice) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetDeviceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetDeviceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetGroup struct { +} + +func (*validateOpGetGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetIdentityProviderByIdentifier struct { +} + +func (*validateOpGetIdentityProviderByIdentifier) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetIdentityProviderByIdentifier) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetIdentityProviderByIdentifierInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetIdentityProviderByIdentifierInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetLogDeliveryConfiguration struct { +} + +func (*validateOpGetLogDeliveryConfiguration) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetLogDeliveryConfiguration) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetLogDeliveryConfigurationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetLogDeliveryConfigurationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetSigningCertificate struct { +} + +func (*validateOpGetSigningCertificate) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetSigningCertificate) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetSigningCertificateInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetSigningCertificateInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetTokensFromRefreshToken struct { +} + +func (*validateOpGetTokensFromRefreshToken) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetTokensFromRefreshToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetTokensFromRefreshTokenInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetTokensFromRefreshTokenInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetUICustomization struct { +} + +func (*validateOpGetUICustomization) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetUICustomization) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetUICustomizationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetUICustomizationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetUserAttributeVerificationCode struct { +} + +func (*validateOpGetUserAttributeVerificationCode) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetUserAttributeVerificationCode) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetUserAttributeVerificationCodeInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetUserAttributeVerificationCodeInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetUserAuthFactors struct { +} + +func (*validateOpGetUserAuthFactors) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetUserAuthFactors) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetUserAuthFactorsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetUserAuthFactorsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetUser struct { +} + +func (*validateOpGetUser) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetUser) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetUserInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetUserInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGetUserPoolMfaConfig struct { +} + +func (*validateOpGetUserPoolMfaConfig) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetUserPoolMfaConfig) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetUserPoolMfaConfigInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetUserPoolMfaConfigInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpGlobalSignOut struct { +} + +func (*validateOpGlobalSignOut) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGlobalSignOut) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GlobalSignOutInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGlobalSignOutInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpInitiateAuth struct { +} + +func (*validateOpInitiateAuth) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpInitiateAuth) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*InitiateAuthInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpInitiateAuthInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListDevices struct { +} + +func (*validateOpListDevices) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListDevices) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListDevicesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListDevicesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListGroups struct { +} + +func (*validateOpListGroups) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListGroups) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListGroupsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListGroupsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListIdentityProviders struct { +} + +func (*validateOpListIdentityProviders) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListIdentityProviders) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListIdentityProvidersInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListIdentityProvidersInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListResourceServers struct { +} + +func (*validateOpListResourceServers) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListResourceServers) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListResourceServersInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListResourceServersInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListTagsForResource struct { +} + +func (*validateOpListTagsForResource) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListTagsForResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListTagsForResourceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListTagsForResourceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListUserImportJobs struct { +} + +func (*validateOpListUserImportJobs) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListUserImportJobs) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListUserImportJobsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListUserImportJobsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListUserPoolClients struct { +} + +func (*validateOpListUserPoolClients) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListUserPoolClients) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListUserPoolClientsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListUserPoolClientsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListUserPools struct { +} + +func (*validateOpListUserPools) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListUserPools) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListUserPoolsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListUserPoolsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListUsersInGroup struct { +} + +func (*validateOpListUsersInGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListUsersInGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListUsersInGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListUsersInGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListUsers struct { +} + +func (*validateOpListUsers) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListUsers) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListUsersInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListUsersInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpListWebAuthnCredentials struct { +} + +func (*validateOpListWebAuthnCredentials) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpListWebAuthnCredentials) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ListWebAuthnCredentialsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpListWebAuthnCredentialsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpResendConfirmationCode struct { +} + +func (*validateOpResendConfirmationCode) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpResendConfirmationCode) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*ResendConfirmationCodeInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpResendConfirmationCodeInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpRespondToAuthChallenge struct { +} + +func (*validateOpRespondToAuthChallenge) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpRespondToAuthChallenge) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*RespondToAuthChallengeInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpRespondToAuthChallengeInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpRevokeToken struct { +} + +func (*validateOpRevokeToken) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpRevokeToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*RevokeTokenInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpRevokeTokenInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSetLogDeliveryConfiguration struct { +} + +func (*validateOpSetLogDeliveryConfiguration) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSetLogDeliveryConfiguration) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SetLogDeliveryConfigurationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSetLogDeliveryConfigurationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSetRiskConfiguration struct { +} + +func (*validateOpSetRiskConfiguration) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSetRiskConfiguration) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SetRiskConfigurationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSetRiskConfigurationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSetUICustomization struct { +} + +func (*validateOpSetUICustomization) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSetUICustomization) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SetUICustomizationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSetUICustomizationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSetUserMFAPreference struct { +} + +func (*validateOpSetUserMFAPreference) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSetUserMFAPreference) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SetUserMFAPreferenceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSetUserMFAPreferenceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSetUserPoolMfaConfig struct { +} + +func (*validateOpSetUserPoolMfaConfig) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSetUserPoolMfaConfig) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SetUserPoolMfaConfigInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSetUserPoolMfaConfigInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSetUserSettings struct { +} + +func (*validateOpSetUserSettings) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSetUserSettings) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SetUserSettingsInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSetUserSettingsInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpSignUp struct { +} + +func (*validateOpSignUp) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpSignUp) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*SignUpInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpSignUpInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStartUserImportJob struct { +} + +func (*validateOpStartUserImportJob) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStartUserImportJob) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StartUserImportJobInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStartUserImportJobInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStartWebAuthnRegistration struct { +} + +func (*validateOpStartWebAuthnRegistration) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStartWebAuthnRegistration) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StartWebAuthnRegistrationInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStartWebAuthnRegistrationInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpStopUserImportJob struct { +} + +func (*validateOpStopUserImportJob) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpStopUserImportJob) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*StopUserImportJobInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpStopUserImportJobInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpTagResource struct { +} + +func (*validateOpTagResource) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpTagResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*TagResourceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpTagResourceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUntagResource struct { +} + +func (*validateOpUntagResource) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUntagResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UntagResourceInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUntagResourceInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateAuthEventFeedback struct { +} + +func (*validateOpUpdateAuthEventFeedback) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateAuthEventFeedback) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateAuthEventFeedbackInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateAuthEventFeedbackInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateDeviceStatus struct { +} + +func (*validateOpUpdateDeviceStatus) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateDeviceStatus) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateDeviceStatusInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateDeviceStatusInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateGroup struct { +} + +func (*validateOpUpdateGroup) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateGroupInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateGroupInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateIdentityProvider struct { +} + +func (*validateOpUpdateIdentityProvider) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateIdentityProvider) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateIdentityProviderInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateIdentityProviderInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateManagedLoginBranding struct { +} + +func (*validateOpUpdateManagedLoginBranding) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateManagedLoginBranding) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateManagedLoginBrandingInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateManagedLoginBrandingInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateResourceServer struct { +} + +func (*validateOpUpdateResourceServer) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateResourceServer) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateResourceServerInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateResourceServerInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateUserAttributes struct { +} + +func (*validateOpUpdateUserAttributes) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateUserAttributes) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateUserAttributesInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateUserAttributesInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateUserPoolClient struct { +} + +func (*validateOpUpdateUserPoolClient) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateUserPoolClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateUserPoolClientInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateUserPoolClientInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateUserPoolDomain struct { +} + +func (*validateOpUpdateUserPoolDomain) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateUserPoolDomain) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateUserPoolDomainInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateUserPoolDomainInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpUpdateUserPool struct { +} + +func (*validateOpUpdateUserPool) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpUpdateUserPool) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*UpdateUserPoolInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpUpdateUserPoolInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpVerifySoftwareToken struct { +} + +func (*validateOpVerifySoftwareToken) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpVerifySoftwareToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*VerifySoftwareTokenInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpVerifySoftwareTokenInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +type validateOpVerifyUserAttribute struct { +} + +func (*validateOpVerifyUserAttribute) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpVerifyUserAttribute) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*VerifyUserAttributeInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpVerifyUserAttributeInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +func addOpAddCustomAttributesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAddCustomAttributes{}, middleware.After) +} + +func addOpAdminAddUserToGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminAddUserToGroup{}, middleware.After) +} + +func addOpAdminConfirmSignUpValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminConfirmSignUp{}, middleware.After) +} + +func addOpAdminCreateUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminCreateUser{}, middleware.After) +} + +func addOpAdminDeleteUserAttributesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminDeleteUserAttributes{}, middleware.After) +} + +func addOpAdminDeleteUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminDeleteUser{}, middleware.After) +} + +func addOpAdminDisableProviderForUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminDisableProviderForUser{}, middleware.After) +} + +func addOpAdminDisableUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminDisableUser{}, middleware.After) +} + +func addOpAdminEnableUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminEnableUser{}, middleware.After) +} + +func addOpAdminForgetDeviceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminForgetDevice{}, middleware.After) +} + +func addOpAdminGetDeviceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminGetDevice{}, middleware.After) +} + +func addOpAdminGetUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminGetUser{}, middleware.After) +} + +func addOpAdminInitiateAuthValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminInitiateAuth{}, middleware.After) +} + +func addOpAdminLinkProviderForUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminLinkProviderForUser{}, middleware.After) +} + +func addOpAdminListDevicesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminListDevices{}, middleware.After) +} + +func addOpAdminListGroupsForUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminListGroupsForUser{}, middleware.After) +} + +func addOpAdminListUserAuthEventsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminListUserAuthEvents{}, middleware.After) +} + +func addOpAdminRemoveUserFromGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminRemoveUserFromGroup{}, middleware.After) +} + +func addOpAdminResetUserPasswordValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminResetUserPassword{}, middleware.After) +} + +func addOpAdminRespondToAuthChallengeValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminRespondToAuthChallenge{}, middleware.After) +} + +func addOpAdminSetUserMFAPreferenceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminSetUserMFAPreference{}, middleware.After) +} + +func addOpAdminSetUserPasswordValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminSetUserPassword{}, middleware.After) +} + +func addOpAdminSetUserSettingsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminSetUserSettings{}, middleware.After) +} + +func addOpAdminUpdateAuthEventFeedbackValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminUpdateAuthEventFeedback{}, middleware.After) +} + +func addOpAdminUpdateDeviceStatusValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminUpdateDeviceStatus{}, middleware.After) +} + +func addOpAdminUpdateUserAttributesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminUpdateUserAttributes{}, middleware.After) +} + +func addOpAdminUserGlobalSignOutValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpAdminUserGlobalSignOut{}, middleware.After) +} + +func addOpChangePasswordValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpChangePassword{}, middleware.After) +} + +func addOpCompleteWebAuthnRegistrationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCompleteWebAuthnRegistration{}, middleware.After) +} + +func addOpConfirmDeviceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpConfirmDevice{}, middleware.After) +} + +func addOpConfirmForgotPasswordValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpConfirmForgotPassword{}, middleware.After) +} + +func addOpConfirmSignUpValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpConfirmSignUp{}, middleware.After) +} + +func addOpCreateGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateGroup{}, middleware.After) +} + +func addOpCreateIdentityProviderValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateIdentityProvider{}, middleware.After) +} + +func addOpCreateManagedLoginBrandingValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateManagedLoginBranding{}, middleware.After) +} + +func addOpCreateResourceServerValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateResourceServer{}, middleware.After) +} + +func addOpCreateUserImportJobValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateUserImportJob{}, middleware.After) +} + +func addOpCreateUserPoolClientValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateUserPoolClient{}, middleware.After) +} + +func addOpCreateUserPoolDomainValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateUserPoolDomain{}, middleware.After) +} + +func addOpCreateUserPoolValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateUserPool{}, middleware.After) +} + +func addOpDeleteGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteGroup{}, middleware.After) +} + +func addOpDeleteIdentityProviderValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteIdentityProvider{}, middleware.After) +} + +func addOpDeleteManagedLoginBrandingValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteManagedLoginBranding{}, middleware.After) +} + +func addOpDeleteResourceServerValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteResourceServer{}, middleware.After) +} + +func addOpDeleteUserAttributesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteUserAttributes{}, middleware.After) +} + +func addOpDeleteUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteUser{}, middleware.After) +} + +func addOpDeleteUserPoolClientValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteUserPoolClient{}, middleware.After) +} + +func addOpDeleteUserPoolDomainValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteUserPoolDomain{}, middleware.After) +} + +func addOpDeleteUserPoolValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteUserPool{}, middleware.After) +} + +func addOpDeleteWebAuthnCredentialValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDeleteWebAuthnCredential{}, middleware.After) +} + +func addOpDescribeIdentityProviderValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeIdentityProvider{}, middleware.After) +} + +func addOpDescribeManagedLoginBrandingByClientValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeManagedLoginBrandingByClient{}, middleware.After) +} + +func addOpDescribeManagedLoginBrandingValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeManagedLoginBranding{}, middleware.After) +} + +func addOpDescribeResourceServerValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeResourceServer{}, middleware.After) +} + +func addOpDescribeRiskConfigurationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeRiskConfiguration{}, middleware.After) +} + +func addOpDescribeUserImportJobValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeUserImportJob{}, middleware.After) +} + +func addOpDescribeUserPoolClientValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeUserPoolClient{}, middleware.After) +} + +func addOpDescribeUserPoolDomainValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeUserPoolDomain{}, middleware.After) +} + +func addOpDescribeUserPoolValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpDescribeUserPool{}, middleware.After) +} + +func addOpForgetDeviceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpForgetDevice{}, middleware.After) +} + +func addOpForgotPasswordValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpForgotPassword{}, middleware.After) +} + +func addOpGetCSVHeaderValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetCSVHeader{}, middleware.After) +} + +func addOpGetDeviceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetDevice{}, middleware.After) +} + +func addOpGetGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetGroup{}, middleware.After) +} + +func addOpGetIdentityProviderByIdentifierValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetIdentityProviderByIdentifier{}, middleware.After) +} + +func addOpGetLogDeliveryConfigurationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetLogDeliveryConfiguration{}, middleware.After) +} + +func addOpGetSigningCertificateValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetSigningCertificate{}, middleware.After) +} + +func addOpGetTokensFromRefreshTokenValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetTokensFromRefreshToken{}, middleware.After) +} + +func addOpGetUICustomizationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetUICustomization{}, middleware.After) +} + +func addOpGetUserAttributeVerificationCodeValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetUserAttributeVerificationCode{}, middleware.After) +} + +func addOpGetUserAuthFactorsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetUserAuthFactors{}, middleware.After) +} + +func addOpGetUserValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetUser{}, middleware.After) +} + +func addOpGetUserPoolMfaConfigValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetUserPoolMfaConfig{}, middleware.After) +} + +func addOpGlobalSignOutValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGlobalSignOut{}, middleware.After) +} + +func addOpInitiateAuthValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpInitiateAuth{}, middleware.After) +} + +func addOpListDevicesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListDevices{}, middleware.After) +} + +func addOpListGroupsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListGroups{}, middleware.After) +} + +func addOpListIdentityProvidersValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListIdentityProviders{}, middleware.After) +} + +func addOpListResourceServersValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListResourceServers{}, middleware.After) +} + +func addOpListTagsForResourceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListTagsForResource{}, middleware.After) +} + +func addOpListUserImportJobsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListUserImportJobs{}, middleware.After) +} + +func addOpListUserPoolClientsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListUserPoolClients{}, middleware.After) +} + +func addOpListUserPoolsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListUserPools{}, middleware.After) +} + +func addOpListUsersInGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListUsersInGroup{}, middleware.After) +} + +func addOpListUsersValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListUsers{}, middleware.After) +} + +func addOpListWebAuthnCredentialsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpListWebAuthnCredentials{}, middleware.After) +} + +func addOpResendConfirmationCodeValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpResendConfirmationCode{}, middleware.After) +} + +func addOpRespondToAuthChallengeValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpRespondToAuthChallenge{}, middleware.After) +} + +func addOpRevokeTokenValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpRevokeToken{}, middleware.After) +} + +func addOpSetLogDeliveryConfigurationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSetLogDeliveryConfiguration{}, middleware.After) +} + +func addOpSetRiskConfigurationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSetRiskConfiguration{}, middleware.After) +} + +func addOpSetUICustomizationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSetUICustomization{}, middleware.After) +} + +func addOpSetUserMFAPreferenceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSetUserMFAPreference{}, middleware.After) +} + +func addOpSetUserPoolMfaConfigValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSetUserPoolMfaConfig{}, middleware.After) +} + +func addOpSetUserSettingsValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSetUserSettings{}, middleware.After) +} + +func addOpSignUpValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpSignUp{}, middleware.After) +} + +func addOpStartUserImportJobValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStartUserImportJob{}, middleware.After) +} + +func addOpStartWebAuthnRegistrationValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStartWebAuthnRegistration{}, middleware.After) +} + +func addOpStopUserImportJobValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpStopUserImportJob{}, middleware.After) +} + +func addOpTagResourceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpTagResource{}, middleware.After) +} + +func addOpUntagResourceValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUntagResource{}, middleware.After) +} + +func addOpUpdateAuthEventFeedbackValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateAuthEventFeedback{}, middleware.After) +} + +func addOpUpdateDeviceStatusValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateDeviceStatus{}, middleware.After) +} + +func addOpUpdateGroupValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateGroup{}, middleware.After) +} + +func addOpUpdateIdentityProviderValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateIdentityProvider{}, middleware.After) +} + +func addOpUpdateManagedLoginBrandingValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateManagedLoginBranding{}, middleware.After) +} + +func addOpUpdateResourceServerValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateResourceServer{}, middleware.After) +} + +func addOpUpdateUserAttributesValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateUserAttributes{}, middleware.After) +} + +func addOpUpdateUserPoolClientValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateUserPoolClient{}, middleware.After) +} + +func addOpUpdateUserPoolDomainValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateUserPoolDomain{}, middleware.After) +} + +func addOpUpdateUserPoolValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpUpdateUserPool{}, middleware.After) +} + +func addOpVerifySoftwareTokenValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpVerifySoftwareToken{}, middleware.After) +} + +func addOpVerifyUserAttributeValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpVerifyUserAttribute{}, middleware.After) +} + +func validateAccountRecoverySettingType(v *types.AccountRecoverySettingType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AccountRecoverySettingType"} + if v.RecoveryMechanisms != nil { + if err := validateRecoveryMechanismsType(v.RecoveryMechanisms); err != nil { + invalidParams.AddNested("RecoveryMechanisms", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAccountTakeoverActionsType(v *types.AccountTakeoverActionsType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AccountTakeoverActionsType"} + if v.LowAction != nil { + if err := validateAccountTakeoverActionType(v.LowAction); err != nil { + invalidParams.AddNested("LowAction", err.(smithy.InvalidParamsError)) + } + } + if v.MediumAction != nil { + if err := validateAccountTakeoverActionType(v.MediumAction); err != nil { + invalidParams.AddNested("MediumAction", err.(smithy.InvalidParamsError)) + } + } + if v.HighAction != nil { + if err := validateAccountTakeoverActionType(v.HighAction); err != nil { + invalidParams.AddNested("HighAction", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAccountTakeoverActionType(v *types.AccountTakeoverActionType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AccountTakeoverActionType"} + if len(v.EventAction) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("EventAction")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAccountTakeoverRiskConfigurationType(v *types.AccountTakeoverRiskConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AccountTakeoverRiskConfigurationType"} + if v.NotifyConfiguration != nil { + if err := validateNotifyConfigurationType(v.NotifyConfiguration); err != nil { + invalidParams.AddNested("NotifyConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.Actions == nil { + invalidParams.Add(smithy.NewErrParamRequired("Actions")) + } else if v.Actions != nil { + if err := validateAccountTakeoverActionsType(v.Actions); err != nil { + invalidParams.AddNested("Actions", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAssetListType(v []types.AssetType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AssetListType"} + for i := range v { + if err := validateAssetType(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAssetType(v *types.AssetType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AssetType"} + if len(v.Category) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("Category")) + } + if len(v.ColorMode) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("ColorMode")) + } + if len(v.Extension) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("Extension")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAttributeListType(v []types.AttributeType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AttributeListType"} + for i := range v { + if err := validateAttributeType(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateAttributeType(v *types.AttributeType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AttributeType"} + if v.Name == nil { + invalidParams.Add(smithy.NewErrParamRequired("Name")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateCompromisedCredentialsActionsType(v *types.CompromisedCredentialsActionsType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CompromisedCredentialsActionsType"} + if len(v.EventAction) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("EventAction")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateCompromisedCredentialsRiskConfigurationType(v *types.CompromisedCredentialsRiskConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CompromisedCredentialsRiskConfigurationType"} + if v.Actions == nil { + invalidParams.Add(smithy.NewErrParamRequired("Actions")) + } else if v.Actions != nil { + if err := validateCompromisedCredentialsActionsType(v.Actions); err != nil { + invalidParams.AddNested("Actions", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateContextDataType(v *types.ContextDataType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ContextDataType"} + if v.IpAddress == nil { + invalidParams.Add(smithy.NewErrParamRequired("IpAddress")) + } + if v.ServerName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ServerName")) + } + if v.ServerPath == nil { + invalidParams.Add(smithy.NewErrParamRequired("ServerPath")) + } + if v.HttpHeaders == nil { + invalidParams.Add(smithy.NewErrParamRequired("HttpHeaders")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateCustomDomainConfigType(v *types.CustomDomainConfigType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CustomDomainConfigType"} + if v.CertificateArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("CertificateArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateCustomEmailLambdaVersionConfigType(v *types.CustomEmailLambdaVersionConfigType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CustomEmailLambdaVersionConfigType"} + if len(v.LambdaVersion) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("LambdaVersion")) + } + if v.LambdaArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("LambdaArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateCustomSMSLambdaVersionConfigType(v *types.CustomSMSLambdaVersionConfigType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CustomSMSLambdaVersionConfigType"} + if len(v.LambdaVersion) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("LambdaVersion")) + } + if v.LambdaArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("LambdaArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateLambdaConfigType(v *types.LambdaConfigType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "LambdaConfigType"} + if v.PreTokenGenerationConfig != nil { + if err := validatePreTokenGenerationVersionConfigType(v.PreTokenGenerationConfig); err != nil { + invalidParams.AddNested("PreTokenGenerationConfig", err.(smithy.InvalidParamsError)) + } + } + if v.CustomSMSSender != nil { + if err := validateCustomSMSLambdaVersionConfigType(v.CustomSMSSender); err != nil { + invalidParams.AddNested("CustomSMSSender", err.(smithy.InvalidParamsError)) + } + } + if v.CustomEmailSender != nil { + if err := validateCustomEmailLambdaVersionConfigType(v.CustomEmailSender); err != nil { + invalidParams.AddNested("CustomEmailSender", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateLogConfigurationListType(v []types.LogConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "LogConfigurationListType"} + for i := range v { + if err := validateLogConfigurationType(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateLogConfigurationType(v *types.LogConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "LogConfigurationType"} + if len(v.LogLevel) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("LogLevel")) + } + if len(v.EventSource) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("EventSource")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateNotifyConfigurationType(v *types.NotifyConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "NotifyConfigurationType"} + if v.SourceArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("SourceArn")) + } + if v.BlockEmail != nil { + if err := validateNotifyEmailType(v.BlockEmail); err != nil { + invalidParams.AddNested("BlockEmail", err.(smithy.InvalidParamsError)) + } + } + if v.NoActionEmail != nil { + if err := validateNotifyEmailType(v.NoActionEmail); err != nil { + invalidParams.AddNested("NoActionEmail", err.(smithy.InvalidParamsError)) + } + } + if v.MfaEmail != nil { + if err := validateNotifyEmailType(v.MfaEmail); err != nil { + invalidParams.AddNested("MfaEmail", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateNotifyEmailType(v *types.NotifyEmailType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "NotifyEmailType"} + if v.Subject == nil { + invalidParams.Add(smithy.NewErrParamRequired("Subject")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validatePreTokenGenerationVersionConfigType(v *types.PreTokenGenerationVersionConfigType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "PreTokenGenerationVersionConfigType"} + if len(v.LambdaVersion) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("LambdaVersion")) + } + if v.LambdaArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("LambdaArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateRecoveryMechanismsType(v []types.RecoveryOptionType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "RecoveryMechanismsType"} + for i := range v { + if err := validateRecoveryOptionType(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateRecoveryOptionType(v *types.RecoveryOptionType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "RecoveryOptionType"} + if v.Priority == nil { + invalidParams.Add(smithy.NewErrParamRequired("Priority")) + } + if len(v.Name) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("Name")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateRefreshTokenRotationType(v *types.RefreshTokenRotationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "RefreshTokenRotationType"} + if len(v.Feature) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("Feature")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateResourceServerScopeListType(v []types.ResourceServerScopeType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ResourceServerScopeListType"} + for i := range v { + if err := validateResourceServerScopeType(&v[i]); err != nil { + invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateResourceServerScopeType(v *types.ResourceServerScopeType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ResourceServerScopeType"} + if v.ScopeName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ScopeName")) + } + if v.ScopeDescription == nil { + invalidParams.Add(smithy.NewErrParamRequired("ScopeDescription")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateSmsConfigurationType(v *types.SmsConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SmsConfigurationType"} + if v.SnsCallerArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("SnsCallerArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateSmsMfaConfigType(v *types.SmsMfaConfigType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SmsMfaConfigType"} + if v.SmsConfiguration != nil { + if err := validateSmsConfigurationType(v.SmsConfiguration); err != nil { + invalidParams.AddNested("SmsConfiguration", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateUsernameConfigurationType(v *types.UsernameConfigurationType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UsernameConfigurationType"} + if v.CaseSensitive == nil { + invalidParams.Add(smithy.NewErrParamRequired("CaseSensitive")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateUserPoolAddOnsType(v *types.UserPoolAddOnsType) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UserPoolAddOnsType"} + if len(v.AdvancedSecurityMode) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("AdvancedSecurityMode")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAddCustomAttributesInput(v *AddCustomAttributesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AddCustomAttributesInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.CustomAttributes == nil { + invalidParams.Add(smithy.NewErrParamRequired("CustomAttributes")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminAddUserToGroupInput(v *AdminAddUserToGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminAddUserToGroupInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminConfirmSignUpInput(v *AdminConfirmSignUpInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminConfirmSignUpInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminCreateUserInput(v *AdminCreateUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminCreateUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.UserAttributes != nil { + if err := validateAttributeListType(v.UserAttributes); err != nil { + invalidParams.AddNested("UserAttributes", err.(smithy.InvalidParamsError)) + } + } + if v.ValidationData != nil { + if err := validateAttributeListType(v.ValidationData); err != nil { + invalidParams.AddNested("ValidationData", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminDeleteUserAttributesInput(v *AdminDeleteUserAttributesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminDeleteUserAttributesInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.UserAttributeNames == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserAttributeNames")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminDeleteUserInput(v *AdminDeleteUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminDeleteUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminDisableProviderForUserInput(v *AdminDisableProviderForUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminDisableProviderForUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.User == nil { + invalidParams.Add(smithy.NewErrParamRequired("User")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminDisableUserInput(v *AdminDisableUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminDisableUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminEnableUserInput(v *AdminEnableUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminEnableUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminForgetDeviceInput(v *AdminForgetDeviceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminForgetDeviceInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminGetDeviceInput(v *AdminGetDeviceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminGetDeviceInput"} + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminGetUserInput(v *AdminGetUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminGetUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminInitiateAuthInput(v *AdminInitiateAuthInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminInitiateAuthInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if len(v.AuthFlow) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("AuthFlow")) + } + if v.ContextData != nil { + if err := validateContextDataType(v.ContextData); err != nil { + invalidParams.AddNested("ContextData", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminLinkProviderForUserInput(v *AdminLinkProviderForUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminLinkProviderForUserInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.DestinationUser == nil { + invalidParams.Add(smithy.NewErrParamRequired("DestinationUser")) + } + if v.SourceUser == nil { + invalidParams.Add(smithy.NewErrParamRequired("SourceUser")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminListDevicesInput(v *AdminListDevicesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminListDevicesInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminListGroupsForUserInput(v *AdminListGroupsForUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminListGroupsForUserInput"} + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminListUserAuthEventsInput(v *AdminListUserAuthEventsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminListUserAuthEventsInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminRemoveUserFromGroupInput(v *AdminRemoveUserFromGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminRemoveUserFromGroupInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminResetUserPasswordInput(v *AdminResetUserPasswordInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminResetUserPasswordInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminRespondToAuthChallengeInput(v *AdminRespondToAuthChallengeInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminRespondToAuthChallengeInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if len(v.ChallengeName) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("ChallengeName")) + } + if v.ContextData != nil { + if err := validateContextDataType(v.ContextData); err != nil { + invalidParams.AddNested("ContextData", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminSetUserMFAPreferenceInput(v *AdminSetUserMFAPreferenceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminSetUserMFAPreferenceInput"} + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminSetUserPasswordInput(v *AdminSetUserPasswordInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminSetUserPasswordInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.Password == nil { + invalidParams.Add(smithy.NewErrParamRequired("Password")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminSetUserSettingsInput(v *AdminSetUserSettingsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminSetUserSettingsInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.MFAOptions == nil { + invalidParams.Add(smithy.NewErrParamRequired("MFAOptions")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminUpdateAuthEventFeedbackInput(v *AdminUpdateAuthEventFeedbackInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminUpdateAuthEventFeedbackInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.EventId == nil { + invalidParams.Add(smithy.NewErrParamRequired("EventId")) + } + if len(v.FeedbackValue) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("FeedbackValue")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminUpdateDeviceStatusInput(v *AdminUpdateDeviceStatusInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminUpdateDeviceStatusInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminUpdateUserAttributesInput(v *AdminUpdateUserAttributesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminUpdateUserAttributesInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.UserAttributes == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserAttributes")) + } else if v.UserAttributes != nil { + if err := validateAttributeListType(v.UserAttributes); err != nil { + invalidParams.AddNested("UserAttributes", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpAdminUserGlobalSignOutInput(v *AdminUserGlobalSignOutInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "AdminUserGlobalSignOutInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpChangePasswordInput(v *ChangePasswordInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ChangePasswordInput"} + if v.ProposedPassword == nil { + invalidParams.Add(smithy.NewErrParamRequired("ProposedPassword")) + } + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCompleteWebAuthnRegistrationInput(v *CompleteWebAuthnRegistrationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CompleteWebAuthnRegistrationInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.Credential == nil { + invalidParams.Add(smithy.NewErrParamRequired("Credential")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpConfirmDeviceInput(v *ConfirmDeviceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ConfirmDeviceInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpConfirmForgotPasswordInput(v *ConfirmForgotPasswordInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ConfirmForgotPasswordInput"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.ConfirmationCode == nil { + invalidParams.Add(smithy.NewErrParamRequired("ConfirmationCode")) + } + if v.Password == nil { + invalidParams.Add(smithy.NewErrParamRequired("Password")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpConfirmSignUpInput(v *ConfirmSignUpInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ConfirmSignUpInput"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.ConfirmationCode == nil { + invalidParams.Add(smithy.NewErrParamRequired("ConfirmationCode")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateGroupInput(v *CreateGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateGroupInput"} + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateIdentityProviderInput(v *CreateIdentityProviderInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateIdentityProviderInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ProviderName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ProviderName")) + } + if len(v.ProviderType) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("ProviderType")) + } + if v.ProviderDetails == nil { + invalidParams.Add(smithy.NewErrParamRequired("ProviderDetails")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateManagedLoginBrandingInput(v *CreateManagedLoginBrandingInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateManagedLoginBrandingInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.Assets != nil { + if err := validateAssetListType(v.Assets); err != nil { + invalidParams.AddNested("Assets", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateResourceServerInput(v *CreateResourceServerInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateResourceServerInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Identifier == nil { + invalidParams.Add(smithy.NewErrParamRequired("Identifier")) + } + if v.Name == nil { + invalidParams.Add(smithy.NewErrParamRequired("Name")) + } + if v.Scopes != nil { + if err := validateResourceServerScopeListType(v.Scopes); err != nil { + invalidParams.AddNested("Scopes", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateUserImportJobInput(v *CreateUserImportJobInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateUserImportJobInput"} + if v.JobName == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobName")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.CloudWatchLogsRoleArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("CloudWatchLogsRoleArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateUserPoolClientInput(v *CreateUserPoolClientInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateUserPoolClientInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientName")) + } + if v.RefreshTokenRotation != nil { + if err := validateRefreshTokenRotationType(v.RefreshTokenRotation); err != nil { + invalidParams.AddNested("RefreshTokenRotation", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateUserPoolDomainInput(v *CreateUserPoolDomainInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateUserPoolDomainInput"} + if v.Domain == nil { + invalidParams.Add(smithy.NewErrParamRequired("Domain")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.CustomDomainConfig != nil { + if err := validateCustomDomainConfigType(v.CustomDomainConfig); err != nil { + invalidParams.AddNested("CustomDomainConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateUserPoolInput(v *CreateUserPoolInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateUserPoolInput"} + if v.PoolName == nil { + invalidParams.Add(smithy.NewErrParamRequired("PoolName")) + } + if v.LambdaConfig != nil { + if err := validateLambdaConfigType(v.LambdaConfig); err != nil { + invalidParams.AddNested("LambdaConfig", err.(smithy.InvalidParamsError)) + } + } + if v.SmsConfiguration != nil { + if err := validateSmsConfigurationType(v.SmsConfiguration); err != nil { + invalidParams.AddNested("SmsConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.UserPoolAddOns != nil { + if err := validateUserPoolAddOnsType(v.UserPoolAddOns); err != nil { + invalidParams.AddNested("UserPoolAddOns", err.(smithy.InvalidParamsError)) + } + } + if v.UsernameConfiguration != nil { + if err := validateUsernameConfigurationType(v.UsernameConfiguration); err != nil { + invalidParams.AddNested("UsernameConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.AccountRecoverySetting != nil { + if err := validateAccountRecoverySettingType(v.AccountRecoverySetting); err != nil { + invalidParams.AddNested("AccountRecoverySetting", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteGroupInput(v *DeleteGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteGroupInput"} + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteIdentityProviderInput(v *DeleteIdentityProviderInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteIdentityProviderInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ProviderName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ProviderName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteManagedLoginBrandingInput(v *DeleteManagedLoginBrandingInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteManagedLoginBrandingInput"} + if v.ManagedLoginBrandingId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ManagedLoginBrandingId")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteResourceServerInput(v *DeleteResourceServerInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteResourceServerInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Identifier == nil { + invalidParams.Add(smithy.NewErrParamRequired("Identifier")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteUserAttributesInput(v *DeleteUserAttributesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteUserAttributesInput"} + if v.UserAttributeNames == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserAttributeNames")) + } + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteUserInput(v *DeleteUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteUserInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteUserPoolClientInput(v *DeleteUserPoolClientInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteUserPoolClientInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteUserPoolDomainInput(v *DeleteUserPoolDomainInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteUserPoolDomainInput"} + if v.Domain == nil { + invalidParams.Add(smithy.NewErrParamRequired("Domain")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteUserPoolInput(v *DeleteUserPoolInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteUserPoolInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDeleteWebAuthnCredentialInput(v *DeleteWebAuthnCredentialInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DeleteWebAuthnCredentialInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.CredentialId == nil { + invalidParams.Add(smithy.NewErrParamRequired("CredentialId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeIdentityProviderInput(v *DescribeIdentityProviderInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeIdentityProviderInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ProviderName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ProviderName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeManagedLoginBrandingByClientInput(v *DescribeManagedLoginBrandingByClientInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeManagedLoginBrandingByClientInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeManagedLoginBrandingInput(v *DescribeManagedLoginBrandingInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeManagedLoginBrandingInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ManagedLoginBrandingId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ManagedLoginBrandingId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeResourceServerInput(v *DescribeResourceServerInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeResourceServerInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Identifier == nil { + invalidParams.Add(smithy.NewErrParamRequired("Identifier")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeRiskConfigurationInput(v *DescribeRiskConfigurationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeRiskConfigurationInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeUserImportJobInput(v *DescribeUserImportJobInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeUserImportJobInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeUserPoolClientInput(v *DescribeUserPoolClientInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeUserPoolClientInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeUserPoolDomainInput(v *DescribeUserPoolDomainInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeUserPoolDomainInput"} + if v.Domain == nil { + invalidParams.Add(smithy.NewErrParamRequired("Domain")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpDescribeUserPoolInput(v *DescribeUserPoolInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "DescribeUserPoolInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpForgetDeviceInput(v *ForgetDeviceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ForgetDeviceInput"} + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpForgotPasswordInput(v *ForgotPasswordInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ForgotPasswordInput"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetCSVHeaderInput(v *GetCSVHeaderInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetCSVHeaderInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetDeviceInput(v *GetDeviceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetDeviceInput"} + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetGroupInput(v *GetGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetGroupInput"} + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetIdentityProviderByIdentifierInput(v *GetIdentityProviderByIdentifierInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetIdentityProviderByIdentifierInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.IdpIdentifier == nil { + invalidParams.Add(smithy.NewErrParamRequired("IdpIdentifier")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetLogDeliveryConfigurationInput(v *GetLogDeliveryConfigurationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetLogDeliveryConfigurationInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetSigningCertificateInput(v *GetSigningCertificateInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetSigningCertificateInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetTokensFromRefreshTokenInput(v *GetTokensFromRefreshTokenInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetTokensFromRefreshTokenInput"} + if v.RefreshToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("RefreshToken")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetUICustomizationInput(v *GetUICustomizationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetUICustomizationInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetUserAttributeVerificationCodeInput(v *GetUserAttributeVerificationCodeInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetUserAttributeVerificationCodeInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.AttributeName == nil { + invalidParams.Add(smithy.NewErrParamRequired("AttributeName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetUserAuthFactorsInput(v *GetUserAuthFactorsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetUserAuthFactorsInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetUserInput(v *GetUserInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetUserInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGetUserPoolMfaConfigInput(v *GetUserPoolMfaConfigInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetUserPoolMfaConfigInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpGlobalSignOutInput(v *GlobalSignOutInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GlobalSignOutInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpInitiateAuthInput(v *InitiateAuthInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "InitiateAuthInput"} + if len(v.AuthFlow) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("AuthFlow")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListDevicesInput(v *ListDevicesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListDevicesInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListGroupsInput(v *ListGroupsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListGroupsInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListIdentityProvidersInput(v *ListIdentityProvidersInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListIdentityProvidersInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListResourceServersInput(v *ListResourceServersInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListResourceServersInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListTagsForResourceInput(v *ListTagsForResourceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListTagsForResourceInput"} + if v.ResourceArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("ResourceArn")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListUserImportJobsInput(v *ListUserImportJobsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListUserImportJobsInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.MaxResults == nil { + invalidParams.Add(smithy.NewErrParamRequired("MaxResults")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListUserPoolClientsInput(v *ListUserPoolClientsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListUserPoolClientsInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListUserPoolsInput(v *ListUserPoolsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListUserPoolsInput"} + if v.MaxResults == nil { + invalidParams.Add(smithy.NewErrParamRequired("MaxResults")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListUsersInGroupInput(v *ListUsersInGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListUsersInGroupInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListUsersInput(v *ListUsersInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListUsersInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpListWebAuthnCredentialsInput(v *ListWebAuthnCredentialsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ListWebAuthnCredentialsInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpResendConfirmationCodeInput(v *ResendConfirmationCodeInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "ResendConfirmationCodeInput"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpRespondToAuthChallengeInput(v *RespondToAuthChallengeInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "RespondToAuthChallengeInput"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if len(v.ChallengeName) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("ChallengeName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpRevokeTokenInput(v *RevokeTokenInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "RevokeTokenInput"} + if v.Token == nil { + invalidParams.Add(smithy.NewErrParamRequired("Token")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSetLogDeliveryConfigurationInput(v *SetLogDeliveryConfigurationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SetLogDeliveryConfigurationInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.LogConfigurations == nil { + invalidParams.Add(smithy.NewErrParamRequired("LogConfigurations")) + } else if v.LogConfigurations != nil { + if err := validateLogConfigurationListType(v.LogConfigurations); err != nil { + invalidParams.AddNested("LogConfigurations", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSetRiskConfigurationInput(v *SetRiskConfigurationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SetRiskConfigurationInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.CompromisedCredentialsRiskConfiguration != nil { + if err := validateCompromisedCredentialsRiskConfigurationType(v.CompromisedCredentialsRiskConfiguration); err != nil { + invalidParams.AddNested("CompromisedCredentialsRiskConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.AccountTakeoverRiskConfiguration != nil { + if err := validateAccountTakeoverRiskConfigurationType(v.AccountTakeoverRiskConfiguration); err != nil { + invalidParams.AddNested("AccountTakeoverRiskConfiguration", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSetUICustomizationInput(v *SetUICustomizationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SetUICustomizationInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSetUserMFAPreferenceInput(v *SetUserMFAPreferenceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SetUserMFAPreferenceInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSetUserPoolMfaConfigInput(v *SetUserPoolMfaConfigInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SetUserPoolMfaConfigInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.SmsMfaConfiguration != nil { + if err := validateSmsMfaConfigType(v.SmsMfaConfiguration); err != nil { + invalidParams.AddNested("SmsMfaConfiguration", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSetUserSettingsInput(v *SetUserSettingsInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SetUserSettingsInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.MFAOptions == nil { + invalidParams.Add(smithy.NewErrParamRequired("MFAOptions")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpSignUpInput(v *SignUpInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "SignUpInput"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.UserAttributes != nil { + if err := validateAttributeListType(v.UserAttributes); err != nil { + invalidParams.AddNested("UserAttributes", err.(smithy.InvalidParamsError)) + } + } + if v.ValidationData != nil { + if err := validateAttributeListType(v.ValidationData); err != nil { + invalidParams.AddNested("ValidationData", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStartUserImportJobInput(v *StartUserImportJobInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StartUserImportJobInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStartWebAuthnRegistrationInput(v *StartWebAuthnRegistrationInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StartWebAuthnRegistrationInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpStopUserImportJobInput(v *StopUserImportJobInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "StopUserImportJobInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.JobId == nil { + invalidParams.Add(smithy.NewErrParamRequired("JobId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpTagResourceInput(v *TagResourceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "TagResourceInput"} + if v.ResourceArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("ResourceArn")) + } + if v.Tags == nil { + invalidParams.Add(smithy.NewErrParamRequired("Tags")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUntagResourceInput(v *UntagResourceInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UntagResourceInput"} + if v.ResourceArn == nil { + invalidParams.Add(smithy.NewErrParamRequired("ResourceArn")) + } + if v.TagKeys == nil { + invalidParams.Add(smithy.NewErrParamRequired("TagKeys")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateAuthEventFeedbackInput(v *UpdateAuthEventFeedbackInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateAuthEventFeedbackInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Username == nil { + invalidParams.Add(smithy.NewErrParamRequired("Username")) + } + if v.EventId == nil { + invalidParams.Add(smithy.NewErrParamRequired("EventId")) + } + if v.FeedbackToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("FeedbackToken")) + } + if len(v.FeedbackValue) == 0 { + invalidParams.Add(smithy.NewErrParamRequired("FeedbackValue")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateDeviceStatusInput(v *UpdateDeviceStatusInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateDeviceStatusInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.DeviceKey == nil { + invalidParams.Add(smithy.NewErrParamRequired("DeviceKey")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateGroupInput(v *UpdateGroupInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateGroupInput"} + if v.GroupName == nil { + invalidParams.Add(smithy.NewErrParamRequired("GroupName")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateIdentityProviderInput(v *UpdateIdentityProviderInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateIdentityProviderInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ProviderName == nil { + invalidParams.Add(smithy.NewErrParamRequired("ProviderName")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateManagedLoginBrandingInput(v *UpdateManagedLoginBrandingInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateManagedLoginBrandingInput"} + if v.Assets != nil { + if err := validateAssetListType(v.Assets); err != nil { + invalidParams.AddNested("Assets", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateResourceServerInput(v *UpdateResourceServerInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateResourceServerInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.Identifier == nil { + invalidParams.Add(smithy.NewErrParamRequired("Identifier")) + } + if v.Name == nil { + invalidParams.Add(smithy.NewErrParamRequired("Name")) + } + if v.Scopes != nil { + if err := validateResourceServerScopeListType(v.Scopes); err != nil { + invalidParams.AddNested("Scopes", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateUserAttributesInput(v *UpdateUserAttributesInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateUserAttributesInput"} + if v.UserAttributes == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserAttributes")) + } else if v.UserAttributes != nil { + if err := validateAttributeListType(v.UserAttributes); err != nil { + invalidParams.AddNested("UserAttributes", err.(smithy.InvalidParamsError)) + } + } + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateUserPoolClientInput(v *UpdateUserPoolClientInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateUserPoolClientInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.RefreshTokenRotation != nil { + if err := validateRefreshTokenRotationType(v.RefreshTokenRotation); err != nil { + invalidParams.AddNested("RefreshTokenRotation", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateUserPoolDomainInput(v *UpdateUserPoolDomainInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateUserPoolDomainInput"} + if v.Domain == nil { + invalidParams.Add(smithy.NewErrParamRequired("Domain")) + } + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.CustomDomainConfig != nil { + if err := validateCustomDomainConfigType(v.CustomDomainConfig); err != nil { + invalidParams.AddNested("CustomDomainConfig", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpUpdateUserPoolInput(v *UpdateUserPoolInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "UpdateUserPoolInput"} + if v.UserPoolId == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserPoolId")) + } + if v.LambdaConfig != nil { + if err := validateLambdaConfigType(v.LambdaConfig); err != nil { + invalidParams.AddNested("LambdaConfig", err.(smithy.InvalidParamsError)) + } + } + if v.SmsConfiguration != nil { + if err := validateSmsConfigurationType(v.SmsConfiguration); err != nil { + invalidParams.AddNested("SmsConfiguration", err.(smithy.InvalidParamsError)) + } + } + if v.UserPoolAddOns != nil { + if err := validateUserPoolAddOnsType(v.UserPoolAddOns); err != nil { + invalidParams.AddNested("UserPoolAddOns", err.(smithy.InvalidParamsError)) + } + } + if v.AccountRecoverySetting != nil { + if err := validateAccountRecoverySettingType(v.AccountRecoverySetting); err != nil { + invalidParams.AddNested("AccountRecoverySetting", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpVerifySoftwareTokenInput(v *VerifySoftwareTokenInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "VerifySoftwareTokenInput"} + if v.UserCode == nil { + invalidParams.Add(smithy.NewErrParamRequired("UserCode")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpVerifyUserAttributeInput(v *VerifyUserAttributeInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "VerifyUserAttributeInput"} + if v.AccessToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) + } + if v.AttributeName == nil { + invalidParams.Add(smithy.NewErrParamRequired("AttributeName")) + } + if v.Code == nil { + invalidParams.Add(smithy.NewErrParamRequired("Code")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} diff --git a/vendor/github.com/aws/smithy-go/document/internal/serde/field.go b/vendor/github.com/aws/smithy-go/document/internal/serde/field.go new file mode 100644 index 00000000..64a9fdb3 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/internal/serde/field.go @@ -0,0 +1,293 @@ +package serde + +import ( + "reflect" + "sort" +) + +const tagKey = "document" + +// Field is represents a struct field, tag, type, and index. +type Field struct { + Tag + + Name string + NameFromTag bool + + Index []int + Type reflect.Type +} + +func buildField(pIdx []int, i int, sf reflect.StructField, fieldTag Tag) Field { + f := Field{ + Name: sf.Name, + Type: sf.Type, + Tag: fieldTag, + } + + if len(fieldTag.Name) != 0 { + f.NameFromTag = true + f.Name = fieldTag.Name + } + + f.Index = make([]int, len(pIdx)+1) + copy(f.Index, pIdx) + f.Index[len(pIdx)] = i + + return f +} + +// GetStructFields returns a list of fields for the given type. Type info is cached +// to avoid repeated calls into the reflect package +func GetStructFields(t reflect.Type) *CachedFields { + if cached, ok := fieldCache.Load(t); ok { + return cached + } + + f := enumFields(t) + sort.Sort(fieldsByName(f)) + f = visibleFields(f) + + fs := &CachedFields{ + fields: f, + fieldsByName: make(map[string]int, len(f)), + } + for i, f := range fs.fields { + fs.fieldsByName[f.Name] = i + } + + cached, _ := fieldCache.LoadOrStore(t, fs) + return cached +} + +// enumFields will recursively iterate through a structure and its nested +// anonymous fields. +// +// Based on the enoding/json struct field enumeration of the Go Stdlib +// https://golang.org/src/encoding/json/encode.go typeField func. +func enumFields(t reflect.Type) []Field { + // Fields to explore + current := []Field{} + next := []Field{{Type: t}} + + // count of queued names + count := map[reflect.Type]int{} + nextCount := map[reflect.Type]int{} + + visited := map[reflect.Type]struct{}{} + fields := []Field{} + + for len(next) > 0 { + current, next = next, current[:0] + count, nextCount = nextCount, map[reflect.Type]int{} + + for _, f := range current { + if _, ok := visited[f.Type]; ok { + continue + } + visited[f.Type] = struct{}{} + + for i := 0; i < f.Type.NumField(); i++ { + sf := f.Type.Field(i) + if sf.PkgPath != "" && !sf.Anonymous { + // Ignore unexported and non-anonymous fields + // unexported but anonymous field may still be used if + // the type has exported nested fields + continue + } + + fieldTag := ParseTag(sf.Tag.Get(tagKey)) + + if fieldTag.Ignore { + continue + } + + ft := sf.Type + if ft.Name() == "" && ft.Kind() == reflect.Ptr { + ft = ft.Elem() + } + + structField := buildField(f.Index, i, sf, fieldTag) + structField.Type = ft + + if !sf.Anonymous || ft.Kind() != reflect.Struct { + fields = append(fields, structField) + if count[f.Type] > 1 { + // If there were multiple instances, add a second, + // so that the annihilation code will see a duplicate. + // It only cares about the distinction between 1 or 2, + // so don't bother generating any more copies. + fields = append(fields, structField) + } + continue + } + + // Record new anon struct to explore next round + nextCount[ft]++ + if nextCount[ft] == 1 { + next = append(next, structField) + } + } + } + } + + return fields +} + +// visibleFields will return a slice of fields which are visible based on +// Go's standard visiblity rules with the exception of ties being broken +// by depth and struct tag naming. +// +// Based on the enoding/json field filtering of the Go Stdlib +// https://golang.org/src/encoding/json/encode.go typeField func. +func visibleFields(fields []Field) []Field { + // Delete all fields that are hidden by the Go rules for embedded fields, + // except that fields with JSON tags are promoted. + + // The fields are sorted in primary order of name, secondary order + // of field index length. Loop over names; for each name, delete + // hidden fields by choosing the one dominant field that survives. + out := fields[:0] + for advance, i := 0, 0; i < len(fields); i += advance { + // One iteration per name. + // Find the sequence of fields with the name of this first field. + fi := fields[i] + name := fi.Name + for advance = 1; i+advance < len(fields); advance++ { + fj := fields[i+advance] + if fj.Name != name { + break + } + } + if advance == 1 { // Only one field with this name + out = append(out, fi) + continue + } + dominant, ok := dominantField(fields[i : i+advance]) + if ok { + out = append(out, dominant) + } + } + + fields = out + sort.Sort(fieldsByIndex(fields)) + + return fields +} + +// dominantField looks through the fields, all of which are known to +// have the same name, to find the single field that dominates the +// others using Go's embedding rules, modified by the presence of +// JSON tags. If there are multiple top-level fields, the boolean +// will be false: This condition is an error in Go and we skip all +// the fields. +// +// Based on the enoding/json field filtering of the Go Stdlib +// https://golang.org/src/encoding/json/encode.go dominantField func. +func dominantField(fields []Field) (Field, bool) { + // The fields are sorted in increasing index-length order. The winner + // must therefore be one with the shortest index length. Drop all + // longer entries, which is easy: just truncate the slice. + length := len(fields[0].Index) + tagged := -1 // Index of first tagged field. + for i, f := range fields { + if len(f.Index) > length { + fields = fields[:i] + break + } + if f.NameFromTag { + if tagged >= 0 { + // Multiple tagged fields at the same level: conflict. + // Return no field. + return Field{}, false + } + tagged = i + } + } + if tagged >= 0 { + return fields[tagged], true + } + // All remaining fields have the same length. If there's more than one, + // we have a conflict (two fields named "X" at the same level) and we + // return no field. + if len(fields) > 1 { + return Field{}, false + } + return fields[0], true +} + +// fieldsByName sorts field by name, breaking ties with depth, +// then breaking ties with "name came from json tag", then +// breaking ties with index sequence. +// +// Based on the enoding/json field filtering of the Go Stdlib +// https://golang.org/src/encoding/json/encode.go fieldsByName type. +type fieldsByName []Field + +func (x fieldsByName) Len() int { return len(x) } + +func (x fieldsByName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } + +func (x fieldsByName) Less(i, j int) bool { + if x[i].Name != x[j].Name { + return x[i].Name < x[j].Name + } + if len(x[i].Index) != len(x[j].Index) { + return len(x[i].Index) < len(x[j].Index) + } + if x[i].NameFromTag != x[j].NameFromTag { + return x[i].NameFromTag + } + return fieldsByIndex(x).Less(i, j) +} + +// fieldsByIndex sorts field by index sequence. +// +// Based on the enoding/json field filtering of the Go Stdlib +// https://golang.org/src/encoding/json/encode.go fieldsByIndex type. +type fieldsByIndex []Field + +func (x fieldsByIndex) Len() int { return len(x) } + +func (x fieldsByIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } + +func (x fieldsByIndex) Less(i, j int) bool { + for k, xik := range x[i].Index { + if k >= len(x[j].Index) { + return false + } + if xik != x[j].Index[k] { + return xik < x[j].Index[k] + } + } + return len(x[i].Index) < len(x[j].Index) +} + +// DecoderFieldByIndex finds the field with the provided nested index, allocating +// embedded parent structs if needed +func DecoderFieldByIndex(v reflect.Value, index []int) reflect.Value { + for i, x := range index { + if i > 0 && v.Kind() == reflect.Ptr && v.Type().Elem().Kind() == reflect.Struct { + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + } + v = v.Field(x) + } + return v +} + +// EncoderFieldByIndex finds the field with the provided nested index +func EncoderFieldByIndex(v reflect.Value, index []int) (reflect.Value, bool) { + for i, x := range index { + if i > 0 && v.Kind() == reflect.Ptr && v.Type().Elem().Kind() == reflect.Struct { + if v.IsNil() { + return reflect.Value{}, false + } + v = v.Elem() + } + v = v.Field(x) + } + return v, true +} diff --git a/vendor/github.com/aws/smithy-go/document/internal/serde/field_cache.go b/vendor/github.com/aws/smithy-go/document/internal/serde/field_cache.go new file mode 100644 index 00000000..b00569e4 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/internal/serde/field_cache.go @@ -0,0 +1,48 @@ +package serde + +import ( + "strings" + "sync" +) + +var fieldCache fieldCacher + +type fieldCacher struct { + cache sync.Map +} + +func (c *fieldCacher) Load(t interface{}) (*CachedFields, bool) { + if v, ok := c.cache.Load(t); ok { + return v.(*CachedFields), true + } + return nil, false +} + +func (c *fieldCacher) LoadOrStore(t interface{}, fs *CachedFields) (*CachedFields, bool) { + v, ok := c.cache.LoadOrStore(t, fs) + return v.(*CachedFields), ok +} + +// CachedFields is a cache entry for a type's fields. +type CachedFields struct { + fields []Field + fieldsByName map[string]int +} + +// All returns all the fields for the cached type. +func (f *CachedFields) All() []Field { + return f.fields +} + +// FieldByName retrieves a field by name. +func (f *CachedFields) FieldByName(name string) (Field, bool) { + if i, ok := f.fieldsByName[name]; ok { + return f.fields[i], ok + } + for _, f := range f.fields { + if strings.EqualFold(f.Name, name) { + return f, true + } + } + return Field{}, false +} diff --git a/vendor/github.com/aws/smithy-go/document/internal/serde/reflect.go b/vendor/github.com/aws/smithy-go/document/internal/serde/reflect.go new file mode 100644 index 00000000..165145cd --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/internal/serde/reflect.go @@ -0,0 +1,24 @@ +package serde + +import ( + "github.com/aws/smithy-go/document" + "math/big" + "reflect" + "time" +) + +// ReflectTypeOf is a structure containing various reflect.Type members that are useful +// to document Marshaler or Unmarshaler implementations. +var ReflectTypeOf = struct { + BigFloat reflect.Type + BigInt reflect.Type + DocumentNumber reflect.Type + MapStringToInterface reflect.Type + Time reflect.Type +}{ + BigFloat: reflect.TypeOf((*big.Float)(nil)).Elem(), + BigInt: reflect.TypeOf((*big.Int)(nil)).Elem(), + DocumentNumber: reflect.TypeOf((*document.Number)(nil)).Elem(), + MapStringToInterface: reflect.TypeOf((map[string]interface{})(nil)), + Time: reflect.TypeOf((*time.Time)(nil)).Elem(), +} diff --git a/vendor/github.com/aws/smithy-go/document/internal/serde/serde.go b/vendor/github.com/aws/smithy-go/document/internal/serde/serde.go new file mode 100644 index 00000000..c2bdbd38 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/internal/serde/serde.go @@ -0,0 +1,100 @@ +package serde + +import ( + "reflect" +) + +// Indirect will walk a value's interface or pointer value types. Returning +// the final value or the value a unmarshaler is defined on. +// +// Based on the enoding/json type reflect value type indirection in Go Stdlib +// https://golang.org/src/encoding/json/decode.go Indirect func. +func Indirect(v reflect.Value, decodingNull bool) reflect.Value { + v0 := v + haveAddr := false + + if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { + v = v.Addr() + haveAddr = true + } + for { + if v.Kind() == reflect.Interface && !v.IsNil() { + e := v.Elem() + if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { + haveAddr = false + v = e + continue + } + } + if v.Kind() != reflect.Ptr { + break + } + if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { + break + } + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + + if haveAddr { + v = v0 + haveAddr = false + } else { + v = v.Elem() + } + } + + return v +} + +// PtrToValue given the input value will dereference pointers and returning the element pointed to. +func PtrToValue(in interface{}) interface{} { + v := reflect.ValueOf(in) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if !v.IsValid() { + return nil + } + if v.Kind() == reflect.Ptr { + return PtrToValue(v.Interface()) + } + return v.Interface() +} + +// IsZeroValue returns whether v is the zero-value for its type. +func IsZeroValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Invalid: + return true + case reflect.Array: + return v.Len() == 0 + case reflect.Map, reflect.Slice: + return v.IsNil() + case reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} + +// ValueElem walks interface and pointer types and returns the underlying element. +func ValueElem(v reflect.Value) reflect.Value { + switch v.Kind() { + case reflect.Interface, reflect.Ptr: + for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr { + v = v.Elem() + } + } + + return v +} diff --git a/vendor/github.com/aws/smithy-go/document/internal/serde/tags.go b/vendor/github.com/aws/smithy-go/document/internal/serde/tags.go new file mode 100644 index 00000000..2097f12b --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/internal/serde/tags.go @@ -0,0 +1,38 @@ +package serde + +import ( + "strings" +) + +// Tag represents the `document` struct field tag and associated options +type Tag struct { + Name string + Ignore bool + OmitEmpty bool +} + +// ParseTag splits a struct field tag into its name and +// comma-separated options. +func ParseTag(tagStr string) (tag Tag) { + parts := strings.Split(tagStr, ",") + if len(parts) == 0 { + return tag + } + + if name := parts[0]; name == "-" { + tag.Name = "" + tag.Ignore = true + } else { + tag.Name = name + tag.Ignore = false + } + + for _, opt := range parts[1:] { + switch opt { + case "omitempty": + tag.OmitEmpty = true + } + } + + return tag +} diff --git a/vendor/github.com/aws/smithy-go/document/json/decoder.go b/vendor/github.com/aws/smithy-go/document/json/decoder.go new file mode 100644 index 00000000..366406c7 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/json/decoder.go @@ -0,0 +1,349 @@ +package json + +import ( + "encoding/json" + "fmt" + "math/big" + "reflect" + + "github.com/aws/smithy-go/document" + "github.com/aws/smithy-go/document/internal/serde" +) + +// DecoderOptions is the set of options that can be configured for a Decoder. +type DecoderOptions struct{} + +// Decoder is a Smithy document decoder for JSON based protocols. +type Decoder struct { + options DecoderOptions +} + +// DecodeJSONInterface decodes the supported JSON input types and stores the result in the value pointed by toValue. +// +// If toValue is not a compatible type, or an error occurs while decoding DecodeJSONInterface will return an error. +// +// The supported input JSON types are: +// bool -> JSON boolean +// float64 -> JSON number +// json.Number -> JSON number +// string -> JSON string +// []interface{} -> JSON array +// map[string]interface{} -> JSON object +// nil -> JSON null +// +func (d *Decoder) DecodeJSONInterface(input interface{}, toValue interface{}) error { + if document.IsNoSerde(toValue) { + return fmt.Errorf("unsupported type: %T", toValue) + } + + v := reflect.ValueOf(toValue) + + if v.Kind() != reflect.Ptr || v.IsNil() || !v.IsValid() { + return &document.InvalidUnmarshalError{Type: reflect.TypeOf(toValue)} + } + + return d.decode(input, v, serde.Tag{}) +} + +func (d *Decoder) decode(jv interface{}, rv reflect.Value, tag serde.Tag) error { + if jv == nil { + rv := serde.Indirect(rv, true) + return d.decodeJSONNull(rv) + } + + rv = serde.Indirect(rv, false) + + if err := d.unsupportedType(jv, rv); err != nil { + return err + } + + switch tv := jv.(type) { + case bool: + return d.decodeJSONBoolean(tv, rv) + case json.Number: + return d.decodeJSONNumber(tv, rv) + case float64: + return d.decodeJSONFloat64(tv, rv) + case string: + return d.decodeJSONString(tv, rv) + case []interface{}: + return d.decodeJSONArray(tv, rv) + case map[string]interface{}: + return d.decodeJSONObject(tv, rv) + default: + return fmt.Errorf("unsupported json type, %T", tv) + } +} + +func (d *Decoder) decodeJSONNull(rv reflect.Value) error { + if rv.IsValid() && rv.CanSet() { + rv.Set(reflect.Zero(rv.Type())) + } + + return nil +} + +func (d *Decoder) decodeJSONBoolean(tv bool, rv reflect.Value) error { + switch rv.Kind() { + case reflect.Bool, reflect.Interface: + rv.Set(reflect.ValueOf(tv).Convert(rv.Type())) + default: + return &document.UnmarshalTypeError{Value: "bool", Type: rv.Type()} + } + + return nil +} + +func (d *Decoder) decodeJSONNumber(tv json.Number, rv reflect.Value) error { + switch rv.Kind() { + case reflect.Interface: + rv.Set(reflect.ValueOf(document.Number(tv))) + case reflect.String: + // covers document.Number + rv.SetString(tv.String()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + i, err := tv.Int64() + if err != nil { + return err + } + if rv.OverflowInt(i) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("number overflow, %s", tv.String()), + Type: rv.Type(), + } + } + rv.SetInt(i) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + u, err := document.Number(tv).Uint64() + if err != nil { + return err + } + if rv.OverflowUint(u) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("number overflow, %s", tv.String()), + Type: rv.Type(), + } + } + rv.SetUint(u) + case reflect.Float32: + f, err := document.Number(tv).Float32() + if err != nil { + return err + } + if rv.OverflowFloat(f) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("float overflow, %s", tv.String()), + Type: rv.Type(), + } + } + rv.SetFloat(f) + case reflect.Float64: + f, err := document.Number(tv).Float64() + if err != nil { + return err + } + if rv.OverflowFloat(f) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("float overflow, %s", tv.String()), + Type: rv.Type(), + } + } + rv.SetFloat(f) + default: + rvt := rv.Type() + switch { + case rvt.ConvertibleTo(serde.ReflectTypeOf.BigFloat): + sv := tv.String() + f, ok := (&big.Float{}).SetString(sv) + if !ok { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("invalid number format, %s", sv), + Type: rv.Type(), + } + } + rv.Set(reflect.ValueOf(*f).Convert(rvt)) + case rvt.ConvertibleTo(serde.ReflectTypeOf.BigInt): + sv := tv.String() + i, ok := (&big.Int{}).SetString(sv, 10) + if !ok { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("invalid number format, %s", sv), + Type: rv.Type(), + } + } + rv.Set(reflect.ValueOf(*i).Convert(rvt)) + default: + return &document.UnmarshalTypeError{Value: "number", Type: rv.Type()} + } + } + + return nil +} + +func (d *Decoder) decodeJSONFloat64(tv float64, rv reflect.Value) error { + switch rv.Kind() { + case reflect.Interface: + rv.Set(reflect.ValueOf(tv)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + i, accuracy := big.NewFloat(tv).Int64() + if accuracy != big.Exact || rv.OverflowInt(i) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("number overflow, %e", tv), + Type: rv.Type(), + } + } + rv.SetInt(i) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + u, accuracy := big.NewFloat(tv).Uint64() + if accuracy != big.Exact || rv.OverflowUint(u) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("number overflow, %e", tv), + Type: rv.Type(), + } + } + rv.SetUint(u) + case reflect.Float32, reflect.Float64: + if rv.OverflowFloat(tv) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("float overflow, %e", tv), + Type: rv.Type(), + } + } + rv.SetFloat(tv) + default: + rvt := rv.Type() + switch { + case rvt.ConvertibleTo(serde.ReflectTypeOf.BigFloat): + f := big.NewFloat(tv) + rv.Set(reflect.ValueOf(*f).Convert(rvt)) + case rvt.ConvertibleTo(serde.ReflectTypeOf.BigInt): + i, accuracy := big.NewFloat(tv).Int(nil) + if accuracy != big.Exact { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("int overflow, %e", tv), + Type: rv.Type(), + } + } + rv.Set(reflect.ValueOf(*i).Convert(rvt)) + default: + return &document.UnmarshalTypeError{Value: "number", Type: rv.Type()} + } + } + + return nil +} + +func (d *Decoder) decodeJSONArray(tv []interface{}, rv reflect.Value) error { + var isArray bool + + switch rv.Kind() { + case reflect.Slice: + // Make room for the slice elements if needed + if rv.IsNil() || rv.Cap() < len(tv) { + rv.Set(reflect.MakeSlice(rv.Type(), 0, len(tv))) + } + case reflect.Array: + // Limited to capacity of existing array. + isArray = true + case reflect.Interface: + s := make([]interface{}, len(tv)) + for i, av := range tv { + if err := d.decode(av, reflect.ValueOf(&s[i]).Elem(), serde.Tag{}); err != nil { + return err + } + } + rv.Set(reflect.ValueOf(s)) + return nil + default: + return &document.UnmarshalTypeError{Value: "list", Type: rv.Type()} + } + + // If rv is not a slice, array + for i := 0; i < rv.Cap() && i < len(tv); i++ { + if !isArray { + rv.SetLen(i + 1) + } + if err := d.decode(tv[i], rv.Index(i), serde.Tag{}); err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) decodeJSONString(tv string, rv reflect.Value) error { + switch rv.Kind() { + case reflect.String: + rv.SetString(tv) + case reflect.Interface: + // Ensure type aliasing is handled properly + rv.Set(reflect.ValueOf(tv).Convert(rv.Type())) + default: + return &document.UnmarshalTypeError{Value: "string", Type: rv.Type()} + } + + return nil +} + +func (d *Decoder) decodeJSONObject(tv map[string]interface{}, rv reflect.Value) error { + switch rv.Kind() { + case reflect.Map: + t := rv.Type() + if t.Key().Kind() != reflect.String { + return &document.UnmarshalTypeError{Value: "map string key", Type: t.Key()} + } + if rv.IsNil() { + rv.Set(reflect.MakeMap(t)) + } + case reflect.Struct: + if rv.CanInterface() && document.IsNoSerde(rv.Interface()) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("unsupported type"), + Type: rv.Type(), + } + } + case reflect.Interface: + rv.Set(reflect.MakeMap(serde.ReflectTypeOf.MapStringToInterface)) + rv = rv.Elem() + default: + return &document.UnmarshalTypeError{Value: "map", Type: rv.Type()} + } + + if rv.Kind() == reflect.Map { + for k, kv := range tv { + key := reflect.New(rv.Type().Key()).Elem() + key.SetString(k) + elem := reflect.New(rv.Type().Elem()).Elem() + if err := d.decode(kv, elem, serde.Tag{}); err != nil { + return err + } + rv.SetMapIndex(key, elem) + } + } else if rv.Kind() == reflect.Struct { + fields := serde.GetStructFields(rv.Type()) + for k, kv := range tv { + if f, ok := fields.FieldByName(k); ok { + fv := serde.DecoderFieldByIndex(rv, f.Index) + if err := d.decode(kv, fv, f.Tag); err != nil { + return err + } + } + } + } + + return nil +} + +func (d *Decoder) unsupportedType(jv interface{}, rv reflect.Value) error { + if rv.Kind() == reflect.Interface && rv.NumMethod() != 0 { + return &document.UnmarshalTypeError{Value: "non-empty interface", Type: rv.Type()} + } + + if rv.Type().ConvertibleTo(serde.ReflectTypeOf.Time) { + return &document.UnmarshalTypeError{ + Type: rv.Type(), + Value: fmt.Sprintf("time value: %v", jv), + } + } + return nil +} diff --git a/vendor/github.com/aws/smithy-go/document/json/doc.go b/vendor/github.com/aws/smithy-go/document/json/doc.go new file mode 100644 index 00000000..cc5c04c3 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/json/doc.go @@ -0,0 +1,8 @@ +// Package json provides a document Encoder and Decoder implementation that is used to implement Smithy document types +// for JSON based protocols. The Encoder and Decoder implement the document.Marshaler and document.Unmarshaler +// interfaces respectively. +// +// This package handles protocol specific implementation details about documents, and can not be used to construct +// a document type for a service client. To construct a document type see each service clients respective document +// package and NewLazyDocument function. +package json diff --git a/vendor/github.com/aws/smithy-go/document/json/encoder.go b/vendor/github.com/aws/smithy-go/document/json/encoder.go new file mode 100644 index 00000000..f3ed69b1 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/json/encoder.go @@ -0,0 +1,329 @@ +package json + +import ( + "fmt" + "math/big" + "reflect" + + "github.com/aws/smithy-go/document" + "github.com/aws/smithy-go/document/internal/serde" + smithyjson "github.com/aws/smithy-go/encoding/json" +) + +// EncoderOptions is the set of options that can be configured for an Encoder. +type EncoderOptions struct{} + +// Encoder is a Smithy document decoder for JSON based protocols. +type Encoder struct { + options EncoderOptions +} + +// Encode returns the JSON encoding of v. +func (e *Encoder) Encode(v interface{}) ([]byte, error) { + encoder := smithyjson.NewEncoder() + + if err := e.encode(jsonValueProvider(encoder.Value), reflect.ValueOf(v), serde.Tag{}); err != nil { + return nil, err + } + + encodedBytes := encoder.Bytes() + + if len(encodedBytes) == 0 { + return nil, nil + } + + return encodedBytes, nil +} + +// valueProvider is an interface for retrieving a JSON Value type used for encoding. +type valueProvider interface { + GetValue() smithyjson.Value +} + +// jsonValueProvider is a valueProvider that returns the JSON value encoder as is. +type jsonValueProvider smithyjson.Value + +func (p jsonValueProvider) GetValue() smithyjson.Value { + return smithyjson.Value(p) +} + +// jsonObjectKeyProvider is a valueProvider that returns a JSON value type for encoding a value for the given JSON object +// key. +type jsonObjectKeyProvider struct { + Object *smithyjson.Object + Key string +} + +func (p jsonObjectKeyProvider) GetValue() smithyjson.Value { + return p.Object.Key(p.Key) +} + +// jsonArrayProvider is a valueProvider that returns a JSON value type for encoding a value in the given JSON array. +type jsonArrayProvider struct { + Array *smithyjson.Array +} + +func (p jsonArrayProvider) GetValue() smithyjson.Value { + return p.Array.Value() +} + +func (e *Encoder) encode(vp valueProvider, rv reflect.Value, tag serde.Tag) error { + // Zero values are serialized as null, or skipped if omitEmpty. + if serde.IsZeroValue(rv) { + if tag.OmitEmpty { + return nil + } + return e.encodeZeroValue(vp, rv) + } + + // Handle both pointers and interface conversion into types + rv = serde.ValueElem(rv) + + switch rv.Kind() { + case reflect.Invalid: + if tag.OmitEmpty { + return nil + } + vp.GetValue().Null() + return nil + + case reflect.Struct: + return e.encodeStruct(vp, rv) + + case reflect.Map: + return e.encodeMap(vp, rv) + + case reflect.Slice, reflect.Array: + return e.encodeSlice(vp, rv) + + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + // skip unsupported types + return nil + + default: + return e.encodeScalar(vp, rv) + } +} + +func (e *Encoder) encodeZeroValue(vp valueProvider, rv reflect.Value) error { + switch rv.Kind() { + case reflect.Invalid: + vp.GetValue().Null() + case reflect.Array: + vp.GetValue().Array().Close() + case reflect.Map, reflect.Slice: + vp.GetValue().Null() + case reflect.String: + vp.GetValue().String("") + case reflect.Bool: + vp.GetValue().Boolean(false) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + vp.GetValue().Long(0) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + vp.GetValue().ULong(0) + case reflect.Float32, reflect.Float64: + vp.GetValue().Double(0) + case reflect.Interface, reflect.Ptr: + vp.GetValue().Null() + default: + return &document.InvalidMarshalError{Message: fmt.Sprintf("unknown value type: %s", rv.String())} + } + + return nil +} + +func (e *Encoder) encodeStruct(vp valueProvider, rv reflect.Value) error { + if rv.CanInterface() && document.IsNoSerde(rv.Interface()) { + return &document.UnmarshalTypeError{ + Value: fmt.Sprintf("unsupported type"), + Type: rv.Type(), + } + } + + switch { + case rv.Type().ConvertibleTo(serde.ReflectTypeOf.Time): + return &document.InvalidMarshalError{ + Message: fmt.Sprintf("unsupported type %s", rv.Type().String()), + } + case rv.Type().ConvertibleTo(serde.ReflectTypeOf.BigFloat): + fallthrough + case rv.Type().ConvertibleTo(serde.ReflectTypeOf.BigInt): + return e.encodeNumber(vp, rv) + } + + object := vp.GetValue().Object() + defer object.Close() + + fields := serde.GetStructFields(rv.Type()) + for _, f := range fields.All() { + if f.Name == "" { + return &document.InvalidMarshalError{Message: "map key cannot be empty"} + } + + fv, found := serde.EncoderFieldByIndex(rv, f.Index) + if !found { + continue + } + + err := e.encode(jsonObjectKeyProvider{ + Object: object, + Key: f.Name, + }, fv, f.Tag) + if err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) encodeMap(vp valueProvider, rv reflect.Value) error { + object := vp.GetValue().Object() + defer object.Close() + + for _, key := range rv.MapKeys() { + keyName := fmt.Sprint(key.Interface()) + if keyName == "" { + return &document.InvalidMarshalError{Message: "map key cannot be empty"} + } + + ev := rv.MapIndex(key) + err := e.encode(jsonObjectKeyProvider{ + Object: object, + Key: keyName, + }, ev, serde.Tag{}) + if err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) encodeSlice(value valueProvider, rv reflect.Value) error { + array := value.GetValue().Array() + defer array.Close() + + for i := 0; i < rv.Len(); i++ { + err := e.encode(jsonArrayProvider{Array: array}, rv.Index(i), serde.Tag{}) + if err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) encodeScalar(vp valueProvider, rv reflect.Value) error { + if rv.Type() == serde.ReflectTypeOf.DocumentNumber { + number := rv.Interface().(document.Number) + if !isValidJSONNumber(number.String()) { + return &document.InvalidMarshalError{Message: fmt.Sprintf("invalid number literal: %s", number)} + } + vp.GetValue().Write([]byte(number)) + } + + switch rv.Kind() { + case reflect.Bool: + vp.GetValue().Boolean(rv.Bool()) + case reflect.String: + vp.GetValue().String(rv.String()) + default: + // Fallback to encoding numbers, will return invalid type if not supported + err := e.encodeNumber(vp, rv) + if err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) encodeNumber(vp valueProvider, rv reflect.Value) error { + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + vp.GetValue().Long(rv.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + vp.GetValue().ULong(rv.Uint()) + case reflect.Float32: + vp.GetValue().Float(float32(rv.Float())) + case reflect.Float64: + vp.GetValue().Double(rv.Float()) + default: + rvt := rv.Type() + switch { + case rvt.ConvertibleTo(serde.ReflectTypeOf.BigInt): + bi := rv.Convert(serde.ReflectTypeOf.BigInt).Interface().(big.Int) + vp.GetValue().BigInteger(&bi) + case rvt.ConvertibleTo(serde.ReflectTypeOf.BigFloat): + bf := rv.Convert(serde.ReflectTypeOf.BigFloat).Interface().(big.Float) + vp.GetValue().BigDecimal(&bf) + default: + return &document.InvalidMarshalError{Message: fmt.Sprintf("incompatible type: %s", rvt.String())} + } + } + + return nil +} + +// isValidJSONNumber reports whether s is a valid JSON number literal. +// From https://golang.org/src/encoding/json/encode.go#L652 isValidNumber +// Copyright 2010 The Go Authors. +func isValidJSONNumber(s string) bool { + // This function implements the JSON numbers grammar. + // See https://tools.ietf.org/html/rfc7159#section-6 + // and https://www.json.org/img/number.png + + if s == "" { + return false + } + + // Optional - + if s[0] == '-' { + s = s[1:] + if s == "" { + return false + } + } + + // Digits + switch { + default: + return false + + case s[0] == '0': + s = s[1:] + + case '1' <= s[0] && s[0] <= '9': + s = s[1:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + } + } + + // . followed by 1 or more digits. + if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { + s = s[2:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + } + } + + // e or E followed by an optional - or + and + // 1 or more digits. + if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { + s = s[1:] + if s[0] == '+' || s[0] == '-' { + s = s[1:] + if s == "" { + return false + } + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + } + } + + // Make sure we are at the end. + return s == "" +} \ No newline at end of file diff --git a/vendor/github.com/aws/smithy-go/document/json/json.go b/vendor/github.com/aws/smithy-go/document/json/json.go new file mode 100644 index 00000000..ec4d2926 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/document/json/json.go @@ -0,0 +1,27 @@ +package json + +// NewEncoder returns an Encoder for serializing Smithy documents for JSON based protocols. +func NewEncoder(optFns ...func(options *EncoderOptions)) *Encoder { + o := EncoderOptions{} + + for _, fn := range optFns { + fn(&o) + } + + return &Encoder{ + options: o, + } +} + +// NewDecoder returns a Decoder for deserializing Smithy documents for JSON based protocols. +func NewDecoder(optFns ...func(*DecoderOptions)) *Decoder { + o := DecoderOptions{} + + for _, fn := range optFns { + fn(&o) + } + + return &Decoder{ + options: o, + } +} diff --git a/vendor/github.com/permitio/permit-golang/LICENSE b/vendor/github.com/permitio/permit-golang/LICENSE new file mode 100644 index 00000000..b2de8792 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 PermitClient.io + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/api.go b/vendor/github.com/permitio/permit-golang/pkg/api/api.go new file mode 100644 index 00000000..a7f18538 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/api.go @@ -0,0 +1,214 @@ +package api + +import ( + "context" + "fmt" + "time" + + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type permitBaseApi struct { + client *openapi.APIClient + config *config.PermitConfig + logger *zap.Logger +} + +type PermitBaseFactsApi struct { + permitBaseApi +} + +// WaitForSyncOptions contains options for configuring facts synchronization behavior +type WaitForSyncOptions struct { + // Policy specifies what to do when timeout is reached ("ignore" or "fail") + // When "ignore" is specified, the request will continue processing even if facts sync times out. + // When "fail" is specified, the request will fail with an error if facts sync times out. + Policy config.FactsSyncTimeoutPolicy +} + +type IPermitBaseFactsApi interface { + lazyLoadPermitContext(ctx context.Context, methodApiLevelArg ...config.APIKeyLevel) error + WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *PermitBaseFactsApi +} + +type IPermitBaseApi interface { + lazyLoadPermitContext(ctx context.Context, methodApiLevelArg ...config.APIKeyLevel) error +} + +// WaitForSync configures the client to wait for facts synchronization. +// +// Parameters: +// - timeout: Required duration to wait for synchronization +// - options: Additional configuration options for facts synchronization +func (a *PermitBaseFactsApi) WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *PermitBaseFactsApi { + if a.config.GetProxyFactsViaPDP() { + stringTimeout := "" + if timeout == nil { + if timeoutFromConfig := a.config.GetFactsSyncTimeout(); timeoutFromConfig != nil { + stringTimeout = fmt.Sprintf("%d", int64(timeoutFromConfig.Seconds())) + } + } else { + stringTimeout = fmt.Sprintf("%d", int64(timeout.Seconds())) + } + + clientConfig := a.client.GetConfig() + clientConfig.DefaultHeader["X-Wait-Timeout"] = stringTimeout + + // Add the timeout policy header if a policy is provided or set in the config + if options.Policy != "" { + clientConfig.DefaultHeader["X-Timeout-Policy"] = string(options.Policy) + } else if a.config.GetFactsSyncTimeoutPolicy() != "" { + clientConfig.DefaultHeader["X-Timeout-Policy"] = string(a.config.GetFactsSyncTimeoutPolicy()) + } + + return NewPermitBaseFactsApi(openapi.NewAPIClient(clientConfig), a.config) + } else { + a.logger.Warn("Attempted to wait for sync, but 'proxyFactsViaPdp' is not enabled. Ignoring") + return a + } +} + +func (a *permitBaseApi) lazyLoadPermitContext(ctx context.Context, methodApiLevelArg ...config.APIKeyLevel) error { + var methodApiLevel config.APIKeyLevel + permitContext := a.config.Context.GetContext() + + if permitContext == nil { + // To ensure it's a regular client and not factsClient + baseClientConfig := NewClientConfig(a.config) + client := openapi.NewAPIClient(baseClientConfig) + newPermitContext, err := config.PermitContextFactory(ctx, client, "", "", false) + if err != nil { + return err + } + a.config.Context = newPermitContext + } + + if len(methodApiLevelArg) == 0 { + methodApiLevel = config.EnvironmentAPIKeyLevel + } else { + methodApiLevel = methodApiLevelArg[0] + } + if methodApiLevel == config.ProjectAPIKeyLevel && a.config.GetContext().GetEnvironment() == "" { + return errors.NewPermitContextError("You're trying to use an SDK method that's specific to a project," + + "but you haven't set the current project in your client's context yet," + + "or you are using an organization level API key." + + "Please set the context to a specific" + + "project using `PermitClient.SetPermitContext()` method.") + } + if methodApiLevel == config.EnvironmentAPIKeyLevel && a.config.GetContext().GetProject() == "" && a.config.GetContext().GetEnvironment() == "" { + return errors.NewPermitContextError("You're trying to use an SDK method that's specific to an environment," + + "but you haven't set the current environment in your client's context yet," + + "or you are using an organization/project level API key." + + "Please set the context to a specific" + + "environment using `PermitClient.SetPermitContext()` method.") + } + return nil +} + +type PermitApiClient struct { + config *config.PermitConfig + logger *zap.Logger + client *openapi.APIClient + ConditionSets *ConditionSets + Elements *Elements + Environments *Environments + ImplicitGrants *ImplicitGrants + Projects *Projects + ProxyConfigs *ProxyConfigs + RelationshipTuples *RelationshipTuples + ResourceActionGroups *ResourceActionGroups + ResourceActions *ResourceActions + ResourceAttributes *ResourceAttributes + ResourceInstances *ResourceInstances + ResourceRelations *ResourceRelations + ResourceRoles *ResourceRoles + Resources *Resources + RoleAssignments *RoleAssignments + Roles *Roles + Tenants *Tenants + Users *Users +} + +func (p *PermitApiClient) SetContext(ctx context.Context, project string, environment string) { + permitContext, err := config.PermitContextFactory(ctx, p.client, project, environment, true) + if err != nil { + p.logger.Error("", zap.Error(err)) + } + p.config.Context = permitContext +} + +func NewClientConfig(config *config.PermitConfig) *openapi.Configuration { + clientConfig := openapi.NewConfiguration() + clientConfig.Host = getHostFromUrl(config.GetApiUrl()) + clientConfig.Scheme = getSchemaFromUrl(config.GetApiUrl()) + clientConfig.AddDefaultHeader("Authorization", "Bearer "+config.GetToken()) + clientConfig.HTTPClient = config.GetHTTPClient() + return clientConfig +} + +func NewFactsClientConfig(config *config.PermitConfig) *openapi.Configuration { + clientConfig := openapi.NewConfiguration() + + // Only add timeout-related headers if proxyFactsViaPDP is enabled + if config.GetProxyFactsViaPDP() { + // Add X-Wait-Timeout header only if factsSyncTimeout is set + if timeoutFromConfig := config.GetFactsSyncTimeout(); timeoutFromConfig != nil { + stringTimeout := fmt.Sprintf("%d", int64(timeoutFromConfig.Seconds())) + clientConfig.DefaultHeader["X-Wait-Timeout"] = stringTimeout + } + + // Add X-Timeout-Policy header only if factsSyncTimeoutPolicy is set + if policy := config.GetFactsSyncTimeoutPolicy(); policy != "" { + clientConfig.DefaultHeader["X-Timeout-Policy"] = string(policy) + } + } + + clientConfig.AddDefaultHeader("Authorization", "Bearer "+config.GetToken()) + clientConfig.Host = getHostFromUrl(config.GetPdpUrl()) + clientConfig.Scheme = getSchemaFromUrl(config.GetPdpUrl()) + clientConfig.HTTPClient = config.GetHTTPClient() + return clientConfig +} + +func NewPermitApiClient(config *config.PermitConfig) *PermitApiClient { + baseClientConfig := NewClientConfig(config) + factsClientConfig := NewFactsClientConfig(config) + client := openapi.NewAPIClient(baseClientConfig) + factsClient := openapi.NewAPIClient(factsClientConfig) + return &PermitApiClient{ + config: config, + logger: config.Logger, + client: client, + ConditionSets: NewConditionSetsApi(client, config), + Elements: NewElementsApi(client, config), + Environments: NewEnvironmentsApi(client, config), + ImplicitGrants: NewImplicitGrantsApi(client, config), + Projects: NewProjectsApi(client, config), + ProxyConfigs: NewProxyConfigsApi(client, config), + RelationshipTuples: NewRelationshipTuplesApi(factsClient, config), + ResourceActionGroups: NewResourceActionGroupsApi(client, config), + ResourceActions: NewResourceActionsApi(client, config), + ResourceAttributes: NewResourceAttributesApi(client, config), + ResourceInstances: NewResourceInstancesApi(factsClient, config), + ResourceRelations: NewResourceRelationsApi(client, config), + ResourceRoles: NewResourceRolesApi(client, config), + Resources: NewResourcesApi(client, config), + RoleAssignments: NewRoleAssignmentsApi(factsClient, config), + Roles: NewRolesApi(client, config), + Tenants: NewTenantsApi(factsClient, config), + Users: NewUsersApi(factsClient, config), + } +} + +func NewPermitBaseFactsApi(client *openapi.APIClient, config *config.PermitConfig) *PermitBaseFactsApi { + return &PermitBaseFactsApi{ + permitBaseApi: permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/condition_sets.go b/vendor/github.com/permitio/permit-golang/pkg/api/condition_sets.go new file mode 100644 index 00000000..990f945e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/condition_sets.go @@ -0,0 +1,257 @@ +package api + +import ( + "context" + "fmt" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ConditionSets struct { + permitBaseApi +} + +func NewConditionSetsApi(client *openapi.APIClient, config *config.PermitConfig) *ConditionSets { + return &ConditionSets{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all condition sets in the current environment. +// Usage Example: +// `condition_sets, err := PermitClient.Api.ConditionSets.List(ctx,1, 10)` +func (c *ConditionSets) List(ctx context.Context, page int, perPage int) ([]models.ConditionSetRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + c.logger.Error("error listing condition sets - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return nil, err + } + + conditionSets, httpRes, err := c.client.ConditionSetsApi.ListConditionSets( + ctx, + c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + ).Page(int32(page)).PerPage(int32(perPage)).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + c.logger.Error("error listing condition sets", zap.Error(err)) + return nil, err + } + + return conditionSets.PaginatedResultConditionSetRead.GetData(), nil +} + +// Get a condition set by key. +// Usage Example: +// `conditionSet, err := PermitClient.Api.ConditionSets.Get(ctx, "cs-key")` +func (c *ConditionSets) Get(ctx context.Context, conditionSetKey string) (*models.ConditionSetRead, error) { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return nil, err + } + + conditionSet, httpRes, err := c.client.ConditionSetsApi.GetConditionSet( + ctx, + c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), conditionSetKey, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + c.logger.Error("error getting condition set: "+conditionSetKey, zap.Error(err)) + return nil, err + } + + return conditionSet, nil +} + +// GetByKey gets a condition set by key from your context's environment. +// Usage Example: +// +// `cs, err := PermitClient.Api.ConditionSets.GetByKey(ctx, "cs-key")` +func (c *ConditionSets) GetByKey(ctx context.Context, conditionSetKey string) (*models.ConditionSetRead, error) { + return c.Get(ctx, conditionSetKey) +} + +// GetById gets a condition set by id from your context's environment. +// Usage Example: +// +// `cs, err := PermitClient.Api.ConditionSets.GetById(ctx, uuid.New())` +func (c *ConditionSets) GetById(ctx context.Context, conditionSetId uuid.UUID) (*models.ConditionSetRead, error) { + return c.Get(ctx, conditionSetId.String()) +} + +// Create a new condition set. +// Usage Example: +// ``` +// csCreate := models.NewConditionSetCreate("cs-key", "cs-name") +// cs, err := PermitClient.Api.ConditionSets.Create(ctx, csCreate) +// ``` +func (c *ConditionSets) Create(ctx context.Context, csCreate models.ConditionSetCreate) (*models.ConditionSetRead, error) { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return nil, err + } + + conditionSet, httpRes, err := c.client.ConditionSetsApi.CreateConditionSet( + ctx, c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + ).ConditionSetCreate(csCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + c.logger.Error("error creating condition set: "+csCreate.GetKey(), zap.Error(err)) + return nil, err + } + + return conditionSet, nil +} + +// Update a condition set. +func (c *ConditionSets) Update(ctx context.Context, conditionSetKey string, conditionSetUpdate models.ConditionSetUpdate) (*models.ConditionSetRead, error) { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return nil, err + } + + conditionSet, httpRes, err := c.client.ConditionSetsApi.UpdateConditionSet( + ctx, c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + conditionSetKey, + ).ConditionSetUpdate(conditionSetUpdate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + c.logger.Error("error updating condition set: "+conditionSetKey, zap.Error(err)) + return nil, err + } + return conditionSet, nil +} + +// Delete a condition set. +func (c *ConditionSets) Delete(ctx context.Context, conditionSetKey string) error { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := c.client.ConditionSetsApi.DeleteConditionSet( + ctx, + c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + conditionSetKey, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + c.logger.Error("error deleting condition set: "+conditionSetKey, zap.Error(err)) + return err + } + + return nil +} + +func (c *ConditionSets) AssignSetPermissions(ctx context.Context, userSetKey string, permission string, resourceSetKey string) ([]models.ConditionSetRuleRead, error) { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return nil, err + } + + rule, httpRes, err := c.client.ConditionSetRulesApi.AssignSetPermissions( + ctx, + c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + ).ConditionSetRuleCreate(*models.NewConditionSetRuleCreate(userSetKey, permission, resourceSetKey)).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + errString := fmt.Sprintf("error creating condition set rule %s, %s, %s", userSetKey, permission, resourceSetKey) + c.logger.Error("error creating condition set rule: "+errString, zap.Error(err)) + return nil, err + } + + return rule, nil +} + +func (c *ConditionSets) UnassignSetPermissions(ctx context.Context, userSetKey string, permission string, resourceSetKey string) error { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := c.client.ConditionSetRulesApi.UnassignSetPermissions( + ctx, + c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + ).ConditionSetRuleRemove(*models.NewConditionSetRuleRemove(userSetKey, permission, resourceSetKey)).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + errString := fmt.Sprintf("error creating condition set rule %s, %s, %s", userSetKey, permission, resourceSetKey) + c.logger.Error(errString, zap.Error(err)) + return err + } + + return nil +} + +func (c *ConditionSets) ListSetPermissions(ctx context.Context, userSetKey string, permission string, resourceSetKey string) ([]models.ConditionSetRuleRead, error) { + err := c.lazyLoadPermitContext(ctx) + + if err != nil { + c.logger.Error("", zap.Error(err)) + return nil, err + } + + rules, httpRes, err := c.client.ConditionSetRulesApi.ListSetPermissions( + ctx, + c.config.Context.GetProject(), + c.config.Context.GetEnvironment(), + ).UserSet(userSetKey).Permission(permission).ResourceSet(resourceSetKey).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + errString := fmt.Sprintf("error listing rules condition set rule %s, %s, %s", userSetKey, permission, resourceSetKey) + c.logger.Error(errString, zap.Error(err)) + return nil, err + } + + return rules, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/elements.go b/vendor/github.com/permitio/permit-golang/pkg/api/elements.go new file mode 100644 index 00000000..cc5c6557 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/elements.go @@ -0,0 +1,45 @@ +package api + +import ( + "context" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type Elements struct { + permitBaseApi +} + +func NewElementsApi(client *openapi.APIClient, config *config.PermitConfig) *Elements { + return &Elements{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// LoginAs login as a given user. +// Usage Example: +// ``` +// userLogin := models.NewUserLoginRequestInput("user-id", "tenant-id") +// embeddedLoginRequestOutput, err := PermitClient.Api.Elements.LoginAs(ctx, userLogin) +// ``` +func (e *Elements) LoginAs(ctx context.Context, userLogin models.UserLoginRequestInput) (*models.EmbeddedLoginRequestOutput, error) { + err := e.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + embeddedLoginRequestOutput, httpRes, err := e.client.AuthenticationApi.ElementsLoginAs(ctx).UserLoginRequestInput(userLogin).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + e.logger.Error("error login as: "+userLogin.GetUserId()+"in tenant: "+userLogin.GetTenantId(), zap.Error(err)) + return nil, err + } + return embeddedLoginRequestOutput, nil + +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/environments.go b/vendor/github.com/permitio/permit-golang/pkg/api/environments.go new file mode 100644 index 00000000..ace8108c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/environments.go @@ -0,0 +1,152 @@ +package api + +import ( + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" + "golang.org/x/net/context" +) + +type Environments struct { + permitBaseApi +} + +func NewEnvironmentsApi(client *openapi.APIClient, config *config.PermitConfig) *Environments { + return &Environments{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List the environments in the project of your context +// Usage Example: +// +// `environments, err := PermitClient.Api.Environments.List(ctx, 1, 10)` +func (e *Environments) List(ctx context.Context, page int, perPage int) ([]models.EnvironmentRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + e.logger.Error("error listing environments - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := e.lazyLoadPermitContext(ctx) + if err != nil { + e.logger.Error("", zap.Error(err)) + return nil, err + } + environments, httpRes, err := e.client.EnvironmentsApi.ListEnvironments(ctx, e.config.Context.ProjectId).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + e.logger.Error("error listing environments", zap.Error(err)) + return nil, err + } + return environments, nil +} + +// Get an environment by key. +// Usage Example: +// +// `environment, err := PermitClient.Api.Environments.Get(ctx, "production")` +func (e *Environments) Get(ctx context.Context, environmentKey string) (*models.EnvironmentRead, error) { + err := e.lazyLoadPermitContext(ctx) + if err != nil { + e.logger.Error("", zap.Error(err)) + return nil, err + } + environment, httpRes, err := e.client.EnvironmentsApi.GetEnvironment(ctx, e.config.Context.ProjectId, environmentKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + e.logger.Error("error getting environment: "+environmentKey, zap.Error(err)) + return nil, err + } + + return environment, nil +} + +// GetByKey get an environment by key. +// Usage Example: +// +// `environment, err := PermitClient.Api.Environments.GetByKey(ctx, "production")` +func (e *Environments) GetByKey(ctx context.Context, environmentKey string) (*models.EnvironmentRead, error) { + return e.Get(ctx, environmentKey) +} + +// GetById get an environment by id. +// Usage Example: +// +// `environment, err := PermitClient.Api.Environments.GetById(ctx, uuid.New())` +func (e *Environments) GetById(ctx context.Context, environmentId uuid.UUID) (*models.EnvironmentRead, error) { + return e.Get(ctx, environmentId.String()) +} + +// Create an environment in the project of your context. +// Usage Example: +// +// ``` +// environmentCreate := models.NewEnvironmentCreate("production", "Production") +// environment, err := PermitClient.Api.Environments.Create(ctx, *environmentCreate) +// ``` +func (e *Environments) Create(ctx context.Context, environmentCreate models.EnvironmentCreate) (*models.EnvironmentRead, error) { + err := e.lazyLoadPermitContext(ctx) + if err != nil { + e.logger.Error("", zap.Error(err)) + return nil, err + } + environment, httpRes, err := e.client.EnvironmentsApi.CreateEnvironment(ctx, e.config.Context.ProjectId).EnvironmentCreate(environmentCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + e.logger.Error("error creating environment: "+environmentCreate.GetKey(), zap.Error(err)) + return nil, err + } + + return environment, nil +} + +// Update an environment in the project of your context. +// Usage Example: +// ``` +// environmentUpdate := models.NewEnvironmentUpdate() +// environmentUpdate.SetName("Production") +// environment, err := PermitClient.Api.Environments.Update(ctx, "production", *environmentUpdate) +// ``` + +func (e *Environments) Update(ctx context.Context, environmentKey string, environmentUpdate models.EnvironmentUpdate) (*models.EnvironmentRead, error) { + err := e.lazyLoadPermitContext(ctx) + if err != nil { + e.logger.Error("", zap.Error(err)) + return nil, err + } + environment, httpRes, err := e.client.EnvironmentsApi.UpdateEnvironment(ctx, e.config.Context.ProjectId, environmentKey).EnvironmentUpdate(environmentUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + e.logger.Error("error updating environment: "+environmentKey, zap.Error(err)) + return nil, err + } + + return environment, nil +} + +// Delete an environment in the project of your context. +// Usage Example: +// +// `err := PermitClient.Api.Environments.Delete(ctx, "production")` +func (e *Environments) Delete(ctx context.Context, environmentKey string) error { + err := e.lazyLoadPermitContext(ctx) + if err != nil { + e.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := e.client.EnvironmentsApi.DeleteEnvironment(ctx, e.config.Context.ProjectId, environmentKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + e.logger.Error("error deleting environment: "+environmentKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/implicitGrants.go b/vendor/github.com/permitio/permit-golang/pkg/api/implicitGrants.go new file mode 100644 index 00000000..6552c703 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/implicitGrants.go @@ -0,0 +1,114 @@ +package api + +import ( + "context" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ImplicitGrants struct { + permitBaseApi +} + +func NewImplicitGrantsApi(client *openapi.APIClient, config *config.PermitConfig) *ImplicitGrants { + return &ImplicitGrants{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +func (r *ImplicitGrants) Create( + ctx context.Context, + resourceId string, + roleId string, + derivedRuleCreate models.DerivedRoleRuleCreate, +) (*models.DerivedRoleRuleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + derivedRoleRead, httpRes, err := r.client.ImplicitGrantsApi.CreateImplicitGrant(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).DerivedRoleRuleCreate(derivedRuleCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating derived role", zap.Error(err)) + return nil, err + } + + return derivedRoleRead, nil +} + +func (r *ImplicitGrants) Delete( + ctx context.Context, + roleId string, + resourceId string, + derivedRoleRuleDelete models.DerivedRoleRuleDelete, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := r.client.ImplicitGrantsApi.DeleteImplicitGrant(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).DerivedRoleRuleDelete(derivedRoleRuleDelete).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting derived role", zap.Error(err)) + return err + } + + return nil +} + +func (r *ImplicitGrants) UpdateConditions( + ctx context.Context, + resourceId string, + roleId string, + roleDerivationSettings models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, +) (*models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updatedSettings, httpRes, err := r.client.ImplicitGrantsApi.UpdateImplicitGrantsConditions(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings(roleDerivationSettings).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error updating derived role", zap.Error(err)) + return nil, err + } + + return updatedSettings, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/projects.go b/vendor/github.com/permitio/permit-golang/pkg/api/projects.go new file mode 100644 index 00000000..0ce52e06 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/projects.go @@ -0,0 +1,143 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type Projects struct { + permitBaseApi +} + +func NewProjectsApi(client *openapi.APIClient, config *config.PermitConfig) *Projects { + return &Projects{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all projects in the organization, requires Project level API key, or higher. +// Usage Example: +// `projects, err := PermitClient.Api.Projects.List(ctx, 1, 10)` +func (p *Projects) List(ctx context.Context, page int, perPage int) ([]models.ProjectRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + p.logger.Error("error listing projects - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := p.lazyLoadPermitContext(ctx, config.OrganizationAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + projects, httpRes, err := p.client.ProjectsApi.ListProjects(ctx).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error listing projects", zap.Error(err)) + return nil, err + } + + return projects, nil +} + +// Get a project by key, requires Project level API key, or higher. +// Usage Example: +// `project, err := PermitClient.Api.Projects.Get(ctx, "project-key")` +func (p *Projects) Get(ctx context.Context, projectKey string) (*models.ProjectRead, error) { + err := p.lazyLoadPermitContext(ctx, config.OrganizationAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + project, httpRes, err := p.client.ProjectsApi.GetProject(ctx, projectKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error getting project: "+projectKey, zap.Error(err)) + return nil, err + } + return project, nil +} + +// GetByKey get a project by key, requires Project level API key, or higher. +// Usage Example: +// `project, err := PermitClient.Api.Projects.GetByKey(ctx, "project-key")` +func (p *Projects) GetByKey(ctx context.Context, projectKey string) (*models.ProjectRead, error) { + return p.Get(ctx, projectKey) +} + +// GetById get a project by id, requires Project level API key, or higher. +// Usage Example: +// `project, err := PermitClient.Api.Projects.GetById(ctx, uuid.New())` +func (p *Projects) GetById(ctx context.Context, projectId uuid.UUID) (*models.ProjectRead, error) { + return p.Get(ctx, projectId.String()) +} + +// Create a new project, requires Project level API key, or higher. +// Usage Example: +// ``` +// projectCreate := models.NewProjectCreate("project-key", "project-name") +// project, err := PermitClient.Api.Projects.Create(ctx, projectCreate) +// ``` +func (p *Projects) Create(ctx context.Context, projectCreate models.ProjectCreate) (*models.ProjectRead, error) { + err := p.lazyLoadPermitContext(ctx, config.OrganizationAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + project, httpRes, err := p.client.ProjectsApi.CreateProject(ctx).ProjectCreate(projectCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error creating project: "+projectCreate.GetKey(), zap.Error(err)) + return nil, err + } + return project, nil +} + +// Update a project, requires Project level API key, or higher. +// Usage Example: +// ``` +// projectUpdate := models.NewProjectUpdate() +// projectUpdate.SetName("new-project-name") +// project, err := PermitClient.Api.Projects.Update(ctx, "project-key", projectUpdate) +// ``` +func (p *Projects) Update(ctx context.Context, projectKey string, projectUpdate models.ProjectUpdate) (*models.ProjectRead, error) { + err := p.lazyLoadPermitContext(ctx, config.OrganizationAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + project, httpRes, err := p.client.ProjectsApi.UpdateProject(ctx, projectKey).ProjectUpdate(projectUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error updating project: "+projectKey, zap.Error(err)) + return nil, err + } + return project, nil +} + +// Delete a project, requires Project level API key, or higher. +// Usage Example: +// `err := PermitClient.Api.Projects.Delete(ctx, "project-key")` +func (p *Projects) Delete(ctx context.Context, projectKey string) error { + err := p.lazyLoadPermitContext(ctx, config.OrganizationAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := p.client.ProjectsApi.DeleteProject(ctx, projectKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error deleting project: "+projectKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/proxyConfig.go b/vendor/github.com/permitio/permit-golang/pkg/api/proxyConfig.go new file mode 100644 index 00000000..3ca78867 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/proxyConfig.go @@ -0,0 +1,143 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ProxyConfigs struct { + permitBaseApi +} + +func NewProxyConfigsApi(client *openapi.APIClient, config *config.PermitConfig) *ProxyConfigs { + return &ProxyConfigs{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all ProxyConfigs in the organization, requires Environment level API key, or higher. +// Usage Example: +// `ProxyConfigs, err := PermitClient.Api.ProxyConfigs.List(ctx, 1, 10)` +func (p *ProxyConfigs) List(ctx context.Context, page int, perPage int) ([]models.ProxyConfigRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + p.logger.Error("error listing ProxyConfigs - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := p.lazyLoadPermitContext(ctx, config.EnvironmentAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + ProxyConfigs, httpRes, err := p.client.ProxyConfigAPI.ListProxyConfigs(ctx, p.config.Context.GetProject(), p.config.Context.GetEnvironment()).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error listing ProxyConfigs", zap.Error(err)) + return nil, err + } + + return ProxyConfigs, nil +} + +// Get a Proxy Config by key, requires Environment level API key, or higher. +// Usage Example: +// `proxyConfig, err := PermitClient.Api.ProxyConfigs.Get(ctx, "proxyconfig-key")` +func (p *ProxyConfigs) Get(ctx context.Context, proxyConfigKey string) (*models.ProxyConfigRead, error) { + err := p.lazyLoadPermitContext(ctx, config.EnvironmentAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + proxyConfig, httpRes, err := p.client.ProxyConfigAPI.GetProxyConfig(ctx, p.config.Context.GetProject(), p.config.Context.GetEnvironment(), proxyConfigKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error getting Proxy Config: "+proxyConfigKey, zap.Error(err)) + return nil, err + } + return proxyConfig, nil +} + +// GetByKey get a project by key, requires Environment level API key, or higher. +// Usage Example: +// `proxyConfig, err := PermitClient.Api.ProxyConfigs.GetByKey(ctx, "proxyconfig-key")` +func (p *ProxyConfigs) GetByKey(ctx context.Context, ProxyConfigKey string) (*models.ProxyConfigRead, error) { + return p.Get(ctx, ProxyConfigKey) +} + +// GetById get a proxy config by id, requires Environment level API key, or higher. +// Usage Example: +// `proxyConfig, err := PermitClient.Api.ProxyConfigs.GetById(ctx, uuid.New())` +func (p *ProxyConfigs) GetById(ctx context.Context, ProxyConfigId uuid.UUID) (*models.ProxyConfigRead, error) { + return p.Get(ctx, ProxyConfigId.String()) +} + +// Create a new proxy config, requires Environment level API key, or higher. +// Usage Example: +// ``` +// proxyConfigCreate := models.NewProxyConfigCreate("user:pass", "proxyConfigKey", "proxyConfigName") +// proxyConfig, err := PermitClient.Api.ProxyConfigs.Create(ctx, proxyConfigCreate) +// ``` +func (p *ProxyConfigs) Create(ctx context.Context, proxyConfigCreate models.ProxyConfigCreate) (*models.ProxyConfigRead, error) { + err := p.lazyLoadPermitContext(ctx, config.EnvironmentAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + proxyConfig, httpRes, err := p.client.ProxyConfigAPI.CreateProxyConfig(ctx, p.config.Context.GetProject(), p.config.Context.GetEnvironment()).ProxyConfigCreate(proxyConfigCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error creating proxy config: "+proxyConfigCreate.GetKey(), zap.Error(err)) + return nil, err + } + return proxyConfig, nil +} + +// Update a proxy config, requires Environment level API key, or higher. +// Usage Example: +// ``` +// proxyConfigUpdate := models.NewProxyConfigUpdate() +// proxyConfigUpdate.SetName("new-proxy-config-name") +// proxyConfig, err := PermitClient.Api.ProxyConfigs.Update(ctx, "proxy-config-key", proxyConfigUpdate) +// ``` +func (p *ProxyConfigs) Update(ctx context.Context, proxyConfigKey string, proxyConfigUpdate models.ProxyConfigUpdate) (*models.ProxyConfigRead, error) { + err := p.lazyLoadPermitContext(ctx, config.EnvironmentAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return nil, err + } + proxyConfig, httpRes, err := p.client.ProxyConfigAPI.UpdateProxyConfig(ctx, p.config.Context.GetProject(), p.config.Context.GetEnvironment(), proxyConfigKey).ProxyConfigUpdate(proxyConfigUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error updating proxy config: "+proxyConfigKey, zap.Error(err)) + return nil, err + } + return proxyConfig, nil +} + +// Delete a proxy config, requires Environment level API key, or higher. +// Usage Example: +// `err := PermitClient.Api.ProxyConfigs.Delete(ctx, "proxy-config-key")` +func (p *ProxyConfigs) Delete(ctx context.Context, proxyConfigKey string) error { + err := p.lazyLoadPermitContext(ctx, config.EnvironmentAPIKeyLevel) + if err != nil { + p.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := p.client.ProxyConfigAPI.DeleteProxyConfig(ctx, p.config.Context.GetProject(), p.config.Context.GetEnvironment(), proxyConfigKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + p.logger.Error("error deleting proxy config: "+proxyConfigKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/relationshipTuples.go b/vendor/github.com/permitio/permit-golang/pkg/api/relationshipTuples.go new file mode 100644 index 00000000..aa7953c2 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/relationshipTuples.go @@ -0,0 +1,226 @@ +package api + +import ( + "context" + "time" + + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type RelationshipTuples struct { + PermitBaseFactsApi +} + +func NewRelationshipTuplesApi(client *openapi.APIClient, config *config.PermitConfig) *RelationshipTuples { + return &RelationshipTuples{ + PermitBaseFactsApi{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + }, + } +} + +// WaitForSync configures the client to wait for facts synchronization. +// +// Parameters: +// - timeout: Optional duration to wait for synchronization. +// - options: Additional configuration options for facts synchronization +func (u *RelationshipTuples) WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *RelationshipTuples { + return NewRelationshipTuplesApi(u.PermitBaseFactsApi.WaitForSync(timeout, options).client, u.config) +} + +func (r *RelationshipTuples) Create( + ctx context.Context, + relationshipTupleCreate models.RelationshipTupleCreate, +) (*models.RelationshipTupleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + relTuple, httpRes, err := r.client.RelationshipTuplesApi.CreateRelationshipTuple(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).RelationshipTupleCreate(relationshipTupleCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating relationship tuple", zap.Error(err)) + return nil, err + } + + return relTuple, nil +} + +func (r *RelationshipTuples) Delete( + ctx context.Context, + relationshipTupleDelete models.RelationshipTupleDelete, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := r.client.RelationshipTuplesApi.DeleteRelationshipTuple(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).RelationshipTupleDelete(relationshipTupleDelete).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting relationship tuple", zap.Error(err)) + return err + } + + return nil +} + +func (r *RelationshipTuples) List( + ctx context.Context, + page int, + perPage int, + tenantFilter string, + subjectFilter string, + relationFilter string, + objectFilter string, +) (*[]models.RelationshipTupleRead, error) { + return r.list(ctx, page, perPage, tenantFilter, subjectFilter, relationFilter, objectFilter, false) +} + +func (r *RelationshipTuples) ListDetailed( + ctx context.Context, + page int, + perPage int, + tenantFilter string, + subjectFilter string, + relationFilter string, + objectFilter string, +) (*[]models.RelationshipTupleRead, error) { + return r.list(ctx, page, perPage, tenantFilter, subjectFilter, relationFilter, objectFilter, true) +} + +func (r *RelationshipTuples) list(ctx context.Context, + page int, + perPage int, + tenantFilter, + subjectFilter, + relationFilter, + objectFilter string, + detailed bool, +) (*[]models.RelationshipTupleRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing relationship tuples - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + request := r.client.RelationshipTuplesApi.ListRelationshipTuples( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).Page(int32(page)).PerPage(int32(perPage)) + + if tenantFilter != "" { + request = request.Tenant(tenantFilter) + } + + if subjectFilter != "" { + request = request.Subject(subjectFilter) + } + + if relationFilter != "" { + request = request.Relation(relationFilter) + } + + if objectFilter != "" { + request = request.Object(objectFilter) + } + + if detailed { + request = request.Detailed(detailed) + } + + relTuples, httpRes, err := request.Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing relationship tuples", zap.Error(err)) + return nil, err + } + + return &relTuples, nil +} + +func (r *RelationshipTuples) BulkCreate( + ctx context.Context, + bulkCreateOperation models.RelationshipTupleCreateBulkOperation, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + _, httpRes, err := r.client.RelationshipTuplesApi.BulkCreateRelationshipTuples(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).RelationshipTupleCreateBulkOperation(bulkCreateOperation).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error executing bulk relationship tuple creation", zap.Error(err)) + return err + } + + return nil +} + +func (r *RelationshipTuples) BulkDelete( + ctx context.Context, + bulkDeleteOperation models.RelationshipTupleDeleteBulkOperation, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + _, httpRes, err := r.client.RelationshipTuplesApi.BulkDeleteRelationshipTuples(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).RelationshipTupleDeleteBulkOperation(bulkDeleteOperation).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error executing bulk relationship tuple deletion", zap.Error(err)) + return err + } + + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resourceActionGroups.go b/vendor/github.com/permitio/permit-golang/pkg/api/resourceActionGroups.go new file mode 100644 index 00000000..d84b5c66 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resourceActionGroups.go @@ -0,0 +1,169 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ResourceActionGroups struct { + permitBaseApi +} + +func NewResourceActionGroupsApi(client *openapi.APIClient, config *config.PermitConfig) *ResourceActionGroups { + return &ResourceActionGroups{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all resource action groups of a resource by resource key. +// Usage Example: +// +// `resourceActions, err := PermitClient.Api.ResourceActions.List(ctx, "resource-key", 1, 10)` +func (a *ResourceActionGroups) List(ctx context.Context, resourceKey string, page int, perPage int) ([]models.ResourceActionGroupRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + a.logger.Error("error listing resource actions - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceActionGroups, _, err := a.client.ResourceActionGroupsApi.ListResourceActionGroups(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey).Page(int32(page)).PerPage(int32(perPage)).Execute() + if err != nil { + a.logger.Error("error listing resource action groups for resource: "+resourceKey, zap.Error(err)) + return nil, err + } + return resourceActionGroups, nil +} + +// ListByAttributes lists all action groups in the current environment by attributes filter +func (a *ResourceActionGroups) ListByAttributes(ctx context.Context, resourceKey string, page int, perPage int, attributesFilter map[string]interface{}) ([]models.ResourceActionGroupRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + a.logger.Error("error listing roles - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := a.lazyLoadPermitContext(ctx) + if err != nil { + a.logger.Error("", zap.Error(err)) + return nil, err + } + actionGroups, httpRes, err := a.client.ResourceActionGroupsApi.ListResourceActionGroups( + ctx, + a.config.Context.GetProject(), + a.config.Context.GetEnvironment(), + resourceKey, + ).Page(int32(page)).PerPage(int32(perPage)).AttributesFilter(attributesFilter).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + a.logger.Error("error listing action groups", zap.Error(err)) + return nil, err + } + return actionGroups, nil +} + +// Get a resource action by resource key and action key. +// Usage Example: +// +// `resourceAction, err := PermitClient.Api.ResourceActions.Get(ctx, "resource-key", "action-key")` +func (a *ResourceActionGroups) Get(ctx context.Context, resourceKey string, actionKey string) (*models.ResourceActionGroupRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceActionsGroups, _, err := a.client.ResourceActionGroupsApi.GetResourceActionGroup(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, actionKey).Execute() + if err != nil { + a.logger.Error("error getting resource action: "+resourceKey+":"+actionKey, zap.Error(err)) + return nil, err + } + return resourceActionsGroups, nil +} + +// GetByKey gets a resource action by resource key and action key. +// Usage Example: +// +// `resourceAction, err := PermitClient.Api.ResourceActions.GetByKey(ctx, "resource-key", "action-key")` +func (a *ResourceActionGroups) GetByKey(ctx context.Context, resourceKey string, actionKey string) (*models.ResourceActionGroupRead, error) { + return a.Get(ctx, resourceKey, actionKey) +} + +// GetById gets a resource action by resource ID and action ID. +// Usage Example: +// +// `resourceAction, err := PermitClient.Api.ResourceActions.GetById(ctx, uuid.New(), uuid.New())` +func (a *ResourceActionGroups) GetById(ctx context.Context, resourceKey uuid.UUID, actionKey uuid.UUID) (*models.ResourceActionGroupRead, error) { + return a.Get(ctx, resourceKey.String(), actionKey.String()) +} + +// Create a resource action by resource key. +// Usage Example: +// ``` +// +// resourceActionCreate := models.NewResourceActionCreate("action-key", "action-name") +// resourceAction, err := PermitClient.Api.ResourceActions.Create(ctx, "resource-key", resourceActionCreate) +// +// ``` +func (a *ResourceActionGroups) Create(ctx context.Context, resourceKey string, resourceActionCreate models.ResourceActionGroupCreate) (*models.ResourceActionGroupRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceActionGroup, _, err := a.client.ResourceActionGroupsApi.CreateResourceActionGroup(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey).ResourceActionGroupCreate(resourceActionCreate).Execute() + if err != nil { + a.logger.Error("error creating resource action: "+resourceKey+":"+resourceActionCreate.GetKey(), zap.Error(err)) + return nil, err + } + return resourceActionGroup, nil +} + +// Update a resource action by resource key and action key. +// Usage Example: +// ``` +// +// resourceActionUpdate := models.NewResourceActionUpdate() +// resourceActionUpdate.SetName("new-action-name") +// resourceAction, err := PermitClient.Api.ResourceActions.Update(ctx, "resource-key", "action-key", resourceActionUpdate) +// +// ``` +//func (a *ResourceActionGroups) Update(ctx context.Context, resourceKey string, actionKey string, resourceActionUpdate models.ResourceActionGroupUpdate) (*models.ResourceActionRead, error) { +// err := a.lazyLoadPermitContext(ctx) +// if err != nil { +// return nil, err +// } +// resourceAction, _, err := a.client.ResourceActionsApi.UpdateResourceAction(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, actionKey).ResourceActionUpdate(resourceActionUpdate).Execute() +// if err != nil { +// a.logger.Error("error updating resource action: "+resourceKey+":"+actionKey, zap.Error(err)) +// return nil, err +// } +// return resourceAction, nil +//} + +// Delete a resource action by resource key and action key. +// Usage Example: +// +// `err := PermitClient.Api.ResourceActions.Delete(ctx, "resource-key", "action-key")` +func (a *ResourceActionGroups) Delete(ctx context.Context, resourceKey string, actionKey string) error { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return err + } + _, err = a.client.ResourceActionsApi.DeleteResourceAction(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, actionKey).Execute() + if err != nil { + a.logger.Error("error deleting resource action: "+resourceKey+":"+actionKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resourceActions.go b/vendor/github.com/permitio/permit-golang/pkg/api/resourceActions.go new file mode 100644 index 00000000..4b2b48bb --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resourceActions.go @@ -0,0 +1,171 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ResourceActions struct { + permitBaseApi +} + +func NewResourceActionsApi(client *openapi.APIClient, config *config.PermitConfig) *ResourceActions { + return &ResourceActions{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all resource actions of a resource by resource key. +// Usage Example: +// +// `resourceActions, err := PermitClient.Api.ResourceActions.List(ctx, "resource-key", 1, 10)` +func (a *ResourceActions) List(ctx context.Context, resourceKey string, page int, perPage int) ([]models.ResourceActionRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + a.logger.Error("error listing resource actions - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceActions, _, err := a.client.ResourceActionsApi.ListResourceActions(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey).Page(int32(page)).PerPage(int32(perPage)).Execute() + if err != nil { + a.logger.Error("error listing resource actions for resource: "+resourceKey, zap.Error(err)) + return nil, err + } + return resourceActions, nil +} + +// List all actions in the current environment by attributes filter +// Usage Example: +// `actions, err := PermitClient.Api.ResourceActions.List(ctx,1, 10, map[string]string{"attribute": "xyz"})` +func (r *ResourceActions) ListByAttributes(ctx context.Context, resourceKey string, page int, perPage int, attributesFilter map[string]interface{}) ([]models.ResourceActionRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing roles - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + actions, httpRes, err := r.client.ResourceActionsApi.ListResourceActions( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceKey, + ).Page(int32(page)).PerPage(int32(perPage)).AttributesFilter(attributesFilter).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing roles", zap.Error(err)) + return nil, err + } + return actions, nil +} + +// Get a resource action by resource key and action key. +// Usage Example: +// +// `resourceAction, err := PermitClient.Api.ResourceActions.Get(ctx, "resource-key", "action-key")` +func (a *ResourceActions) Get(ctx context.Context, resourceKey string, actionKey string) (*models.ResourceActionRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceActions, _, err := a.client.ResourceActionsApi.GetResourceAction(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, actionKey).Execute() + if err != nil { + a.logger.Error("error getting resource action: "+resourceKey+":"+actionKey, zap.Error(err)) + return nil, err + } + return resourceActions, nil +} + +// GetByKey gets a resource action by resource key and action key. +// Usage Example: +// +// `resourceAction, err := PermitClient.Api.ResourceActions.GetByKey(ctx, "resource-key", "action-key")` +func (a *ResourceActions) GetByKey(ctx context.Context, resourceKey string, actionKey string) (*models.ResourceActionRead, error) { + return a.Get(ctx, resourceKey, actionKey) +} + +// GetById gets a resource action by resource ID and action ID. +// Usage Example: +// +// `resourceAction, err := PermitClient.Api.ResourceActions.GetById(ctx, uuid.New(), uuid.New())` +func (a *ResourceActions) GetById(ctx context.Context, resourceKey uuid.UUID, actionKey uuid.UUID) (*models.ResourceActionRead, error) { + return a.Get(ctx, resourceKey.String(), actionKey.String()) +} + +// Create a resource action by resource key. +// Usage Example: +// ``` +// +// resourceActionCreate := models.NewResourceActionCreate("action-key", "action-name") +// resourceAction, err := PermitClient.Api.ResourceActions.Create(ctx, "resource-key", resourceActionCreate) +// +// ``` +func (a *ResourceActions) Create(ctx context.Context, resourceKey string, resourceActionCreate models.ResourceActionCreate) (*models.ResourceActionRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceAction, _, err := a.client.ResourceActionsApi.CreateResourceAction(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey).ResourceActionCreate(resourceActionCreate).Execute() + if err != nil { + a.logger.Error("error creating resource action: "+resourceKey+":"+resourceActionCreate.GetKey(), zap.Error(err)) + return nil, err + } + return resourceAction, nil +} + +// Update a resource action by resource key and action key. +// Usage Example: +// ``` +// +// resourceActionUpdate := models.NewResourceActionUpdate() +// resourceActionUpdate.SetName("new-action-name") +// resourceAction, err := PermitClient.Api.ResourceActions.Update(ctx, "resource-key", "action-key", resourceActionUpdate) +// +// ``` +func (a *ResourceActions) Update(ctx context.Context, resourceKey string, actionKey string, resourceActionUpdate models.ResourceActionUpdate) (*models.ResourceActionRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceAction, _, err := a.client.ResourceActionsApi.UpdateResourceAction(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, actionKey).ResourceActionUpdate(resourceActionUpdate).Execute() + if err != nil { + a.logger.Error("error updating resource action: "+resourceKey+":"+actionKey, zap.Error(err)) + return nil, err + } + return resourceAction, nil +} + +// Delete a resource action by resource key and action key. +// Usage Example: +// +// `err := PermitClient.Api.ResourceActions.Delete(ctx, "resource-key", "action-key")` +func (a *ResourceActions) Delete(ctx context.Context, resourceKey string, actionKey string) error { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return err + } + _, err = a.client.ResourceActionsApi.DeleteResourceAction(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, actionKey).Execute() + if err != nil { + a.logger.Error("error deleting resource action: "+resourceKey+":"+actionKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resourceInstances.go b/vendor/github.com/permitio/permit-golang/pkg/api/resourceInstances.go new file mode 100644 index 00000000..3189f7b4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resourceInstances.go @@ -0,0 +1,232 @@ +package api + +import ( + "context" + + "time" + + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ResourceInstances struct { + PermitBaseFactsApi +} + +func NewResourceInstancesApi(client *openapi.APIClient, config *config.PermitConfig) *ResourceInstances { + return &ResourceInstances{ + PermitBaseFactsApi{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + }, + } +} + +// WaitForSync configures the client to wait for facts synchronization. +// +// Parameters: +// - timeout: Optional duration to wait for synchronization. +// - options: Additional configuration options for facts synchronization +func (r *ResourceInstances) WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *ResourceInstances { + return NewResourceInstancesApi(r.PermitBaseFactsApi.WaitForSync(timeout, options).client, r.config) +} + +func (r *ResourceInstances) Create( + ctx context.Context, + resourceInstanceCreate models.ResourceInstanceCreate, +) (*models.ResourceInstanceRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + created, httpRes, err := r.client.ResourceInstancesApi.CreateResourceInstance(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).ResourceInstanceCreate(resourceInstanceCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating resource instance", zap.Error(err)) + return nil, err + } + + r.logger.Debug("resource instance created", + zap.String("type", "resource_instance"), + zap.String("resource", created.GetResource()), + zap.String("key", created.GetKey()), + zap.String("id", created.Id), + ) + + return created, nil +} + +func (r *ResourceInstances) Delete( + ctx context.Context, + instanceId string, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := r.client.ResourceInstancesApi.DeleteResourceInstance(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + instanceId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting resource instance", zap.Error(err)) + return err + } + + return nil +} + +func (r *ResourceInstances) Get( + ctx context.Context, + instanceId string, +) (*models.ResourceInstanceRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + retrieved, httpRes, err := r.client.ResourceInstancesApi.GetResourceInstance(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + instanceId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting resource instance", zap.Error(err)) + return nil, err + } + + return retrieved, nil +} + +func (r *ResourceInstances) List( + ctx context.Context, + page int, + perPage int, + tenantFilter string, + resourceFilter string, + keyFilter string, +) (*[]models.ResourceInstanceRead, error) { + return r.list(ctx, page, perPage, tenantFilter, resourceFilter, keyFilter, false) +} + +func (r *ResourceInstances) ListDetailed( + ctx context.Context, + page int, + perPage int, + tenantFilter string, + resourceFilter string, + keyFilter string, +) (*[]models.ResourceInstanceRead, error) { + return r.list(ctx, page, perPage, tenantFilter, resourceFilter, keyFilter, true) +} + +func (r *ResourceInstances) list(ctx context.Context, + page int, + perPage int, + tenantFilter string, + resourceFilter string, + keyFilter string, + detailed bool, +) (*[]models.ResourceInstanceRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing relationship tuples - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + request := r.client.ResourceInstancesApi.ListResourceInstances( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).Page(int32(page)).PerPage(int32(perPage)) + + if tenantFilter != "" { + request = request.Tenant(tenantFilter) + } + + if resourceFilter != "" { + request = request.Resource(resourceFilter) + } + + if keyFilter != "" { + request = request.Search(keyFilter) + } + + if detailed { + request = request.Detailed(detailed) + } + + relTuples, httpRes, err := request.Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing resource instances", zap.Error(err)) + return nil, err + } + + return &relTuples, nil +} + +func (r *ResourceInstances) Update( + ctx context.Context, + instanceId string, + resourceInstanceUpdate models.ResourceInstanceUpdate, +) (*models.ResourceInstanceRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updated, httpRes, err := r.client.ResourceInstancesApi.UpdateResourceInstance( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + instanceId, + ).ResourceInstanceUpdate(resourceInstanceUpdate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error updating resource instance", zap.Error(err)) + return nil, err + } + + return updated, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resourceRelations.go b/vendor/github.com/permitio/permit-golang/pkg/api/resourceRelations.go new file mode 100644 index 00000000..62995d54 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resourceRelations.go @@ -0,0 +1,158 @@ +package api + +import ( + "context" + "fmt" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ResourceRelations struct { + permitBaseApi +} + +func NewResourceRelationsApi(client *openapi.APIClient, config *config.PermitConfig) *ResourceRelations { + return &ResourceRelations{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +func (r *ResourceRelations) Create( + ctx context.Context, + resourceId string, + relationCreate models.RelationCreate, +) (*models.RelationRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + created, httpRes, err := r.client.ResourceRelations.CreateResourceRelation( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + ).RelationCreate(relationCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating resource relation", zap.Error(err)) + return nil, err + } + + return created, nil +} + +func (r *ResourceRelations) Delete( + ctx context.Context, + resourceId string, + relationId string, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := r.client.ResourceRelations.DeleteResourceRelation(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + relationId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting resource instance", zap.Error(err)) + return err + } + + return nil +} + +func (r *ResourceRelations) Get( + ctx context.Context, + resourceId string, + relationId string, +) (*models.RelationRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + retrieved, httpRes, err := r.client.ResourceRelations.GetResourceRelation(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + relationId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting resource instance", zap.Error(err)) + return nil, err + } + + return retrieved, nil +} + +func (r *ResourceRelations) List( + ctx context.Context, + page int, + perPage int, + resourceId string, +) (*[]models.RelationRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing relationship tuples - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + request := r.client.ResourceRelations.ListResourceRelations( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + ).Page(int32(page)).PerPage(int32(perPage)) + + retrieved, httpRes, err := request.Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error listing resource instances", zap.Error(err)) + return nil, err + } + + if retrieved == nil { + errorMsg := "error listing resource instances - retrieved is nil" + r.logger.Error(errorMsg) + return nil, fmt.Errorf(errorMsg) + } + + return &retrieved.Data, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resourceRoles.go b/vendor/github.com/permitio/permit-golang/pkg/api/resourceRoles.go new file mode 100644 index 00000000..0a5a102c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resourceRoles.go @@ -0,0 +1,372 @@ +package api + +import ( + "context" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ResourceRoles struct { + permitBaseApi +} + +func NewResourceRolesApi(client *openapi.APIClient, config *config.PermitConfig) *ResourceRoles { + return &ResourceRoles{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +func (r *ResourceRoles) Create( + ctx context.Context, + resourceId string, + resourceRoleCreate models.ResourceRoleCreate, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + created, httpRes, err := r.client.ResourceRoles.CreateResourceRole(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + ).ResourceRoleCreate(resourceRoleCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating resource role", zap.Error(err)) + return nil, err + } + + return created, nil +} + +func (r *ResourceRoles) Delete( + ctx context.Context, + resourceId string, + roleId string, +) error { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + + httpRes, err := r.client.ResourceRoles.DeleteResourceRole(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error deleting resource role", zap.Error(err)) + return err + } + + return nil +} + +func (r *ResourceRoles) Get( + ctx context.Context, + resourceId string, + roleId string, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + retrieved, httpRes, err := r.client.ResourceRoles.GetResourceRole(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error getting resource role", zap.Error(err)) + return nil, err + } + + return retrieved, nil +} + +func (r *ResourceRoles) List( + ctx context.Context, + page int, + perPage int, + resourceId string, +) (*[]models.ResourceRoleRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing resource roles - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + request := r.client.ResourceRoles.ListResourceRoles( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + ).Page(int32(page)).PerPage(int32(perPage)) + + retrieved, httpRes, err := request.Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing resource roles", zap.Error(err)) + return nil, err + } + + return &retrieved, nil +} + +func (r *ResourceRoles) Update( + ctx context.Context, + resourceId string, + roleId string, + resourceInstanceUpdate models.ResourceRoleUpdate, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updated, httpRes, err := r.client.ResourceRoles.UpdateResourceRole( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).ResourceRoleUpdate(resourceInstanceUpdate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error updating resource role", zap.Error(err)) + return nil, err + } + + return updated, nil +} + +func (r *ResourceRoles) AddParent( + ctx context.Context, + resourceId string, + roleId string, + parentRoleId string, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updated, httpRes, err := r.client.ResourceRoles.AddParentResourceRole(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + parentRoleId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error adding parent to resource role", zap.Error(err)) + return nil, err + } + + return updated, nil +} + +func (r *ResourceRoles) RemoveParent( + ctx context.Context, + resourceId string, + roleId string, + parentRoleId string, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updated, httpRes, err := r.client.ResourceRoles.RemoveParentResourceRole(ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + parentRoleId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating resource instance", zap.Error(err)) + return nil, err + } + + return updated, nil +} + +func (r *ResourceRoles) AssignPermissions( + ctx context.Context, + resourceId string, + roleId string, + addRolePermissions models.AddRolePermissions, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updated, httpRes, err := r.client.ResourceRoles.AssignPermissionsToResourceRole( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).AddRolePermissions(addRolePermissions).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error assigning permissions", zap.Error(err)) + return nil, err + } + + return updated, nil +} + +func (r *ResourceRoles) RemovePermissions( + ctx context.Context, + resourceId string, + roleId string, + removeRolePermissions models.RemoveRolePermissions, +) (*models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + updated, httpRes, err := r.client.ResourceRoles.RemovePermissionsFromResourceRole( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).RemoveRolePermissions(removeRolePermissions).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error removing permissions", zap.Error(err)) + return nil, err + } + + return updated, nil +} + +func (r *ResourceRoles) GetAncestors( + ctx context.Context, + resourceId string, + roleId string, +) (*[]models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + retrieved, httpRes, err := r.client.ResourceRoles.GetResourceRoleAncestors( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error assigning permissions", zap.Error(err)) + return nil, err + } + + if retrieved.Roles.PaginatedResultResourceRoleRead != nil { + return &retrieved.Roles.PaginatedResultResourceRoleRead.Data, nil + } else { + return retrieved.Roles.ResourceRoleRead, nil + } +} + +func (r *ResourceRoles) GetDescendants( + ctx context.Context, + resourceId string, + roleId string, +) (*[]models.ResourceRoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + retrieved, httpRes, err := r.client.ResourceRoles.GetResourceRoleDescendants( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + resourceId, + roleId, + ).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error assigning permissions", zap.Error(err)) + return nil, err + } + + if retrieved.Roles.PaginatedResultResourceRoleRead != nil { + return &retrieved.Roles.PaginatedResultResourceRoleRead.Data, nil + } else { + return retrieved.Roles.ResourceRoleRead, nil + } +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resources.go b/vendor/github.com/permitio/permit-golang/pkg/api/resources.go new file mode 100644 index 00000000..0bdb7a46 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resources.go @@ -0,0 +1,187 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type Resources struct { + permitBaseApi +} + +func NewResourcesApi(client *openapi.APIClient, config *config.PermitConfig) *Resources { + return &Resources{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all the resources in the current environment. +// Usage Example: +// +// `resources, err := PermitClient.Api.Resources.List(ctx, 1, 10)` +func (r *Resources) List(ctx context.Context, page int, perPage int) ([]models.ResourceRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing resources - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + resources, httpRes, err := r.client.ResourcesApi.ListResources(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing resources", zap.Error(err)) + return nil, err + } + return resources, nil +} + +// Search for resources by key or name. +// Usage Example: +// +// `resources, err := PermitClient.Api.Resources.List(ctx, 1, 10)` +func (r *Resources) Search(ctx context.Context, page int, perPage int, query string) ([]models.ResourceRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing resources - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + resources, httpRes, err := r.client.ResourcesApi.ListResources( + ctx, + r.config.Context.GetProject(), + r.config.Context.GetEnvironment(), + ).Page(int32(page)).PerPage(int32(perPage)).Search(query).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error listing resources", zap.Error(err)) + return nil, err + } + + return resources, nil +} + +// Get a resource by its key. +// Usage Example: +// +// `resource, err := PermitClient.Api.Resources.Get(ctx, "my-resource")` +func (r *Resources) Get(ctx context.Context, resourceKey string) (*models.ResourceRead, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + resource, httpRes, err := r.client.ResourcesApi.GetResource(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), resourceKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error getting resource: "+resourceKey, zap.Error(err)) + return nil, err + } + return resource, nil +} + +// GetByKey gets a resource by its key. +// Usage Example: +// +// `resource, err := PermitClient.Api.Resources.GetByKey(ctx, "my-resource")` +func (r *Resources) GetByKey(ctx context.Context, resourceKey string) (*models.ResourceRead, error) { + return r.Get(ctx, resourceKey) +} + +// GetById gets a resource by its ID. +// Usage Example: +// +// `resource, err := PermitClient.Api.Resources.GetById(ctx, uuid.New())` +func (r *Resources) GetById(ctx context.Context, resourceId uuid.UUID) (*models.ResourceRead, error) { + return r.Get(ctx, resourceId.String()) +} + +// Create a new resource. +// Usage Example: +// ``` +// +// resourceCreate := models.NewResourceCreate("document", "Document", map[string]models.ActionBlockEditable{"read": {}, "write": {}} +// resource, err := PermitClient.Api.Resources.Create(ctx, resourceCreate) +// +// ``` +func (r *Resources) Create(ctx context.Context, resourceCreate models.ResourceCreate) (*models.ResourceRead, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + resource, httpRes, err := r.client.ResourcesApi.CreateResource(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).ResourceCreate(resourceCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error creating resource: "+resourceCreate.GetKey(), zap.Error(err)) + return nil, err + } + return resource, nil +} + +// Update a resource. +// Usage Example: +// ``` +// +// resourceUpdate := models.NewResourceUpdate() +// resourceUpdate.SetActions(map[string]models.ActionBlockEditable{"read": {}, "write": {}} +// resource, err := PermitClient.Api.Resources.Update(ctx, "my-resource", resourceUpdate) +// +// ``` +func (r *Resources) Update(ctx context.Context, resourceKey string, resourceUpdate models.ResourceUpdate) (*models.ResourceRead, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + resource, httpRes, err := r.client.ResourcesApi.UpdateResource(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), resourceKey).ResourceUpdate(resourceUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error updating resource: "+resourceKey, zap.Error(err)) + return nil, err + } + return resource, nil +} + +// Delete a resource. +// Usage Example: +// +// `err := PermitClient.Api.Resources.Delete(ctx, "my-resource")` +func (r *Resources) Delete(ctx context.Context, resourceKey string) error { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := r.client.ResourcesApi.DeleteResource(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), resourceKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error deleting resource: "+resourceKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/resoureAttributes.go b/vendor/github.com/permitio/permit-golang/pkg/api/resoureAttributes.go new file mode 100644 index 00000000..84d83ae8 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/resoureAttributes.go @@ -0,0 +1,141 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type ResourceAttributes struct { + permitBaseApi +} + +func NewResourceAttributesApi(client *openapi.APIClient, config *config.PermitConfig) *ResourceAttributes { + return &ResourceAttributes{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +// List all resource attributes of a resource, by resource key. +// Usage Example: +// +// `resourceAttributes, err := PermitClient.Api.ResourceAttributes.List(ctx, "resource-key", 1, 10)` +func (a *ResourceAttributes) List(ctx context.Context, resourceKey string, page int, perPage int) ([]models.ResourceAttributeRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + a.logger.Error("error listing resource attributes - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceAttributes, _, err := a.client.ResourceAttributesApi.ListResourceAttributes(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey).Page(int32(page)).PerPage(int32(perPage)).Execute() + if err != nil { + a.logger.Error("error listing resource attributes for resource: "+resourceKey, zap.Error(err)) + return nil, err + } + return resourceAttributes, nil +} + +// Get a resource attribute by resource key and attribute key. +// Usage Example: +// +// `resourceAttribute, err := PermitClient.Api.ResourceAttributes.Get(ctx, "resource-key", "attribute-key")` +func (a *ResourceAttributes) Get(ctx context.Context, resourceKey string, attributeKey string) (*models.ResourceAttributeRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceAttribute, _, err := a.client.ResourceAttributesApi.GetResourceAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, attributeKey).Execute() + if err != nil { + a.logger.Error("error getting resource attribute: "+resourceKey+":"+attributeKey, zap.Error(err)) + return nil, err + } + return resourceAttribute, nil +} + +// GetByKey gets a resource attribute by resource key and attribute key. +// Usage Example: +// +// `resourceAttribute, err := PermitClient.Api.ResourceAttributes.GetByKey(ctx, "resource-key", "attribute-key")` +func (a *ResourceAttributes) GetByKey(ctx context.Context, resourceKey string, attributeKey string) (*models.ResourceAttributeRead, error) { + return a.Get(ctx, resourceKey, attributeKey) +} + +// GetById gets a resource attribute by resource ID and attribute ID. +// Usage Example: +// +// `resourceAttribute, err := PermitClient.Api.ResourceAttributes.GetById(ctx, uuid.New(), uuid.New())` +func (a *ResourceAttributes) GetById(ctx context.Context, resourceKey uuid.UUID, attributeKey uuid.UUID) (*models.ResourceAttributeRead, error) { + return a.Get(ctx, resourceKey.String(), attributeKey.String()) +} + +// Create a resource attribute by resource key. +// Usage Example: +// ``` +// +// resourceAttributeCreate := models.NewResourceAttributeCreate("attribute-key", models.AttributeType("string")) +// resourceAttribute, err := PermitClient.Api.ResourceAttributes.Create(ctx, "resource-key", resourceAttributeCreate) +// +// ``` +func (a *ResourceAttributes) Create(ctx context.Context, resourceKey string, resourceAttributeCreate models.ResourceAttributeCreate) (*models.ResourceAttributeRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceAttribute, _, err := a.client.ResourceAttributesApi.CreateResourceAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey).ResourceAttributeCreate(resourceAttributeCreate).Execute() + if err != nil { + a.logger.Error("error creating resource attribute: "+resourceKey+":"+resourceAttributeCreate.GetKey(), zap.Error(err)) + return nil, err + } + return resourceAttribute, nil +} + +// Update a resource attribute by resource key and attribute key. +// Usage Example: +// ``` +// +// resourceAttributeUpdate := models.NewResourceAttributeUpdate() +// resourceAttributeUpdate.SetType("bool") +// resourceAttribute, err := PermitClient.Api.ResourceAttributes.Update(ctx, "resource-key", "attribute-key", resourceAttributeUpdate) +// +// ``` +func (a *ResourceAttributes) Update(ctx context.Context, resourceKey string, attributeKey string, resourceAttributeUpdate models.ResourceAttributeUpdate) (*models.ResourceAttributeRead, error) { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return nil, err + } + resourceAttribute, _, err := a.client.ResourceAttributesApi.UpdateResourceAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, attributeKey).ResourceAttributeUpdate(resourceAttributeUpdate).Execute() + if err != nil { + a.logger.Error("error updating resource attribute: "+resourceKey+":"+attributeKey, zap.Error(err)) + return nil, err + } + return resourceAttribute, nil +} + +// Delete a resource attribute by resource key and attribute key. +// Usage Example: +// +// `err := PermitClient.Api.ResourceAttributes.Delete(ctx, "resource-key", "attribute-key")` +func (a *ResourceAttributes) Delete(ctx context.Context, resourceKey string, attributeKey string) error { + err := a.lazyLoadPermitContext(ctx) + if err != nil { + return err + } + _, err = a.client.ResourceAttributesApi.DeleteResourceAttribute(ctx, a.config.Context.GetProject(), a.config.Context.GetEnvironment(), resourceKey, attributeKey).Execute() + if err != nil { + a.logger.Error("error deleting resource attribute: "+resourceKey+":"+attributeKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/roleAssignments.go b/vendor/github.com/permitio/permit-golang/pkg/api/roleAssignments.go new file mode 100644 index 00000000..c7ba9800 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/roleAssignments.go @@ -0,0 +1,99 @@ +package api + +import ( + "context" + "time" + + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type RoleAssignments struct { + PermitBaseFactsApi +} + +func NewRoleAssignmentsApi(client *openapi.APIClient, config *config.PermitConfig) *RoleAssignments { + return &RoleAssignments{ + PermitBaseFactsApi{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + }, + } +} + +// WaitForSync configures the client to wait for facts synchronization. +// +// Parameters: +// - timeout: Optional duration to wait for synchronization. +// - options: Additional configuration options for facts synchronization +func (r *RoleAssignments) WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *RoleAssignments { + return NewRoleAssignmentsApi(r.PermitBaseFactsApi.WaitForSync(timeout, options).client, r.config) +} + +func (r *RoleAssignments) List(ctx context.Context, page int, perPage int, userFilter, roleFilter, tenantFilter string) (*[]models.RoleAssignmentRead, error) { + response, err := r.list(ctx, page, perPage, userFilter, roleFilter, tenantFilter, false) + if err != nil { + return nil, err + } + return response.RoleAssignmentRead, nil +} + +func (r *RoleAssignments) ListDetailed(ctx context.Context, page int, perPage int, userFilter, roleFilter, tenantFilter string) (*[]models.RoleAssignmentDetailedRead, error) { + response, err := r.list(ctx, page, perPage, userFilter, roleFilter, tenantFilter, true) + if err != nil { + return nil, err + } + return response.RoleAssignmentDetailedRead, nil +} + +func (r *RoleAssignments) list(ctx context.Context, page int, perPage int, userFilter, roleFilter, tenantFilter string, detailed bool) (*models.ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet, error) { + perPageLimit := int32(DefaultPerPageLimit) + + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing users - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + + err := r.lazyLoadPermitContext(ctx) + + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + request := r.client.RoleAssignmentsApi.ListRoleAssignments(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()). + Page(int32(page)).PerPage(int32(perPage)) + + if userFilter != "" { + request = request.User(userFilter) + } + + if roleFilter != "" { + request = request.Role(roleFilter) + } + + if tenantFilter != "" { + request = request.Tenant(tenantFilter) + } + + if detailed { + request = request.Detailed(detailed) + } + + roleAssignments, httpRes, err := request.Execute() + + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing roles assignments", zap.Error(err)) + return nil, err + } + + return roleAssignments, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/roles.go b/vendor/github.com/permitio/permit-golang/pkg/api/roles.go new file mode 100644 index 00000000..77759b64 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/roles.go @@ -0,0 +1,300 @@ +package api + +import ( + "context" + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type Roles struct { + permitBaseApi +} + +func NewRolesApi(client *openapi.APIClient, config *config.PermitConfig) *Roles { + return &Roles{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + } +} + +type RoleRead struct { + models.RoleRead +} + +// List all roles in the current environment. +// Usage Example: +// `roles, err := PermitClient.Api.Roles.List(ctx,1, 10)` +func (r *Roles) List(ctx context.Context, page int, perPage int) ([]models.RoleRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing roles - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + roles, httpRes, err := r.client.RolesApi.ListRoles(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing roles", zap.Error(err)) + return nil, err + } + return roles, nil +} + +// List all roles in the current environment by attributes filter +// Usage Example: +// `roles, err := PermitClient.Api.Roles.List(ctx,1, 10, map[string]string{"attribute": "xyz"})` +func (r *Roles) ListByAttributes(ctx context.Context, page int, perPage int, attributesFilter map[string]interface{}) ([]models.RoleRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + r.logger.Error("error listing roles - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + roles, httpRes, err := r.client.RolesApi.ListRoles(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).Page(int32(page)).PerPage(int32(perPage)).AttributesFilter(attributesFilter).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error listing roles", zap.Error(err)) + return nil, err + } + return roles, nil +} + +// Get a role by key. +// Usage Example: +// `role, err := PermitClient.Api.Roles.Get(ctx, "role-key")` +func (r *Roles) Get(ctx context.Context, roleKey string) (*models.RoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + role, httpRes, err := r.client.RolesApi.GetRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error getting role: "+roleKey, zap.Error(err)) + return nil, err + } + + return role, nil +} + +// GetByKey get a role by key. +// Usage Example: +// `role, err := PermitClient.Api.Roles.GetByKey(ctx, "role-key")` +func (r *Roles) GetByKey(ctx context.Context, roleKey string) (*models.RoleRead, error) { + return r.Get(ctx, roleKey) +} + +// GetById get a role by id. +// Usage Example: +// `role, err := PermitClient.Api.Roles.GetById(ctx, uuid.New())` +func (r *Roles) GetById(ctx context.Context, roleKey uuid.UUID) (*models.RoleRead, error) { + return r.Get(ctx, roleKey.String()) +} + +// Create a new role. +// Usage Example: +// ``` +// roleCreate := models.NewRoleCreate("role-key", "role-name") +// role, err := PermitClient.Api.Roles.Create(ctx, roleCreate) +// ``` +func (r *Roles) Create(ctx context.Context, roleCreate models.RoleCreate) (*models.RoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + role, httpRes, err := r.client.RolesApi.CreateRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).RoleCreate(roleCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + r.logger.Error("error creating role: "+roleCreate.GetKey(), zap.Error(err)) + return nil, err + } + + r.logger.Debug("role created", + zap.String("type", "role"), + zap.String("key", role.GetKey()), + zap.String("id", role.Id), + ) + + return role, nil +} + +// Update a role. +// Usage Example: +// ``` +// roleUpdate := models.NewRoleUpdate() +// roleUpdate.SetName("new-role-name") +// role, err := PermitClient.Api.Roles.Update(ctx, "role-key", roleUpdate) +// ``` +func (r *Roles) Update(ctx context.Context, roleKey string, roleUpdate models.RoleUpdate) (*models.RoleRead, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + role, httpRes, err := r.client.RolesApi.UpdateRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey).RoleUpdate(roleUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error updating role: "+roleKey, zap.Error(err)) + return nil, err + } + return role, nil +} + +// Delete a role. +// Usage Example: +// `err := PermitClient.Api.Roles.Delete(ctx, "role-key")` +func (r *Roles) Delete(ctx context.Context, roleKey string) error { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := r.client.RolesApi.DeleteRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error deleting role: "+roleKey, zap.Error(err)) + return err + } + return nil +} + +// AssignPermissions assign permissions to a role, by role key and list of permission keys. +// If a permission is already granted to the role it is skipped. +// Each permission can be either a resource-action key, or {resource_key}:{action_key}, i.e: the "document:read". +// Usage Example: +// `err := PermitClient.Api.Roles.AssignPermissions(ctx, "role-key", []string{"document:read", "document:write"})` +func (r *Roles) AssignPermissions(ctx context.Context, roleKey string, permissions []string) error { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + addRolePermissions := *models.NewAddRolePermissions(permissions) + _, httpRes, err := r.client.RolesApi.AssignPermissionsToRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey).AddRolePermissions(addRolePermissions).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error assigning these permissions: '"+listToString(permissions)+"' to role: "+roleKey, zap.Error(err)) + return err + } + return nil +} + +// RemovePermissions remove permissions from a role, by role key and list of permission keys. +// If a permission is not found it is skipped. +// Each permission can be either a resource-action key, or {resource_key}:{action_key}, i.e: the "document:read". +// Usage Example: +// `err := PermitClient.Api.Roles.RemovePermissions(ctx, "role-key", []string{"document:read", "document:write"})` +func (r *Roles) RemovePermissions(ctx context.Context, roleKey string, permissions []string) error { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + removeRolePermissions := *models.NewRemoveRolePermissions(permissions) + _, httpRes, err := r.client.RolesApi.RemovePermissionsFromRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey).RemoveRolePermissions(removeRolePermissions).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error removing these permissions: '"+listToString(permissions)+"' from role: "+roleKey, zap.Error(err)) + return err + } + return nil +} + +func (r *Roles) BulkAssignRole(ctx context.Context, assignments []models.RoleAssignmentCreate) (*models.BulkRoleAssignmentReport, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + req := r.client.RoleAssignmentsApi.BulkAssignRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).RoleAssignmentCreate(assignments) + report, resp, err := req.Execute() + + err = errors.HttpErrorHandle(err, resp) + + if err != nil { + r.logger.Error("failed assigning roles in bulk", zap.Error(err), zap.Int("count", len(assignments))) + return nil, err + } + + return report, nil +} + +func (r *Roles) BulkUnAssignRole(ctx context.Context, unassignments []models.RoleAssignmentRemove) (*models.BulkRoleUnAssignmentReport, error) { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return nil, err + } + + req := r.client.RoleAssignmentsApi.BulkUnassignRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment()).RoleAssignmentRemove(unassignments) + report, resp, err := req.Execute() + + err = errors.HttpErrorHandle(err, resp) + + if err != nil { + r.logger.Error("failed assigning roles in bulk", zap.Error(err), zap.Int("count", len(unassignments))) + return nil, err + } + + return report, nil +} + +// AddParentRole add a parent role to a role, by role key and parent role key. +// Makes a role extend the parent role. +// In other words, a role will automatically be assigned any permissions that are granted to the parent role. +// We can say the role extends the parent role or inherits from the parent role. +// Usage Example: +// `err := PermitClient.Api.Roles.AddParentRole(ctx, "role-key", "parent-role-key")` +func (r *Roles) AddParentRole(ctx context.Context, roleKey string, parentRoleKey string) error { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + _, httpRes, err := r.client.RolesApi.AddParentRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey, parentRoleKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error adding parent role: '"+parentRoleKey+"' to role: "+roleKey, zap.Error(err)) + return err + } + return nil +} + +// RemoveParentRole remove a parent role from a role, by role key and parent role key. +// Usage Example: +// `err := PermitClient.Api.Roles.RemoveParentRole(ctx, "role-key", "parent-role-key")` +func (r *Roles) RemoveParentRole(ctx context.Context, roleKey string, parentRoleKey string) error { + err := r.lazyLoadPermitContext(ctx) + if err != nil { + r.logger.Error("", zap.Error(err)) + return err + } + _, httpRes, err := r.client.RolesApi.RemoveParentRole(ctx, r.config.Context.GetProject(), r.config.Context.GetEnvironment(), roleKey, parentRoleKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + r.logger.Error("error removing parent role: '"+parentRoleKey+"' from role: "+roleKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/tenants.go b/vendor/github.com/permitio/permit-golang/pkg/api/tenants.go new file mode 100644 index 00000000..3d7180bb --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/tenants.go @@ -0,0 +1,188 @@ +package api + +import ( + "context" + "time" + + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type Tenants struct { + PermitBaseFactsApi +} + +func NewTenantsApi(client *openapi.APIClient, config *config.PermitConfig) *Tenants { + return &Tenants{ + PermitBaseFactsApi{ + permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + }, + } +} + +// WaitForSync configures the client to wait for facts synchronization. +// +// Parameters: +// - timeout: Optional duration to wait for synchronization. +// - options: Additional configuration options for facts synchronization +func (t *Tenants) WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *Tenants { + return NewTenantsApi(t.PermitBaseFactsApi.WaitForSync(timeout, options).client, t.config) +} + +// List all tenants under the context's environment. +// Usage Example: +// `tenants, err := PermitClient.Api.Tenants.List(ctx, 1, 10)` +func (t *Tenants) List(ctx context.Context, page int, perPage int) ([]models.TenantRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + t.logger.Error("error listing tenants - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := t.lazyLoadPermitContext(ctx) + if err != nil { + t.logger.Error("", zap.Error(err)) + return nil, err + } + tenants, httpRes, err := t.client.TenantsApi.ListTenants(ctx, t.config.Context.ProjectId, t.config.Context.EnvironmentId).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + t.logger.Error("error listing tenants", zap.Error(err)) + } + return tenants, nil +} + +// ListTenantsByAttributes gets tenants under the context's environment - by a given attributes. +// Usage Example: +// `tenants, err := PermitClient.Api.Tenants.ListTenantsByAttributes(ctx, map[string]string{"key": "value"})` +func (t *Tenants) ListByAttributes(ctx context.Context, attributes map[string]interface{}, page int, perPage int) ([]models.TenantRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + t.logger.Error("error listing tenants - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := t.lazyLoadPermitContext(ctx) + if err != nil { + t.logger.Error("", zap.Error(err)) + return nil, err + } + tenants, httpRes, err := t.client.TenantsApi.ListTenants(ctx, t.config.Context.ProjectId, t.config.Context.EnvironmentId).Page(int32(page)).PerPage(int32(perPage)).AttributeFilter(attributes).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + t.logger.Error("error listing tenants", zap.Error(err)) + } + return tenants, nil + +} + +// Get a tenant under the context's environment - by a given tenant key. +// Usage Example: +// `tenant, err := PermitClient.Api.Tenants.Get(ctx, "tenant-key")` +func (t *Tenants) Get(ctx context.Context, tenantKey string) (*models.TenantRead, error) { + err := t.lazyLoadPermitContext(ctx) + if err != nil { + t.logger.Error("", zap.Error(err)) + return nil, err + } + tenant, httpRes, err := t.client.TenantsApi.GetTenant(ctx, t.config.Context.ProjectId, t.config.Context.EnvironmentId, tenantKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + t.logger.Error("error getting tenant: "+tenantKey, zap.Error(err)) + return nil, err + } + + return tenant, nil +} + +// GetByKey gets a tenant under the context's environment - by a given tenant key. +// Usage Example: +// `tenant, err := PermitClient.Api.Tenants.GetByKey(ctx, "tenant-key")` +func (t *Tenants) GetByKey(ctx context.Context, tenantKey string) (*models.TenantRead, error) { + return t.Get(ctx, tenantKey) +} + +// GetById gets a tenant under the context's environment - by a given tenant id. +// Usage Example: +// `tenant, err := PermitClient.Api.Tenants.GetById(ctx, uuid.New())` +func (t *Tenants) GetById(ctx context.Context, tenantId uuid.UUID) (*models.TenantRead, error) { + return t.Get(ctx, tenantId.String()) +} + +// Create a new tenant under the context's environment. +// Usage Example: +// ``` +// tenantCreate := models.NewTenantCreate("tenant-key", "tenant-name") +// tenant, err := PermitClient.Api.Tenants.Create(ctx, tenantCreate) +// ``` +func (t *Tenants) Create(ctx context.Context, tenantCreate models.TenantCreate) (*models.TenantRead, error) { + err := t.lazyLoadPermitContext(ctx) + if err != nil { + t.logger.Error("", zap.Error(err)) + return nil, err + } + + tenant, httpRes, err := t.client.TenantsApi.CreateTenant(ctx, t.config.Context.ProjectId, t.config.Context.EnvironmentId).TenantCreate(tenantCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + t.logger.Error("error creating tenant: "+tenantCreate.GetKey(), zap.Error(err)) + return nil, err + } + + t.logger.Debug("tenant created", + zap.String("type", "tenant"), + zap.String("key", tenant.GetKey()), + zap.String("id", tenant.Id), + ) + + return tenant, nil +} + +// Update a tenant under the context's environment. +// Usage Example: +// ``` +// tenantUpdate := models.NewTenantUpdate() +// tenantUpdate.SetName("new-tenant-name") +// tenant, err := PermitClient.Api.Tenants.Update(ctx, "tenant-key", tenantUpdate) +// ``` +func (t *Tenants) Update(ctx context.Context, tenantKey string, tenantUpdate models.TenantUpdate) (*models.TenantRead, error) { + err := t.lazyLoadPermitContext(ctx) + if err != nil { + t.logger.Error("", zap.Error(err)) + return nil, err + } + tenant, httpRes, err := t.client.TenantsApi.UpdateTenant(ctx, t.config.Context.ProjectId, t.config.Context.EnvironmentId, tenantKey).TenantUpdate(tenantUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + t.logger.Error("error updating tenant: "+tenantKey, zap.Error(err)) + return nil, err + } + return tenant, nil +} + +// Delete a tenant under the context's environment. +// Usage Example: +// `err := PermitClient.Api.Tenants.Delete(ctx, "tenant-key")` +func (t *Tenants) Delete(ctx context.Context, tenantKey string) error { + err := t.lazyLoadPermitContext(ctx) + if err != nil { + t.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := t.client.TenantsApi.DeleteTenant(ctx, t.config.Context.ProjectId, t.config.Context.EnvironmentId, tenantKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + t.logger.Error("error deleting tenant: "+tenantKey, zap.Error(err)) + return err + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/users.go b/vendor/github.com/permitio/permit-golang/pkg/api/users.go new file mode 100644 index 00000000..48ff7392 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/users.go @@ -0,0 +1,349 @@ +package api + +import ( + "context" + "strings" + "time" + + "github.com/google/uuid" + "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/models" + "github.com/permitio/permit-golang/pkg/openapi" + "go.uber.org/zap" +) + +type Users struct { + PermitBaseFactsApi +} + +func NewUsersApi(client *openapi.APIClient, config *config.PermitConfig) *Users { + return &Users{ + PermitBaseFactsApi{ + permitBaseApi: permitBaseApi{ + client: client, + config: config, + logger: config.Logger, + }, + }, + } +} + +// WaitForSync configures the client to wait for facts synchronization. +// +// Parameters: +// - timeout: Optional duration to wait for synchronization. +// - options: Additional configuration options for facts synchronization +func (u *Users) WaitForSync(timeout *time.Duration, options WaitForSyncOptions) *Users { + return NewUsersApi(u.PermitBaseFactsApi.WaitForSync(timeout, options).client, u.config) +} + +// List the users from your context's environment. +// Usage Example: +// +// `users, err := PermitClient.Api.Users.List(ctx, 1, 10)` +func (u *Users) List(ctx context.Context, page int, perPage int) ([]models.UserRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + u.logger.Error("error listing users - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + users, httpRes, err := u.client.UsersApi.ListUsers(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment()).Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error listing users", zap.Error(err)) + return nil, err + } + return users.GetData(), nil +} + +// Get a user from your context's environment. +// Usage Example: +// +// `user, err := PermitClient.Api.Users.Get(ctx, "user-key")` +func (u *Users) Get(ctx context.Context, userKey string) (*models.UserRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + user, httpRes, err := u.client.UsersApi.GetUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error getting user: "+userKey, zap.Error(err)) + return nil, err + } + return user, nil +} + +// GetByKey gets a user by key from your context's environment. +// Usage Example: +// +// `user, err := PermitClient.Api.Users.GetByKey(ctx, "user-key")` +func (u *Users) GetByKey(ctx context.Context, userKey string) (*models.UserRead, error) { + return u.Get(ctx, userKey) +} + +// GetById gets a user by id from your context's environment. +// Usage Example: +// +// `user, err := PermitClient.Api.Users.GetById(ctx, uuid.New())` +func (u *Users) GetById(ctx context.Context, userId uuid.UUID) (*models.UserRead, error) { + return u.Get(ctx, userId.String()) +} + +// Create a user in your context's environment. +// Usage Example: +// ``` +// +// userCreate := models.NewUserCreate("user-key") +// userCreate.SetEmail("user-email@mail.com") +// userCreate.SetFirstName("user-first-name") +// userCreate.SetLastName("user-last-name") +// user, err := PermitClient.Api.Users.Create(ctx, userCreate) +// +// ``` +func (u *Users) Create(ctx context.Context, userCreate models.UserCreate) (*models.UserRead, error) { + err := u.lazyLoadPermitContext(ctx) + + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + + user, httpRes, err := u.client.UsersApi.CreateUser( + ctx, + u.config.Context.GetProject(), + u.config.Context.GetEnvironment(), + ).UserCreate(userCreate).Execute() + + err = errors.HttpErrorHandle(err, httpRes) + + if err != nil { + u.logger.Error("error creating user:"+userCreate.GetKey(), zap.Error(err)) + return nil, err + } + + u.logger.Debug("user created", + zap.String("type", "user"), + zap.String("key", user.GetKey()), + zap.String("id", user.Id), + ) + + return user, nil +} + +// Update a user in your context's environment. +// Usage Example: +// ``` +// +// userUpdate := models.NewUserUpdate() +// userUpdate.SetEmail("new@email.com") +// userUpdate.SetFirstName("new-first-name") +// userUpdate.SetLastName("new-last-name") +// user, err := PermitClient.Api.Users.Update(ctx, "user-key", userUpdate) +// +// ``` +func (u *Users) Update(ctx context.Context, userKey string, userUpdate models.UserUpdate) (*models.UserRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + user, httpRes, err := u.client.UsersApi.UpdateUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).UserUpdate(userUpdate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error updating user:"+userKey, zap.Error(err)) + return nil, err + } + return user, nil +} + +// Delete a user from your context's environment. +// Usage Example: +// +// `err := PermitClient.Api.Users.Delete(ctx, "user-key")` +func (u *Users) Delete(ctx context.Context, userKey string) error { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return err + } + httpRes, err := u.client.UsersApi.DeleteUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error deleting user:"+userKey, zap.Error(err)) + return err + } + return nil +} + +// AssignRole assigns a role to a user in your context's environment, by user key, role key and tenant key. +// Usage Example: +// `roleAssignment, err := PermitClient.Api.Users.AssignRole(ctx, "user-key", "role-key", "default")` +func (u *Users) AssignRole(ctx context.Context, userKey string, roleKey string, tenantKey string) (*models.RoleAssignmentRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + userRoleCreate := *models.NewUserRoleCreate(roleKey, tenantKey) + roleAssignmentRead, httpRes, err := u.client.UsersApi.AssignRoleToUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).UserRoleCreate(userRoleCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error assigning role:"+roleKey+" to user:"+userKey, zap.Error(err)) + return nil, err + } + return roleAssignmentRead, nil +} + +// AssignResourceRole assigns a *resource* role to a user in your context's environment, by user key, role key, tenant key and a resource instance string (e.g. "document:mydoc"). +// Usage Example: +// `roleAssignment, err := PermitClient.Api.Users.AssignRole(ctx, "user-key", "role-key", "default", "document:mydoc")` +func (u *Users) AssignResourceRole(ctx context.Context, userKey string, roleKey string, tenantKey string, resourceInstance string) (*models.RoleAssignmentRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + userRoleCreate := *models.NewUserRoleCreate(roleKey, tenantKey) + userRoleCreate.SetResourceInstance(resourceInstance) + roleAssignmentRead, httpRes, err := u.client.UsersApi.AssignRoleToUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).UserRoleCreate(userRoleCreate).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error assigning role:"+roleKey+" to user:"+userKey, zap.Error(err)) + return nil, err + } + return roleAssignmentRead, nil +} + +// UnassignResourceRole unassigns a *resource* role from a user in your context's environment, by user key, role key, tenant key and a resource instance string (e.g. "document:mydoc"). +// Usage Example: +// `err := PermitClient.Api.Users.UnassignResourceRole(ctx, "user-key", "role-key", "default", "document:mydoc")` +func (u *Users) UnassignResourceRole(ctx context.Context, userKey string, roleKey string, tenantKey string, resourceInstance string) (*models.UserRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + userRoleRemove := *models.NewUserRoleRemove(roleKey, tenantKey) + userRoleRemove.SetResourceInstance(resourceInstance) + user, httpRes, err := u.client.UsersApi.UnassignRoleFromUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).UserRoleRemove(userRoleRemove).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error unassigning role:"+roleKey+" from user:"+userKey, zap.Error(err)) + return nil, err + } + return user, nil +} + +// UnassignRole unassigns a role from a user in your context's environment, by user key, role key and tenant key. +// Usage Example: +// `err := PermitClient.Api.Users.UnassignRole(ctx, "user-key", "role-key", "default")` +func (u *Users) UnassignRole(ctx context.Context, userKey string, roleKey string, tenantKey string) (*models.UserRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + UserRoleRemove := *models.NewUserRoleRemove(roleKey, tenantKey) + user, httpRes, err := u.client.UsersApi.UnassignRoleFromUser(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment(), userKey).UserRoleRemove(UserRoleRemove).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error unassigning role:"+roleKey+" from user:"+userKey, zap.Error(err)) + return nil, err + } + return user, nil +} + +// GetAssignedRoles lists all roles assigned to a user in your context's environment, by user key, tenant key and pagination options. +// Usage Example: +// ``` +// +// `roleAssignmentList, err := PermitClient.Api.Users.GetAssignedRoles(ctx, "user-key", "default", 1, 10)` +func (u *Users) GetAssignedRoles(ctx context.Context, userKey string, tenantKey string, page int, perPage int) ([]models.RoleAssignmentRead, error) { + perPageLimit := int32(DefaultPerPageLimit) + if !isPaginationInLimit(int32(page), int32(perPage), perPageLimit) { + err := errors.NewPermitPaginationError() + u.logger.Error("error listing users - max per page: "+string(perPageLimit), zap.Error(err)) + return nil, err + } + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + roleAssignments, httpRes, err := u.client.RoleAssignmentsApi.ListRoleAssignments(ctx, u.config.Context.GetProject(), u.config.Context.GetEnvironment()). + User(userKey). + Tenant(tenantKey). + Page(int32(page)).PerPage(int32(perPage)).Execute() + err = errors.HttpErrorHandle(err, httpRes) + if err != nil { + u.logger.Error("error listing roles for user:"+userKey, zap.Error(err)) + return nil, err + } + if roleAssignments == nil || roleAssignments.RoleAssignmentRead == nil { + if roleAssignments.RoleAssignmentRead == nil { + emptyRoleAssignments := make([]models.RoleAssignmentRead, 0) + return emptyRoleAssignments, nil + } + } + return *roleAssignments.RoleAssignmentRead, nil +} + +// SyncUser syncs a user in your context's environment, by user. +// Usage Example: +// ``` +// userCreate := *models.NewUserCreate("user-key") +// userCreate.SetEmail("user-email") +// userCreate.SetFirstName("user-first-name") +// userCreate.SetLastName("user-last-name") +// user, err := PermitClient.Api.Users.SyncUser(ctx, userCreate) +// ``` +func (u *Users) SyncUser(ctx context.Context, user models.UserCreate) (*models.UserRead, error) { + err := u.lazyLoadPermitContext(ctx) + if err != nil { + u.logger.Error("", zap.Error(err)) + return nil, err + } + existUser, err := u.Get(ctx, user.GetKey()) + if err != nil { + if !strings.Contains(err.Error(), string(errors.NotFound)) { + u.logger.Error("", zap.Error(err)) + return nil, err + } + } + if existUser != nil { + u.logger.Info("User already exists, updating it...", zap.String("user", user.GetKey())) + userUpdate := models.NewUserUpdate() + if email := user.GetEmail(); email != "" { + userUpdate.SetEmail(user.GetEmail()) + } + if firstName := user.GetFirstName(); firstName != "" { + userUpdate.SetFirstName(user.GetFirstName()) + } + if lastName := user.GetLastName(); lastName != "" { + userUpdate.SetLastName(user.GetLastName()) + } + userUpdate.SetAttributes(user.GetAttributes()) + userRead, err := u.Update(ctx, user.GetKey(), *userUpdate) + if err != nil { + u.logger.Error("error updating user: "+user.GetKey(), zap.Error(err)) + return nil, err + } + return userRead, nil + } + u.logger.Info("User does not exist, creating it...", zap.String("user", user.GetKey())) + userRead, err := u.Create(ctx, user) + if err != nil { + u.logger.Error("error creating user: "+user.GetKey(), zap.Error(err)) + return nil, err + } + return userRead, err +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/api/utils.go b/vendor/github.com/permitio/permit-golang/pkg/api/utils.go new file mode 100644 index 00000000..19981b23 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/api/utils.go @@ -0,0 +1,27 @@ +package api + +const DefaultPerPageLimit = 100 + +func isPaginationInLimit(page int32, perPage int32, perPageLimit int32) bool { + return perPage <= perPageLimit && perPage > 0 && page > 0 +} + +func listToString(list []string) string { + var str string + for _, s := range list { + str += s + "," + } + return str +} + +func getSchemaFromUrl(url string) string { + if url[0:5] == "https" { + return "https" + } + return "http" +} + +func getHostFromUrl(url string) string { + schema := getSchemaFromUrl(url) + return url[len(schema)+3:] +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/config/builder.go b/vendor/github.com/permitio/permit-golang/pkg/config/builder.go new file mode 100644 index 00000000..47aec8d5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/config/builder.go @@ -0,0 +1,94 @@ +package config + +import ( + "go.uber.org/zap" + "net/http" + "time" +) + +type PermitBuilder struct { + PermitConfig +} + +func NewConfigBuilder(token string) *PermitBuilder { + factsSyncTimeout := DefaultFactsSyncTimeout + return &PermitBuilder{ + PermitConfig: PermitConfig{ + apiUrl: DefaultApiUrl, + token: token, + pdpUrl: DefaultPdpUrl, + debug: DefaultDebugMode, + Context: nil, + Logger: nil, + proxyFactsViaPDP: false, + factsSyncTimeout: &factsSyncTimeout, + httpClient: &http.Client{Timeout: DefaultTimeout}, + }, + } +} + +func (c *PermitConfig) WithProxyFactsViaPDP(proxyFactsViaPDP bool) *PermitConfig { + c.proxyFactsViaPDP = proxyFactsViaPDP + return c +} + +func (c *PermitConfig) WithFactsSyncTimeout(timeout time.Duration) *PermitConfig { + c.factsSyncTimeout = &timeout + return c +} +func (c *PermitConfig) WithHTTPClient(client *http.Client) *PermitConfig { + c.httpClient = client + return c +} + +func (c *PermitConfig) WithApiUrl(apiUrl string) *PermitConfig { + if apiUrl != "" { + c.apiUrl = apiUrl + } + + return c +} + +func (c *PermitConfig) WithPdpUrl(pdpUrl string) *PermitConfig { + if pdpUrl != "" { + c.pdpUrl = pdpUrl + } + + return c +} + +func (c *PermitConfig) WithOpaUrl(opaUrl string) *PermitConfig { + c.opaUrl = opaUrl + return c +} + +func (c *PermitConfig) WithDebug(debug bool) *PermitConfig { + c.debug = debug + return c +} + +func (c *PermitConfig) WithContext(context *PermitContext) *PermitConfig { + c.Context = context + return c +} + +func (c *PermitConfig) WithTimeout(timeout time.Duration) *PermitConfig { + c.httpClient.Timeout = timeout + return c +} + +func (c *PermitConfig) WithLogger(logger *zap.Logger) *PermitConfig { + c.Logger = logger + return c +} + +func (c *PermitConfig) Build() PermitConfig { + if c.Logger == nil { + logger, err := zap.NewProduction() + if err != nil { + panic(err) + } + c.Logger = logger + } + return *c +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/config/config.go b/vendor/github.com/permitio/permit-golang/pkg/config/config.go new file mode 100644 index 00000000..17690a72 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/config/config.go @@ -0,0 +1,101 @@ +package config + +import ( + "net/http" + "time" + + "go.uber.org/zap" +) + +// FactsSyncTimeoutPolicy defines the possible policies for facts synchronization timeout +type FactsSyncTimeoutPolicy string + +const ( + // FactsSyncTimeoutPolicyIgnore indicates to ignore timeout and continue + FactsSyncTimeoutPolicyIgnore FactsSyncTimeoutPolicy = "ignore" + // FactsSyncTimeoutPolicyFail indicates to fail the request when timeout is reached + FactsSyncTimeoutPolicyFail FactsSyncTimeoutPolicy = "fail" +) + +type PermitConfig struct { + apiUrl string + token string + pdpUrl string + opaUrl string + debug bool + Context *PermitContext + Logger *zap.Logger + httpClient *http.Client + proxyFactsViaPDP bool + factsSyncTimeout *time.Duration + factsSyncTimeoutPolicy FactsSyncTimeoutPolicy +} + +type IPermitConfig interface { + GetApiUrl() string + GetToken() string + GetPdpUrl() string + GetOpaUrl() string + GetDebug() bool + GetContext() *PermitContext + GetLogger() *zap.Logger + GetProxyFactsViaPDP() bool + GetFactsSyncTimeout() *time.Duration + GetFactsSyncTimeoutPolicy() FactsSyncTimeoutPolicy + GetHTTPClient() *http.Client +} + +func NewPermitConfig(apiUrl string, token string, pdpUrl string, debug bool, context *PermitContext, logger *zap.Logger) *PermitConfig { + return &PermitConfig{ + apiUrl: apiUrl, + token: token, + pdpUrl: pdpUrl, + debug: debug, + Context: context, + Logger: logger, + } +} + +func (c *PermitConfig) GetApiUrl() string { + return c.apiUrl +} + +func (c *PermitConfig) GetToken() string { + return c.token +} + +func (c *PermitConfig) GetPdpUrl() string { + return c.pdpUrl +} + +func (c *PermitConfig) GetOpaUrl() string { + return c.opaUrl +} + +func (c *PermitConfig) GetDebug() bool { + return c.debug +} + +func (c *PermitConfig) GetContext() *PermitContext { + return c.Context +} + +func (c *PermitConfig) GetLogger() *zap.Logger { + return c.Logger +} + +func (c *PermitConfig) GetProxyFactsViaPDP() bool { + return c.proxyFactsViaPDP +} + +func (c *PermitConfig) GetFactsSyncTimeout() *time.Duration { + return c.factsSyncTimeout +} + +func (c *PermitConfig) GetFactsSyncTimeoutPolicy() FactsSyncTimeoutPolicy { + return c.factsSyncTimeoutPolicy +} + +func (c *PermitConfig) GetHTTPClient() *http.Client { + return c.httpClient +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/config/consts.go b/vendor/github.com/permitio/permit-golang/pkg/config/consts.go new file mode 100644 index 00000000..93359fb8 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/config/consts.go @@ -0,0 +1,14 @@ +package config + +import "time" + +// Default Builder consts +const ( + DefaultApiUrl = "https://api.permit.io" + DefaultDebugMode = false + DefaultPdpUrl = "http://localhost:7766" + DefaultOpaUrl = "http://localhost:8181" + + DefaultTimeout = time.Second * 5 + DefaultFactsSyncTimeout = 10 * time.Second +) diff --git a/vendor/github.com/permitio/permit-golang/pkg/config/context.go b/vendor/github.com/permitio/permit-golang/pkg/config/context.go new file mode 100644 index 00000000..1f0a4887 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/config/context.go @@ -0,0 +1,81 @@ +package config + +import ( + "context" + PermitErrors "github.com/permitio/permit-golang/pkg/errors" + "github.com/permitio/permit-golang/pkg/openapi" + "strings" +) + +type PermitContext struct { + APIKeyLevel APIKeyLevel + ProjectId string + EnvironmentId string +} + +type PermitContextInterface interface { + SetPermitContext(project string, environment string, apiKeyLevel APIKeyLevel) + GetProject() string + GetEnvironment() string + GetContext() *PermitContext +} + +func (p *PermitContext) SetPermitContext(project string, environment string, apiKeyLevel APIKeyLevel) { + p.ProjectId = project + p.EnvironmentId = environment + p.APIKeyLevel = apiKeyLevel +} + +func (p *PermitContext) GetContext() *PermitContext { + return p +} + +func (p *PermitContext) GetEnvironment() string { + return p.EnvironmentId +} + +func (p *PermitContext) GetProject() string { + return p.ProjectId +} + +func PermitContextFactory(ctx context.Context, client *openapi.APIClient, project string, environment string, isUserInput bool) (*PermitContext, error) { + apiKeysScopeRead, httpRes, err := client.APIKeysApi.GetApiKeyScope(ctx).Execute() + err = PermitErrors.HttpErrorHandle(err, httpRes) + additionalErrorMessage := PermitErrors.EmptyErrorMessage + if err != nil { + if strings.Contains(err.Error(), string(PermitErrors.ForbiddenMessage)) { + additionalErrorMessage = PermitErrors.ForbiddenMessage + } + if strings.Contains(err.Error(), string(PermitErrors.UnauthorizedMessage)) { + additionalErrorMessage = PermitErrors.UnauthorizedMessage + } + return nil, PermitErrors.NewPermitContextError(additionalErrorMessage) + } + apiKeyLevel := GetApiKeyLevel(apiKeysScopeRead) + if isUserInput { + if apiKeyLevel == EnvironmentAPIKeyLevel { + if environment == "" || project == "" { + return nil, PermitErrors.NewPermitContextError("You initiated the Permit.io " + + "client with an Environment level API key, " + + "please set a context with the API key related environment and project") + } + } + if apiKeyLevel == ProjectAPIKeyLevel { + if project == "" { + return nil, PermitErrors.NewPermitContextError("You initiated the Permit.io " + + "client with a Project level API key, " + + "please set a context with the API key related project") + } + } + return NewPermitContext(apiKeyLevel, project, environment), nil + } + return NewPermitContext(apiKeyLevel, apiKeysScopeRead.GetProjectId(), apiKeysScopeRead.GetEnvironmentId()), nil +} + +func NewPermitContext(apiKeyLevel APIKeyLevel, project string, environment string) *PermitContext { + return &PermitContext{ + APIKeyLevel: apiKeyLevel, + ProjectId: project, + EnvironmentId: environment, + } +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/config/utils.go b/vendor/github.com/permitio/permit-golang/pkg/config/utils.go new file mode 100644 index 00000000..7e418c34 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/config/utils.go @@ -0,0 +1,24 @@ +package config + +import ( + "github.com/permitio/permit-golang/pkg/models" +) + +type APIKeyLevel int + +const ( + NoneAPIKeyLevel APIKeyLevel = iota + OrganizationAPIKeyLevel + ProjectAPIKeyLevel + EnvironmentAPIKeyLevel +) + +func GetApiKeyLevel(scope *models.APIKeyScopeRead) APIKeyLevel { + if scope.HasEnvironmentId() { + return EnvironmentAPIKeyLevel + } + if scope.HasProjectId() { + return ProjectAPIKeyLevel + } + return OrganizationAPIKeyLevel +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/all_tenants.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/all_tenants.go new file mode 100644 index 00000000..0e2fcc40 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/all_tenants.go @@ -0,0 +1,108 @@ +package enforcement + +import ( + "bytes" + "encoding/json" + "github.com/permitio/permit-golang/pkg/errors" + "go.uber.org/zap" + "io" + "net/http" +) + +type TenantDetails struct { + Key string `json:"key"` + Attributes map[string]interface{} `json:"attributes"` +} + +type AllTenantsCheckResponse struct { + CheckResponse + Tenant TenantDetails `json:"tenant"` +} + +type opaAllTenantsResponse struct { + Result *allowedTenantsResponse `json:"result"` +} + +type allowedTenantsResponse struct { + AllowedTenants *[]AllTenantsCheckResponse `json:"allowed_tenants"` +} + +func (e *PermitEnforcer) getAllTenantsCheckEndpoint() string { + return e.getEndpointByPolicyPackage(allTenantsPolicyPackage) +} + +func (e *PermitEnforcer) parseAllTenantsResponse(res *http.Response) ([]AllTenantsCheckResponse, error) { + var result []AllTenantsCheckResponse + bodyBytes, err := io.ReadAll(res.Body) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error reading Permit.AllTenantsCheck() response from PDP", zap.Error(permitError)) + return nil, permitError + } + err = errors.HttpErrorHandle(err, res) + if err != nil { + e.logger.Error(string(bodyBytes), zap.Error(err)) + return nil, err + } + if e.config.GetOpaUrl() != "" { + opaStruct := &opaAllTenantsResponse{ + Result: &allowedTenantsResponse{ + &result, + }, + } + + if err := json.Unmarshal(bodyBytes, opaStruct); err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error unmarshalling Permit.AllTenantsCheck() response from OPA", zap.Error(permitError)) + return nil, err + } + } else { + pdpStruct := &allowedTenantsResponse{&result} + if err := json.Unmarshal(bodyBytes, &pdpStruct); err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error unmarshalling Permit.AllTenantsCheck() response from PDP", zap.Error(permitError)) + return nil, permitError + } + } + + return result, nil +} + +func (e *PermitEnforcer) AllTenantsCheck(user User, action Action, resource Resource, additionalContext ...map[string]string) ([]TenantDetails, error) { + reqAuthValue := "Bearer " + e.config.GetToken() + + if additionalContext == nil { + additionalContext = make([]map[string]string, 0) + additionalContext = append(additionalContext, make(map[string]string)) + } + jsonCheckReq, err := newJsonCheckRequest(e.config.GetOpaUrl(), user, action, resource, additionalContext[0]) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error marshalling Permit.AllTenantsCheck() request", zap.Error(permitError)) + return nil, permitError + } + reqBody := bytes.NewBuffer(jsonCheckReq) + httpRequest, err := http.NewRequest(reqMethod, e.getAllTenantsCheckEndpoint(), reqBody) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error creating Permit.AllTenantsCheck() request", zap.Error(permitError)) + return nil, permitError + } + httpRequest.Header.Set(reqContentTypeKey, reqContentTypeValue) + httpRequest.Header.Set(reqAuthKey, reqAuthValue) + res, err := e.client.Do(httpRequest) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error sending Permit.AllTenantsCheck() request to PDP", zap.Error(permitError)) + return nil, permitError + } + results, err := e.parseAllTenantsResponse(res) + if err != nil { + return nil, err + } + allowResults := make([]TenantDetails, len(results)) + for result := range results { + allowResults[result] = results[result].Tenant + } + return allowResults, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/bulk_check.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/bulk_check.go new file mode 100644 index 00000000..50cbdacf --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/bulk_check.go @@ -0,0 +1,204 @@ +package enforcement + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/permitio/permit-golang/pkg/errors" + "go.uber.org/zap" + "io" + "net/http" +) + +type opaBulkResponse struct { + Result *allowBulkResponse `json:"result"` +} + +type allowBulkResponse struct { + Allow *[]CheckResponse `json:"allow"` +} + +func NewBulkCheckRequest(requests ...CheckRequest) []CheckRequest { + return requests +} + +func NewBulkCheckRequestParameterized(user []User, action []Action, resource []Resource, context []map[string]string) ([]CheckRequest, error) { + if len(user) != len(action) || len(user) != len(resource) || len(user) != len(context) { + return nil, fmt.Errorf("user, action, resource and context must have the same length") + } + requests := make([]CheckRequest, len(user)) + for i := range user { + requests[i] = CheckRequest{ + User: user[i], + Action: action[i], + Resource: resource[i], + Context: context[i], + } + } + return requests, nil +} + +func newJsonBulkCheckRequest(opaUrl string, requests ...CheckRequest) ([]byte, error) { + checkReq := NewBulkCheckRequest(requests...) + var genericCheckReq interface{} = checkReq + if opaUrl != "" { + genericCheckReq = &struct { + Input []CheckRequest `json:"input"` + }{checkReq} + } + jsonCheckReq, err := json.Marshal(genericCheckReq) + if err != nil { + return nil, err + } + return jsonCheckReq, nil +} + +func (e *PermitEnforcer) getBulkCheckEndpoint() string { + return e.getEndpointByPolicyPackage(bulkPolicyPackage) +} + +func (e *PermitEnforcer) parseBulkResponse(res *http.Response) ([]CheckResponse, error) { + var result []CheckResponse + bodyBytes, err := io.ReadAll(res.Body) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error reading Permit.BulkCheck() response from PDP", zap.Error(permitError)) + return nil, permitError + } + err = errors.HttpErrorHandle(err, res) + if err != nil { + e.logger.Error(string(bodyBytes), zap.Error(err)) + return nil, err + } + if e.config.GetOpaUrl() != "" { + opaStruct := &opaBulkResponse{ + &allowBulkResponse{ + &result, + }, + } + + if err := json.Unmarshal(bodyBytes, opaStruct); err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error unmarshalling Permit.BulkCheck() response from OPA", zap.Error(permitError)) + return nil, err + } + } else { + pdpStruct := &allowBulkResponse{&result} + if err := json.Unmarshal(bodyBytes, &pdpStruct); err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error unmarshalling Permit.BulkCheck response from PDP", zap.Error(permitError)) + return nil, permitError + } + } + + return result, nil +} + +func (e *PermitEnforcer) BulkCheck(requests ...CheckRequest) ([]bool, error) { + tenantRequestsMap := make(map[string][]CheckRequest) + requestsOrder := make(map[string]map[int]int) + + for i, request := range requests { + // Create a map of tenant key to requests for that tenant + tenantRequests, found := tenantRequestsMap[request.Resource.GetTenant()] + if !found || tenantRequests == nil { + tenantRequests = []CheckRequest{ + request, + } + } else { + tenantRequests = append(tenantRequests, request) + } + tenantRequestsMap[request.Resource.GetTenant()] = tenantRequests + // keep a mapping between the index in the tenant slice to the original requests slice + // so we can return the results in the same order as the original requests + if requestsOrder[request.Resource.GetTenant()] == nil { + requestsOrder[request.Resource.GetTenant()] = map[int]int{ + len(tenantRequests) - 1: i, + } + } else { + requestsOrder[request.Resource.GetTenant()][len(tenantRequests)-1] = i + } + } + results := make([]bool, len(requests)) + for tenant, tenantRequests := range tenantRequestsMap { + tenantResults, err := e.bulkCheck(tenantRequests...) + if err != nil { + return nil, err + } + for i := range tenantRequests { + // i represents the index in the tenant slice + // put the result in the original index in the results slice + // so we can return the results in the same order as the original requests + originalRequestIndex := requestsOrder[tenant][i] + results[originalRequestIndex] = tenantResults[i] + } + } + return results, nil +} + +func (e *PermitEnforcer) bulkCheck(requests ...CheckRequest) ([]bool, error) { + reqAuthValue := "Bearer " + e.config.GetToken() + + jsonCheckReq, err := newJsonBulkCheckRequest(e.config.GetOpaUrl(), requests...) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error marshalling Permit.BulkCheck() request", zap.Error(permitError)) + return nil, permitError + } + reqBody := bytes.NewBuffer(jsonCheckReq) + httpRequest, err := http.NewRequest(reqMethod, e.getBulkCheckEndpoint(), reqBody) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error creating Permit.BulkCheck() request", zap.Error(permitError)) + return nil, permitError + } + httpRequest.Header.Set(reqContentTypeKey, reqContentTypeValue) + httpRequest.Header.Set(reqAuthKey, reqAuthValue) + res, err := e.client.Do(httpRequest) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error sending Permit.BulkCheck() request to PDP", zap.Error(permitError)) + return nil, permitError + } + results, err := e.parseBulkResponse(res) + if err != nil { + return nil, err + } + if len(results) != len(requests) { + return nil, errors.NewPermitUnexpectedError(fmt.Errorf("unexpected number of results"), res) + } + allowResults := make([]bool, len(results)) + for result := range results { + allowResults[result] = results[result].Allow + } + return allowResults, nil +} + +func (e *PermitEnforcer) FilterObjects(user User, action Action, context map[string]string, resources ...ResourceI) ([]ResourceI, error) { + requests := make([]CheckRequest, len(resources)) + for i, resource := range resources { + permitResource := ResourceBuilder(resource.GetType()). + WithID(resource.GetID()). + WithContext(resource.GetContext()). + WithAttributes(resource.GetAttributes()). + WithTenant(resource.GetTenant()). + Build() + requests[i] = *NewCheckRequest(user, + action, + permitResource, + context, + ) + } + results, err := e.BulkCheck(requests...) + if err != nil { + return nil, err + } + filteredResources := make([]ResourceI, 0) + for i, result := range results { + if result { + filteredResources = append(filteredResources, resources[i]) + } + } + + return filteredResources, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/check.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/check.go new file mode 100644 index 00000000..b2ff31d1 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/check.go @@ -0,0 +1,129 @@ +package enforcement + +import ( + "bytes" + "encoding/json" + "github.com/permitio/permit-golang/pkg/errors" + "go.uber.org/zap" + "io" + "net/http" +) + +type Action string + +type CheckResponse struct { + Allow bool `json:"allow"` + Query map[string]interface{} `json:"query"` + Debug map[string]interface{} `json:"debug"` + Result bool `json:"result"` +} + +type CheckRequest struct { + User User `json:"user"` + Action Action `json:"action"` + Resource Resource `json:"resource"` + Context map[string]string `json:"context"` +} + +func NewCheckRequest(user User, action Action, resource Resource, context map[string]string) *CheckRequest { + return &CheckRequest{ + User: user, + Action: action, + Resource: resource, + Context: context, + } +} + +func newJsonCheckRequest(opaUrl string, user User, action Action, resource Resource, context map[string]string) ([]byte, error) { + checkReq := NewCheckRequest(user, action, resource, context) + var genericCheckReq interface{} = checkReq + if opaUrl != "" { + genericCheckReq = &struct { + Input *CheckRequest `json:"input"` + }{checkReq} + } + jsonCheckReq, err := json.Marshal(genericCheckReq) + if err != nil { + return nil, err + } + return jsonCheckReq, nil +} + +func (e *PermitEnforcer) getCheckEndpoint() string { + return e.getEndpointByPolicyPackage(mainPolicyPackage) +} + +func (e *PermitEnforcer) parseResponse(res *http.Response) (*CheckResponse, error) { + var result CheckResponse + err := errors.HttpErrorHandle(nil, res) + if err != nil { + responseBodyZap := zap.String("response_body", "") + if permitErr, ok := err.(errors.PermitError); ok { + responseBodyZap = zap.String("response_body", permitErr.ResponseBody) + } + e.logger.Error("erroneous http response from PDP for Permit.Check()", zap.Error(err), responseBodyZap) + return nil, err + } + + bodyBytes, err := io.ReadAll(res.Body) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error reading Permit.Check() response from PDP", zap.Error(permitError)) + return nil, permitError + } + + if e.config.GetOpaUrl() != "" { + opaStruct := &struct { + Result *CheckResponse `json:"result"` + }{&result} + + if err := json.Unmarshal(bodyBytes, opaStruct); err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error unmarshalling Permit.Check() response from OPA", zap.Error(permitError)) + return nil, err + } + } else { + if err := json.Unmarshal(bodyBytes, &result); err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error unmarshalling Permit.Check response from PDP", zap.Error(permitError)) + return nil, permitError + } + } + + return &result, nil +} + +func (e *PermitEnforcer) Check(user User, action Action, resource Resource, additionalContext ...map[string]string) (bool, error) { + reqAuthValue := "Bearer " + e.config.GetToken() + + if additionalContext == nil { + additionalContext = make([]map[string]string, 0) + additionalContext = append(additionalContext, make(map[string]string)) + } + jsonCheckReq, err := newJsonCheckRequest(e.config.GetOpaUrl(), user, action, resource, additionalContext[0]) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error marshalling Permit.Check() request", zap.Error(permitError)) + return false, permitError + } + reqBody := bytes.NewBuffer(jsonCheckReq) + httpRequest, err := http.NewRequest(reqMethod, e.getCheckEndpoint(), reqBody) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error creating Permit.Check() request", zap.Error(permitError)) + return false, permitError + } + httpRequest.Header.Set(reqContentTypeKey, reqContentTypeValue) + httpRequest.Header.Set(reqAuthKey, reqAuthValue) + res, err := e.client.Do(httpRequest) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error sending Permit.Check() request to PDP", zap.Error(permitError)) + return false, permitError + } + result, err := e.parseResponse(res) + if err != nil { + return false, err + } + return result.Allow, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/consts.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/consts.go new file mode 100644 index 00000000..fe9037ee --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/consts.go @@ -0,0 +1,57 @@ +package enforcement + +import "strings" + +const ( + DefaultTenant = "default" + DefaultTimeout = 30 + AllowKey = "allow" +) + +const ( + reqMethod = "POST" + reqContentTypeKey = "Content-Type" + reqContentTypeValue = "application/json" + reqAuthKey = "Authorization" +) + +type packageName string +type sidecarPath string + +const ( + mainPolicyPackage packageName = "permit.root" + bulkPolicyPackage packageName = "permit.bulk" + allTenantsPolicyPackage packageName = "permit.all_tenants" + userPermissionsPackage packageName = "permit.user_permissions" +) + +const ( + mainPolicy sidecarPath = "/allowed" + bulkPolicy sidecarPath = "/allowed/bulk" + allTenantsPolicy sidecarPath = "/allowed/all-tenants" + userPermissions sidecarPath = "/user-permissions" +) + +type checkOperationConfig struct { + sidecarPath sidecarPath + opaPath string +} + +var policyMap = map[packageName]checkOperationConfig{ + mainPolicyPackage: { + sidecarPath: mainPolicy, + opaPath: strings.Replace(string(mainPolicyPackage), ".", "/", -1), + }, + bulkPolicyPackage: { + sidecarPath: bulkPolicy, + opaPath: strings.Replace(string(bulkPolicyPackage), ".", "/", -1), + }, + allTenantsPolicyPackage: { + sidecarPath: allTenantsPolicy, + opaPath: strings.Replace(string(allTenantsPolicyPackage), ".", "/", -1), + }, + userPermissionsPackage: { + sidecarPath: userPermissions, + opaPath: strings.Replace(string(userPermissionsPackage), ".", "/", -1), + }, +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/enforcement.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/enforcement.go new file mode 100644 index 00000000..b1bfb4dc --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/enforcement.go @@ -0,0 +1,40 @@ +package enforcement + +import ( + "github.com/permitio/permit-golang/pkg/config" + "go.uber.org/zap" + "net/http" +) + +type PermitBaseEnforcer struct { + config *config.PermitConfig + logger *zap.Logger + client *http.Client +} + +type PermitEnforcer struct { + PermitBaseEnforcer +} + +func NewPermitEnforcerClient(config *config.PermitConfig) *PermitEnforcer { + client := config.GetHTTPClient() + if client == nil { + client = http.DefaultClient + } + return &PermitEnforcer{ + PermitBaseEnforcer{ + config: config, + logger: config.GetLogger(), + client: client, + }, + } +} + +func (e *PermitEnforcer) getEndpointByPolicyPackage(name packageName) string { + operationConfig := policyMap[name] + if e.config.GetOpaUrl() != "" { + return e.config.GetOpaUrl() + "/v1/data/" + operationConfig.opaPath + } else { + return e.config.GetPdpUrl() + string(operationConfig.sidecarPath) + } +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/resource.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/resource.go new file mode 100644 index 00000000..499e8454 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/resource.go @@ -0,0 +1,76 @@ +package enforcement + +type ResourceI interface { + GetID() string + GetType() string + GetTenant() string + GetAttributes() map[string]interface{} + GetContext() map[string]string +} + +type Resource struct { + Type string `json:"type,omitempty"` + ID string `json:"id,omitempty"` + Key string `json:"key,omitempty"` + Tenant string `json:"tenant,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` + Context map[string]string `json:"context,omitempty"` +} + +func (r *Resource) GetID() string { + return r.ID +} + +func (r *Resource) GetType() string { + return r.Type +} + +func (r *Resource) GetTenant() string { + return r.Tenant +} + +func (r *Resource) GetAttributes() map[string]interface{} { + return r.Attributes +} + +func (r *Resource) GetContext() map[string]string { + return r.Context +} + +func ResourceBuilder(resourceType string) *Resource { + return &Resource{ + Type: resourceType, + } +} + +func (r *Resource) WithID(ID string) *Resource { + r.ID = ID + return r +} + +func (r *Resource) WithKey(key string) *Resource { + r.Key = key + return r +} + +func (r *Resource) WithTenant(tenant string) *Resource { + r.Tenant = tenant + return r +} + +func (r *Resource) WithAttributes(attributes map[string]interface{}) *Resource { + r.Attributes = attributes + return r +} + +func (r *Resource) WithContext(context map[string]string) *Resource { + r.Context = context + return r +} + +func (r *Resource) Build() Resource { + if r.Tenant == "" { + r.Tenant = DefaultTenant + } + return *r +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/user.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/user.go new file mode 100644 index 00000000..11d5bcd0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/user.go @@ -0,0 +1,50 @@ +package enforcement + +type AssignedRole struct { + Role string + Tenant string +} + +type User struct { + Key string `json:"key,omitempty"` + FirstName string `json:"first_name,omitempty"` + LastName string `json:"last_name,omitempty"` + Email string `json:"email,omitempty"` + Roles []AssignedRole `json:"roles,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +func UserBuilder(key string) *User { + return &User{ + Key: key, + } +} + +func (u *User) WithFirstName(firstName string) *User { + u.FirstName = firstName + return u +} + +func (u *User) WithLastName(lastName string) *User { + u.LastName = lastName + return u +} + +func (u *User) WithEmail(email string) *User { + u.Email = email + return u +} + +func (u *User) WithRoles(roles []AssignedRole) *User { + u.Roles = roles + return u +} + +func (u *User) WithAttributes(attributes map[string]interface{}) *User { + u.Attributes = attributes + return u +} + +func (u *User) Build() User { + return *u +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/user_permissions.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/user_permissions.go new file mode 100644 index 00000000..1788e37c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/user_permissions.go @@ -0,0 +1,216 @@ +package enforcement + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + + "github.com/permitio/permit-golang/pkg/errors" + "go.uber.org/zap" +) + +type ResourceDetails struct { + Type string `json:"type,omitempty"` + Key string `json:"key,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +type TenantUserPermissions struct { + Tenant TenantDetails `json:"tenant"` + Resource *ResourceDetails `json:"resource,omitempty"` + Permissions []string `json:"permissions"` + Roles []string `json:"roles"` +} + +type UserPermissions map[string]TenantUserPermissions + +type userPermissionsResponse struct { + Permissions *UserPermissions `json:"permissions"` +} + +type opaUserPermissionsResponse struct { + Result *userPermissionsResponse `json:"result"` +} + +func (e *PermitEnforcer) getUserPermissionsEndpoint() string { + return e.getEndpointByPolicyPackage(userPermissionsPackage) +} + +func (e *PermitEnforcer) parseUserPermissionsResponse(res *http.Response) (UserPermissions, error) { + var result UserPermissions + bodyBytes, err := io.ReadAll(res.Body) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error reading Permit.GetUserPermissions() response from PDP", zap.Error(permitError)) + return nil, permitError + } + err = errors.HttpErrorHandle(err, res) + if err != nil { + e.logger.Error(string(bodyBytes), zap.Error(err)) + return nil, err + } + if e.config.GetOpaUrl() != "" { + opaStruct := &opaUserPermissionsResponse{ + Result: &userPermissionsResponse{ + &result, + }, + } + + if err := json.Unmarshal(bodyBytes, opaStruct); err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error unmarshalling Permit.GetUserPermissions() response from OPA", zap.Error(permitError)) + return nil, err + } + } else { + pdpStruct := &userPermissionsResponse{&result} + if err := json.Unmarshal(bodyBytes, &pdpStruct.Permissions); err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error unmarshalling Permit.GetUserPermissions() response from PDP", zap.Error(permitError)) + return nil, permitError + } + } + + return result, nil +} + +type GetUserPermissionsRequest struct { + User User `json:"user"` + Tenants []string `json:"tenants,omitempty"` + Resources []string `json:"resources,omitempty"` + ResourceTypes []string `json:"resource_types,omitempty"` + Context map[string]interface{} `json:"context,omitempty"` +} + +type UserPermissionsOption func(*GetUserPermissionsRequest) + +func WithTenants(tenants []string) UserPermissionsOption { + return func(req *GetUserPermissionsRequest) { + req.Tenants = tenants + } +} + +func WithResources(resources []string) UserPermissionsOption { + return func(req *GetUserPermissionsRequest) { + req.Resources = resources + } +} + +func WithResourceTypes(resourceTypes []string) UserPermissionsOption { + return func(req *GetUserPermissionsRequest) { + req.ResourceTypes = resourceTypes + } +} + +func WithContext(context map[string]interface{}) UserPermissionsOption { + return func(req *GetUserPermissionsRequest) { + req.Context = context + } +} + +func NewGetUserPermissionsRequest(user User, tenants []string) *GetUserPermissionsRequest { + return &GetUserPermissionsRequest{ + User: user, + Tenants: tenants, + Context: nil, + } +} + +func newJsonGetUserPermissionsRequest(opaUrl string, user User, tenants []string) ([]byte, error) { + getUserPermissionsReq := NewGetUserPermissionsRequest(user, tenants) + var genericCheckReq interface{} = getUserPermissionsReq + if opaUrl != "" { + genericCheckReq = &struct { + Input *GetUserPermissionsRequest `json:"input"` + }{getUserPermissionsReq} + } + jsonCheckReq, err := json.Marshal(genericCheckReq) + if err != nil { + return nil, err + } + return jsonCheckReq, nil +} + +func (e *PermitEnforcer) GetUserPermissions(user User, tenants ...string) (UserPermissions, error) { + reqAuthValue := "Bearer " + e.config.GetToken() + + jsonCheckReq, err := newJsonGetUserPermissionsRequest(e.config.GetOpaUrl(), user, tenants) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error marshalling Permit.GetUserPermissions() request", zap.Error(permitError)) + return nil, permitError + } + reqBody := bytes.NewBuffer(jsonCheckReq) + httpRequest, err := http.NewRequest(reqMethod, e.getUserPermissionsEndpoint(), reqBody) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error creating Permit.GetUserPermissions() request", zap.Error(permitError)) + return nil, permitError + } + httpRequest.Header.Set(reqContentTypeKey, reqContentTypeValue) + httpRequest.Header.Set(reqAuthKey, reqAuthValue) + res, err := e.client.Do(httpRequest) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error sending Permit.GetUserPermissions() request to PDP", zap.Error(permitError)) + return nil, permitError + } + result, err := e.parseUserPermissionsResponse(res) + if err != nil { + return nil, err + } + return result, nil +} + +func (e *PermitEnforcer) GetUserPermissionsWithOptions(user User, opts ...UserPermissionsOption) (UserPermissions, error) { + // Create base request with just the required user + req := &GetUserPermissionsRequest{ + User: user, + } + + // Apply all options + for _, opt := range opts { + opt(req) + } + + // Build request and send to API + reqAuthValue := "Bearer " + e.config.GetToken() + + var genericCheckReq interface{} = req + if e.config.GetOpaUrl() != "" { + genericCheckReq = &struct { + Input *GetUserPermissionsRequest `json:"input"` + }{req} + } + + jsonCheckReq, err := json.Marshal(genericCheckReq) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error marshalling Permit.GetUserPermissionWithOptions() request", zap.Error(permitError)) + return nil, permitError + } + + reqBody := bytes.NewBuffer(jsonCheckReq) + httpRequest, err := http.NewRequest(reqMethod, e.getUserPermissionsEndpoint(), reqBody) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, nil) + e.logger.Error("error creating Permit.GetUserPermissionWithOptions() request", zap.Error(permitError)) + return nil, permitError + } + + httpRequest.Header.Set(reqContentTypeKey, reqContentTypeValue) + httpRequest.Header.Set(reqAuthKey, reqAuthValue) + res, err := e.client.Do(httpRequest) + if err != nil { + permitError := errors.NewPermitUnexpectedError(err, res) + e.logger.Error("error sending Permit.GetUserPermissionWithOptions() request to PDP", zap.Error(permitError)) + return nil, permitError + } + + result, err := e.parseUserPermissionsResponse(res) + if err != nil { + return nil, err + } + + return result, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/enforcement/utils.go b/vendor/github.com/permitio/permit-golang/pkg/enforcement/utils.go new file mode 100644 index 00000000..dc790747 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/enforcement/utils.go @@ -0,0 +1,16 @@ +package enforcement + +import "encoding/json" + +func MapToJson(m map[string]interface{}) string { + json, _ := json.Marshal(m) + return string(json) +} + +func mapToStringMap(m map[string]interface{}) map[string]string { + result := make(map[string]string) + for k, v := range m { + result[k] = v.(string) + } + return result +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/errors/consts.go b/vendor/github.com/permitio/permit-golang/pkg/errors/consts.go new file mode 100644 index 00000000..89fbdc59 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/errors/consts.go @@ -0,0 +1,51 @@ +package errors + +type ErrorCode string + +const ( + UnexpectedError ErrorCode = "UnexpectedError" + NotFound ErrorCode = "NotFound" + Conflict ErrorCode = "Conflict" + PaginationError ErrorCode = "PaginationError" + TeapotError ErrorCode = "TeapotError" + ContextError ErrorCode = "ContextError" + DuplicateEntity ErrorCode = "DuplicateEntity" + ConnectionError ErrorCode = "ConnectionError" + UnprocessableEntityError ErrorCode = "UnprocessableEntityError" + EmptyDecisionLogs ErrorCode = "EmptyDecisionLogs" + MissingRequestAttribute ErrorCode = "MissingRequestAttribute" + ForbiddenAccess ErrorCode = "ForbiddenAccess" + Unauthorized ErrorCode = "Unauthorized" + InvalidPermissionFormat ErrorCode = "InvalidPermissionFormat" + MissingPermissions ErrorCode = "MissingPermissions" + UnsupportedAttributeType ErrorCode = "UnsupportedAttributeType" + MissingResourceAttribute ErrorCode = "MissingResourceAttribute" + InvalidPolicyRepoStatus ErrorCode = "InvalidPolicyRepoStatus" + MismatchAttributesTypes ErrorCode = "MismatchAttributesTypes" +) + +type ErrorType string + +const ( + GENERAL_ERROR ErrorType = "general_error" + API_ERROR ErrorType = "api_error" + CACHE_ERROR ErrorType = "cache_error" + INVALID_REQUEST_ERROR ErrorType = "invalid_request_error" +) + +type ErrorMessage string + +const ( + EmptyErrorMessage ErrorMessage = "" + PaginationMessage ErrorMessage = "The pagination page and size per page are invalid" + ConflictMessage ErrorMessage = "The resource already exists" + NotFoundMessage ErrorMessage = "The resource was not found" + UnexpectedErrorMessage ErrorMessage = "An unexpected error happened." + ForbiddenMessage ErrorMessage = "The access for this object is forbidden using the provided API key" + ContextMessage ErrorMessage = "The context is missing or invalid" + ContextUnexpectedMessage ErrorMessage = "The context is missing or invalid" + UnauthorizedMessage ErrorMessage = "The access for this object is not authorized using the provided API key, make sure you have the right permissions with the right API key" + DuplicateEntityMessage ErrorMessage = "The entity already exists" + ConnectionErrorMessage ErrorMessage = "The connection to the api failed" + UnprocessableEntityMessage ErrorMessage = "The entity send with the request is not valid" +) diff --git a/vendor/github.com/permitio/permit-golang/pkg/errors/errors.go b/vendor/github.com/permitio/permit-golang/pkg/errors/errors.go new file mode 100644 index 00000000..980db487 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/errors/errors.go @@ -0,0 +1,97 @@ +package errors + +import ( + e "errors" + "fmt" + "net/http" + "strings" +) + +type PermitError struct { + error + StatusCode int + ResponseBody string + ErrorCode ErrorCode + ErrorType ErrorType +} + +func NewPermitUnexpectedError(err error, response *http.Response) PermitError { + if err == nil { + return NewPermitError(UnexpectedErrorMessage, UnexpectedError, GENERAL_ERROR, response) + } + return NewPermitError(ErrorMessage(err.Error()), UnexpectedError, GENERAL_ERROR, response) +} + +func NewPermitError(errorMessage ErrorMessage, errorCode ErrorCode, errorType ErrorType, response *http.Response) PermitError { + permitError := e.New(fmt.Sprintf("ErrorCode: %s, ErrorType: %s, Message: %s", errorCode, errorType, errorMessage)) + + if response == nil { + return PermitError{ + error: permitError, + ErrorCode: errorCode, + ErrorType: errorType, + } + } else { + return PermitError{ + StatusCode: response.StatusCode, + ResponseBody: getJsonFromHttpResponse(response), + error: permitError, + ErrorCode: errorCode, + ErrorType: errorType, + } + } +} + +func NewPermitNotFoundError(err error, response *http.Response) PermitError { + if err == nil { + return NewPermitError(NotFoundMessage, NotFound, API_ERROR, response) + } + + return NewPermitError(ErrorMessage(err.Error()), NotFound, API_ERROR, response) +} + +func NewPermitConflictError(response *http.Response) PermitError { + return NewPermitError(ConflictMessage, Conflict, API_ERROR, response) +} + +func NewPermitPaginationError() PermitError { + return NewPermitError(PaginationMessage, PaginationError, API_ERROR, nil) +} + +func NewPermitUnprocessableEntityError(err error, response *http.Response) PermitError { + if err == nil { + return NewPermitError(UnprocessableEntityMessage, UnprocessableEntityError, API_ERROR, response) + } + errorMessage := ErrorMessage(err.Error()) + if strings.Contains(err.Error(), "not a valid email address") { + errorMessage = "Email is not valid" + } + return NewPermitError(errorMessage, UnprocessableEntityError, API_ERROR, response) +} + +func NewPermitForbiddenError(response *http.Response) PermitError { + return NewPermitError(ForbiddenMessage, ForbiddenAccess, API_ERROR, response) +} + +func NewPermitUnauthorizedError(response *http.Response) PermitError { + return NewPermitError(UnauthorizedMessage, Unauthorized, API_ERROR, response) +} + +func NewPermitContextError(additionalMessage ErrorMessage) PermitError { + return NewPermitError(ContextMessage+" - "+additionalMessage, ContextError, GENERAL_ERROR, nil) +} + +func NewPermitDuplicateEntityError(err error, response *http.Response) PermitError { + if err == nil { + return NewPermitError(DuplicateEntityMessage, DuplicateEntity, API_ERROR, response) + } + return NewPermitError(ErrorMessage(err.Error()), DuplicateEntity, API_ERROR, response) +} + +func NewPermitConnectionError(err error) PermitError { + if err == nil { + return NewPermitError(ConnectionErrorMessage, ConnectionError, GENERAL_ERROR, nil) + } + + return NewPermitError(ErrorMessage(err.Error()), ConnectionError, GENERAL_ERROR, nil) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/errors/handlers.go b/vendor/github.com/permitio/permit-golang/pkg/errors/handlers.go new file mode 100644 index 00000000..8561ef51 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/errors/handlers.go @@ -0,0 +1,36 @@ +package errors + +import ( + "net/http" +) + +func HttpErrorHandle(err error, response *http.Response) error { + if response == nil { + return err + } + + if response.StatusCode == 401 { + return NewPermitUnauthorizedError(response) + } + if response.StatusCode == 403 { + return NewPermitForbiddenError(response) + } + if response.StatusCode == 404 { + err = NewPermitNotFoundError(err, response) + return err + } + if response.StatusCode == 409 { + err = NewPermitConflictError(response) + return err + } + if response.StatusCode == 422 { + return NewPermitUnprocessableEntityError(err, response) + } + if response.StatusCode >= 500 { + return NewPermitUnexpectedError(err, response) + } + if err != nil { + return NewPermitUnexpectedError(err, response) + } + return nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/errors/utils.go b/vendor/github.com/permitio/permit-golang/pkg/errors/utils.go new file mode 100644 index 00000000..286813fe --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/errors/utils.go @@ -0,0 +1,16 @@ +package errors + +import ( + "io" + "net/http" +) + +func getJsonFromHttpResponse(httpResponse *http.Response) string { + body, err := io.ReadAll(httpResponse.Body) + + if err != nil { + return "" + } + + return string(body) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/client.go b/vendor/github.com/permitio/permit-golang/pkg/models/client.go new file mode 100644 index 00000000..9a945714 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/client.go @@ -0,0 +1,13 @@ +package models + +import ( + "bytes" + "encoding/json" +) + +// A wrapper for strict JSON decoding +func newStrictDecoder(data []byte) *json.Decoder { + dec := json.NewDecoder(bytes.NewBuffer(data)) + dec.DisallowUnknownFields() + return dec +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_editable.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_editable.go new file mode 100644 index 00000000..fdc2e463 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_editable.go @@ -0,0 +1,198 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ActionBlockEditable type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ActionBlockEditable{} + +// ActionBlockEditable struct for ActionBlockEditable +type ActionBlockEditable struct { + // a more descriptive name for the action + Name *string `json:"name,omitempty"` + // optional description string explaining what this action represents in your system + Description *string `json:"description,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewActionBlockEditable instantiates a new ActionBlockEditable object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewActionBlockEditable() *ActionBlockEditable { + this := ActionBlockEditable{} + return &this +} + +// NewActionBlockEditableWithDefaults instantiates a new ActionBlockEditable object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewActionBlockEditableWithDefaults() *ActionBlockEditable { + this := ActionBlockEditable{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ActionBlockEditable) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockEditable) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ActionBlockEditable) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ActionBlockEditable) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ActionBlockEditable) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockEditable) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ActionBlockEditable) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ActionBlockEditable) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ActionBlockEditable) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockEditable) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ActionBlockEditable) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ActionBlockEditable) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ActionBlockEditable) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ActionBlockEditable) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableActionBlockEditable struct { + value *ActionBlockEditable + isSet bool +} + +func (v NullableActionBlockEditable) Get() *ActionBlockEditable { + return v.value +} + +func (v *NullableActionBlockEditable) Set(val *ActionBlockEditable) { + v.value = val + v.isSet = true +} + +func (v NullableActionBlockEditable) IsSet() bool { + return v.isSet +} + +func (v *NullableActionBlockEditable) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableActionBlockEditable(val *ActionBlockEditable) *NullableActionBlockEditable { + return &NullableActionBlockEditable{value: val, isSet: true} +} + +func (v NullableActionBlockEditable) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableActionBlockEditable) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_read.go new file mode 100644 index 00000000..b8b06cc8 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_action_block_read.go @@ -0,0 +1,263 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ActionBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ActionBlockRead{} + +// ActionBlockRead struct for ActionBlockRead +type ActionBlockRead struct { + // a more descriptive name for the action + Name *string `json:"name,omitempty"` + // optional description string explaining what this action represents in your system + Description *string `json:"description,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` + // Unique id of the action + Id string `json:"id"` + // action key + Key *string `json:"key,omitempty"` +} + +// NewActionBlockRead instantiates a new ActionBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewActionBlockRead(id string) *ActionBlockRead { + this := ActionBlockRead{} + this.Id = id + return &this +} + +// NewActionBlockReadWithDefaults instantiates a new ActionBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewActionBlockReadWithDefaults() *ActionBlockRead { + this := ActionBlockRead{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ActionBlockRead) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockRead) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ActionBlockRead) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ActionBlockRead) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ActionBlockRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ActionBlockRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ActionBlockRead) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ActionBlockRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ActionBlockRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ActionBlockRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +// GetId returns the Id field value +func (o *ActionBlockRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ActionBlockRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ActionBlockRead) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value if set, zero value otherwise. +func (o *ActionBlockRead) GetKey() string { + if o == nil || IsNil(o.Key) { + var ret string + return ret + } + return *o.Key +} + +// GetKeyOk returns a tuple with the Key field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ActionBlockRead) GetKeyOk() (*string, bool) { + if o == nil || IsNil(o.Key) { + return nil, false + } + return o.Key, true +} + +// HasKey returns a boolean if a field has been set. +func (o *ActionBlockRead) HasKey() bool { + if o != nil && !IsNil(o.Key) { + return true + } + + return false +} + +// SetKey gets a reference to the given string and assigns it to the Key field. +func (o *ActionBlockRead) SetKey(v string) { + o.Key = &v +} + +func (o ActionBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ActionBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + toSerialize["id"] = o.Id + if !IsNil(o.Key) { + toSerialize["key"] = o.Key + } + return toSerialize, nil +} + +type NullableActionBlockRead struct { + value *ActionBlockRead + isSet bool +} + +func (v NullableActionBlockRead) Get() *ActionBlockRead { + return v.value +} + +func (v *NullableActionBlockRead) Set(val *ActionBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableActionBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableActionBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableActionBlockRead(val *ActionBlockRead) *NullableActionBlockRead { + return &NullableActionBlockRead{value: val, isSet: true} +} + +func (v NullableActionBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableActionBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_actor.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_actor.go new file mode 100644 index 00000000..6dfa8ce9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_actor.go @@ -0,0 +1,175 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// Actor - struct for Actor +type Actor struct { + AuthnMeAPIKeyRead *AuthnMeAPIKeyRead + AuthnMeMemberRead *AuthnMeMemberRead + AuthnMeUserRead *AuthnMeUserRead +} + +// AuthnMeAPIKeyReadAsActor is a convenience function that returns AuthnMeAPIKeyRead wrapped in Actor +func AuthnMeAPIKeyReadAsActor(v *AuthnMeAPIKeyRead) Actor { + return Actor{ + AuthnMeAPIKeyRead: v, + } +} + +// AuthnMeMemberReadAsActor is a convenience function that returns AuthnMeMemberRead wrapped in Actor +func AuthnMeMemberReadAsActor(v *AuthnMeMemberRead) Actor { + return Actor{ + AuthnMeMemberRead: v, + } +} + +// AuthnMeUserReadAsActor is a convenience function that returns AuthnMeUserRead wrapped in Actor +func AuthnMeUserReadAsActor(v *AuthnMeUserRead) Actor { + return Actor{ + AuthnMeUserRead: v, + } +} + +// Unmarshal JSON data into one of the pointers in the struct +func (dst *Actor) UnmarshalJSON(data []byte) error { + var err error + match := 0 + // try to unmarshal data into AuthnMeAPIKeyRead + err = newStrictDecoder(data).Decode(&dst.AuthnMeAPIKeyRead) + if err == nil { + jsonAuthnMeAPIKeyRead, _ := json.Marshal(dst.AuthnMeAPIKeyRead) + if string(jsonAuthnMeAPIKeyRead) == "{}" { // empty struct + dst.AuthnMeAPIKeyRead = nil + } else { + match++ + } + } else { + dst.AuthnMeAPIKeyRead = nil + } + + // try to unmarshal data into AuthnMeMemberRead + err = newStrictDecoder(data).Decode(&dst.AuthnMeMemberRead) + if err == nil { + jsonAuthnMeMemberRead, _ := json.Marshal(dst.AuthnMeMemberRead) + if string(jsonAuthnMeMemberRead) == "{}" { // empty struct + dst.AuthnMeMemberRead = nil + } else { + match++ + } + } else { + dst.AuthnMeMemberRead = nil + } + + // try to unmarshal data into AuthnMeUserRead + err = newStrictDecoder(data).Decode(&dst.AuthnMeUserRead) + if err == nil { + jsonAuthnMeUserRead, _ := json.Marshal(dst.AuthnMeUserRead) + if string(jsonAuthnMeUserRead) == "{}" { // empty struct + dst.AuthnMeUserRead = nil + } else { + match++ + } + } else { + dst.AuthnMeUserRead = nil + } + + if match > 1 { // more than 1 match + // reset to nil + dst.AuthnMeAPIKeyRead = nil + dst.AuthnMeMemberRead = nil + dst.AuthnMeUserRead = nil + + return fmt.Errorf("data matches more than one schema in oneOf(Actor)") + } else if match == 1 { + return nil // exactly one match + } else { // no match + return fmt.Errorf("data failed to match schemas in oneOf(Actor)") + } +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src Actor) MarshalJSON() ([]byte, error) { + if src.AuthnMeAPIKeyRead != nil { + return json.Marshal(&src.AuthnMeAPIKeyRead) + } + + if src.AuthnMeMemberRead != nil { + return json.Marshal(&src.AuthnMeMemberRead) + } + + if src.AuthnMeUserRead != nil { + return json.Marshal(&src.AuthnMeUserRead) + } + + return nil, nil // no data in oneOf schemas +} + +// Get the actual instance +func (obj *Actor) GetActualInstance() interface{} { + if obj == nil { + return nil + } + if obj.AuthnMeAPIKeyRead != nil { + return obj.AuthnMeAPIKeyRead + } + + if obj.AuthnMeMemberRead != nil { + return obj.AuthnMeMemberRead + } + + if obj.AuthnMeUserRead != nil { + return obj.AuthnMeUserRead + } + + // all schemas are nil + return nil +} + +type NullableActor struct { + value *Actor + isSet bool +} + +func (v NullableActor) Get() *Actor { + return v.value +} + +func (v *NullableActor) Set(val *Actor) { + v.value = val + v.isSet = true +} + +func (v NullableActor) IsSet() bool { + return v.isSet +} + +func (v *NullableActor) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableActor(val *Actor) *NullableActor { + return &NullableActor{value: val, isSet: true} +} + +func (v NullableActor) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableActor) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_add_role_permissions.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_add_role_permissions.go new file mode 100644 index 00000000..4385caf0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_add_role_permissions.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AddRolePermissions struct for AddRolePermissions +type AddRolePermissions struct { + // List of permissions to assign to the role. If a permission is already granted to the role it is skipped. Each permission can be either a resource action id, or `{resource_key}:{action_key}`, i.e: the \"permission name\". + Permissions []string `json:"permissions"` +} + +// NewAddRolePermissions instantiates a new AddRolePermissions object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAddRolePermissions(permissions []string) *AddRolePermissions { + this := AddRolePermissions{} + this.Permissions = permissions + return &this +} + +// NewAddRolePermissionsWithDefaults instantiates a new AddRolePermissions object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAddRolePermissionsWithDefaults() *AddRolePermissions { + this := AddRolePermissions{} + return &this +} + +// GetPermissions returns the Permissions field value +func (o *AddRolePermissions) GetPermissions() []string { + if o == nil { + var ret []string + return ret + } + + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value +// and a boolean to check if the value has been set. +func (o *AddRolePermissions) GetPermissionsOk() ([]string, bool) { + if o == nil { + return nil, false + } + return o.Permissions, true +} + +// SetPermissions sets field value +func (o *AddRolePermissions) SetPermissions(v []string) { + o.Permissions = v +} + +func (o AddRolePermissions) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["permissions"] = o.Permissions + } + return json.Marshal(toSerialize) +} + +type NullableAddRolePermissions struct { + value *AddRolePermissions + isSet bool +} + +func (v NullableAddRolePermissions) Get() *AddRolePermissions { + return v.value +} + +func (v *NullableAddRolePermissions) Set(val *AddRolePermissions) { + v.value = val + v.isSet = true +} + +func (v NullableAddRolePermissions) IsSet() bool { + return v.isSet +} + +func (v *NullableAddRolePermissions) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAddRolePermissions(val *AddRolePermissions) *NullableAddRolePermissions { + return &NullableAddRolePermissions{value: val, isSet: true} +} + +func (v NullableAddRolePermissions) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAddRolePermissions) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_create.go new file mode 100644 index 00000000..f0e8dc27 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_create.go @@ -0,0 +1,298 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// APIKeyCreate struct for APIKeyCreate +type APIKeyCreate struct { + OrganizationId string `json:"organization_id"` + ProjectId *string `json:"project_id,omitempty"` + EnvironmentId *string `json:"environment_id,omitempty"` + ObjectType *MemberAccessObj `json:"object_type,omitempty"` + AccessLevel *MemberAccessLevel `json:"access_level,omitempty"` + OwnerType *APIKeyOwnerType `json:"owner_type,omitempty"` +} + +// NewAPIKeyCreate instantiates a new APIKeyCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAPIKeyCreate(organizationId string) *APIKeyCreate { + this := APIKeyCreate{} + this.OrganizationId = organizationId + var objectType MemberAccessObj = ENV + this.ObjectType = &objectType + var accessLevel MemberAccessLevel = ADMIN + this.AccessLevel = &accessLevel + var ownerType APIKeyOwnerType = MEMBER + this.OwnerType = &ownerType + return &this +} + +// NewAPIKeyCreateWithDefaults instantiates a new APIKeyCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAPIKeyCreateWithDefaults() *APIKeyCreate { + this := APIKeyCreate{} + var objectType MemberAccessObj = ENV + this.ObjectType = &objectType + var accessLevel MemberAccessLevel = ADMIN + this.AccessLevel = &accessLevel + var ownerType APIKeyOwnerType = MEMBER + this.OwnerType = &ownerType + return &this +} + +// GetOrganizationId returns the OrganizationId field value +func (o *APIKeyCreate) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *APIKeyCreate) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *APIKeyCreate) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value if set, zero value otherwise. +func (o *APIKeyCreate) GetProjectId() string { + if o == nil || IsNil(o.ProjectId) { + var ret string + return ret + } + return *o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyCreate) GetProjectIdOk() (*string, bool) { + if o == nil || IsNil(o.ProjectId) { + return nil, false + } + return o.ProjectId, true +} + +// HasProjectId returns a boolean if a field has been set. +func (o *APIKeyCreate) HasProjectId() bool { + if o != nil && !IsNil(o.ProjectId) { + return true + } + + return false +} + +// SetProjectId gets a reference to the given string and assigns it to the ProjectId field. +func (o *APIKeyCreate) SetProjectId(v string) { + o.ProjectId = &v +} + +// GetEnvironmentId returns the EnvironmentId field value if set, zero value otherwise. +func (o *APIKeyCreate) GetEnvironmentId() string { + if o == nil || IsNil(o.EnvironmentId) { + var ret string + return ret + } + return *o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyCreate) GetEnvironmentIdOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentId) { + return nil, false + } + return o.EnvironmentId, true +} + +// HasEnvironmentId returns a boolean if a field has been set. +func (o *APIKeyCreate) HasEnvironmentId() bool { + if o != nil && !IsNil(o.EnvironmentId) { + return true + } + + return false +} + +// SetEnvironmentId gets a reference to the given string and assigns it to the EnvironmentId field. +func (o *APIKeyCreate) SetEnvironmentId(v string) { + o.EnvironmentId = &v +} + +// GetObjectType returns the ObjectType field value if set, zero value otherwise. +func (o *APIKeyCreate) GetObjectType() MemberAccessObj { + if o == nil || IsNil(o.ObjectType) { + var ret MemberAccessObj + return ret + } + return *o.ObjectType +} + +// GetObjectTypeOk returns a tuple with the ObjectType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyCreate) GetObjectTypeOk() (*MemberAccessObj, bool) { + if o == nil || IsNil(o.ObjectType) { + return nil, false + } + return o.ObjectType, true +} + +// HasObjectType returns a boolean if a field has been set. +func (o *APIKeyCreate) HasObjectType() bool { + if o != nil && !IsNil(o.ObjectType) { + return true + } + + return false +} + +// SetObjectType gets a reference to the given MemberAccessObj and assigns it to the ObjectType field. +func (o *APIKeyCreate) SetObjectType(v MemberAccessObj) { + o.ObjectType = &v +} + +// GetAccessLevel returns the AccessLevel field value if set, zero value otherwise. +func (o *APIKeyCreate) GetAccessLevel() MemberAccessLevel { + if o == nil || IsNil(o.AccessLevel) { + var ret MemberAccessLevel + return ret + } + return *o.AccessLevel +} + +// GetAccessLevelOk returns a tuple with the AccessLevel field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyCreate) GetAccessLevelOk() (*MemberAccessLevel, bool) { + if o == nil || IsNil(o.AccessLevel) { + return nil, false + } + return o.AccessLevel, true +} + +// HasAccessLevel returns a boolean if a field has been set. +func (o *APIKeyCreate) HasAccessLevel() bool { + if o != nil && !IsNil(o.AccessLevel) { + return true + } + + return false +} + +// SetAccessLevel gets a reference to the given MemberAccessLevel and assigns it to the AccessLevel field. +func (o *APIKeyCreate) SetAccessLevel(v MemberAccessLevel) { + o.AccessLevel = &v +} + +// GetOwnerType returns the OwnerType field value if set, zero value otherwise. +func (o *APIKeyCreate) GetOwnerType() APIKeyOwnerType { + if o == nil || IsNil(o.OwnerType) { + var ret APIKeyOwnerType + return ret + } + return *o.OwnerType +} + +// GetOwnerTypeOk returns a tuple with the OwnerType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyCreate) GetOwnerTypeOk() (*APIKeyOwnerType, bool) { + if o == nil || IsNil(o.OwnerType) { + return nil, false + } + return o.OwnerType, true +} + +// HasOwnerType returns a boolean if a field has been set. +func (o *APIKeyCreate) HasOwnerType() bool { + if o != nil && !IsNil(o.OwnerType) { + return true + } + + return false +} + +// SetOwnerType gets a reference to the given APIKeyOwnerType and assigns it to the OwnerType field. +func (o *APIKeyCreate) SetOwnerType(v APIKeyOwnerType) { + o.OwnerType = &v +} + +func (o APIKeyCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if !IsNil(o.ProjectId) { + toSerialize["project_id"] = o.ProjectId + } + if !IsNil(o.EnvironmentId) { + toSerialize["environment_id"] = o.EnvironmentId + } + if !IsNil(o.ObjectType) { + toSerialize["object_type"] = o.ObjectType + } + if !IsNil(o.AccessLevel) { + toSerialize["access_level"] = o.AccessLevel + } + if !IsNil(o.OwnerType) { + toSerialize["owner_type"] = o.OwnerType + } + return json.Marshal(toSerialize) +} + +type NullableAPIKeyCreate struct { + value *APIKeyCreate + isSet bool +} + +func (v NullableAPIKeyCreate) Get() *APIKeyCreate { + return v.value +} + +func (v *NullableAPIKeyCreate) Set(val *APIKeyCreate) { + v.value = val + v.isSet = true +} + +func (v NullableAPIKeyCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableAPIKeyCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAPIKeyCreate(val *APIKeyCreate) *NullableAPIKeyCreate { + return &NullableAPIKeyCreate{value: val, isSet: true} +} + +func (v NullableAPIKeyCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAPIKeyCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_owner_type.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_owner_type.go new file mode 100644 index 00000000..5dc0960d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_owner_type.go @@ -0,0 +1,112 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// APIKeyOwnerType An enumeration. +type APIKeyOwnerType string + +// List of APIKeyOwnerType +const ( + PDP_CONFIG APIKeyOwnerType = "pdp_config" + MEMBER APIKeyOwnerType = "member" + ELEMENTS APIKeyOwnerType = "elements" +) + +// All allowed values of APIKeyOwnerType enum +var AllowedAPIKeyOwnerTypeEnumValues = []APIKeyOwnerType{ + "pdp_config", + "member", + "elements", +} + +func (v *APIKeyOwnerType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := APIKeyOwnerType(value) + for _, existing := range AllowedAPIKeyOwnerTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid APIKeyOwnerType", value) +} + +// NewAPIKeyOwnerTypeFromValue returns a pointer to a valid APIKeyOwnerType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewAPIKeyOwnerTypeFromValue(v string) (*APIKeyOwnerType, error) { + ev := APIKeyOwnerType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for APIKeyOwnerType: valid values are %v", v, AllowedAPIKeyOwnerTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v APIKeyOwnerType) IsValid() bool { + for _, existing := range AllowedAPIKeyOwnerTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to APIKeyOwnerType value +func (v APIKeyOwnerType) Ptr() *APIKeyOwnerType { + return &v +} + +type NullableAPIKeyOwnerType struct { + value *APIKeyOwnerType + isSet bool +} + +func (v NullableAPIKeyOwnerType) Get() *APIKeyOwnerType { + return v.value +} + +func (v *NullableAPIKeyOwnerType) Set(val *APIKeyOwnerType) { + v.value = val + v.isSet = true +} + +func (v NullableAPIKeyOwnerType) IsSet() bool { + return v.isSet +} + +func (v *NullableAPIKeyOwnerType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAPIKeyOwnerType(val *APIKeyOwnerType) *NullableAPIKeyOwnerType { + return &NullableAPIKeyOwnerType{value: val, isSet: true} +} + +func (v NullableAPIKeyOwnerType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAPIKeyOwnerType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_read.go new file mode 100644 index 00000000..5495076a --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_read.go @@ -0,0 +1,447 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// APIKeyRead struct for APIKeyRead +type APIKeyRead struct { + OrganizationId string `json:"organization_id"` + ProjectId *string `json:"project_id,omitempty"` + EnvironmentId *string `json:"environment_id,omitempty"` + ObjectType *MemberAccessObj `json:"object_type,omitempty"` + AccessLevel *MemberAccessLevel `json:"access_level,omitempty"` + OwnerType APIKeyOwnerType `json:"owner_type"` + Id string `json:"id"` + Secret *string `json:"secret,omitempty"` + CreatedAt time.Time `json:"created_at"` + CreatedByMember OrgMemberRead `json:"created_by_member"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` +} + +// NewAPIKeyRead instantiates a new APIKeyRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAPIKeyRead(organizationId string, ownerType APIKeyOwnerType, id string, createdAt time.Time, createdByMember OrgMemberRead) *APIKeyRead { + this := APIKeyRead{} + this.OrganizationId = organizationId + var objectType MemberAccessObj = ENV + this.ObjectType = &objectType + var accessLevel MemberAccessLevel = ADMIN + this.AccessLevel = &accessLevel + this.OwnerType = ownerType + this.Id = id + this.CreatedAt = createdAt + this.CreatedByMember = createdByMember + return &this +} + +// NewAPIKeyReadWithDefaults instantiates a new APIKeyRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAPIKeyReadWithDefaults() *APIKeyRead { + this := APIKeyRead{} + var objectType MemberAccessObj = ENV + this.ObjectType = &objectType + var accessLevel MemberAccessLevel = ADMIN + this.AccessLevel = &accessLevel + return &this +} + +// GetOrganizationId returns the OrganizationId field value +func (o *APIKeyRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *APIKeyRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value if set, zero value otherwise. +func (o *APIKeyRead) GetProjectId() string { + if o == nil || IsNil(o.ProjectId) { + var ret string + return ret + } + return *o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetProjectIdOk() (*string, bool) { + if o == nil || IsNil(o.ProjectId) { + return nil, false + } + return o.ProjectId, true +} + +// HasProjectId returns a boolean if a field has been set. +func (o *APIKeyRead) HasProjectId() bool { + if o != nil && !IsNil(o.ProjectId) { + return true + } + + return false +} + +// SetProjectId gets a reference to the given string and assigns it to the ProjectId field. +func (o *APIKeyRead) SetProjectId(v string) { + o.ProjectId = &v +} + +// GetEnvironmentId returns the EnvironmentId field value if set, zero value otherwise. +func (o *APIKeyRead) GetEnvironmentId() string { + if o == nil || IsNil(o.EnvironmentId) { + var ret string + return ret + } + return *o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentId) { + return nil, false + } + return o.EnvironmentId, true +} + +// HasEnvironmentId returns a boolean if a field has been set. +func (o *APIKeyRead) HasEnvironmentId() bool { + if o != nil && !IsNil(o.EnvironmentId) { + return true + } + + return false +} + +// SetEnvironmentId gets a reference to the given string and assigns it to the EnvironmentId field. +func (o *APIKeyRead) SetEnvironmentId(v string) { + o.EnvironmentId = &v +} + +// GetObjectType returns the ObjectType field value if set, zero value otherwise. +func (o *APIKeyRead) GetObjectType() MemberAccessObj { + if o == nil || IsNil(o.ObjectType) { + var ret MemberAccessObj + return ret + } + return *o.ObjectType +} + +// GetObjectTypeOk returns a tuple with the ObjectType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetObjectTypeOk() (*MemberAccessObj, bool) { + if o == nil || IsNil(o.ObjectType) { + return nil, false + } + return o.ObjectType, true +} + +// HasObjectType returns a boolean if a field has been set. +func (o *APIKeyRead) HasObjectType() bool { + if o != nil && !IsNil(o.ObjectType) { + return true + } + + return false +} + +// SetObjectType gets a reference to the given MemberAccessObj and assigns it to the ObjectType field. +func (o *APIKeyRead) SetObjectType(v MemberAccessObj) { + o.ObjectType = &v +} + +// GetAccessLevel returns the AccessLevel field value if set, zero value otherwise. +func (o *APIKeyRead) GetAccessLevel() MemberAccessLevel { + if o == nil || IsNil(o.AccessLevel) { + var ret MemberAccessLevel + return ret + } + return *o.AccessLevel +} + +// GetAccessLevelOk returns a tuple with the AccessLevel field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetAccessLevelOk() (*MemberAccessLevel, bool) { + if o == nil || IsNil(o.AccessLevel) { + return nil, false + } + return o.AccessLevel, true +} + +// HasAccessLevel returns a boolean if a field has been set. +func (o *APIKeyRead) HasAccessLevel() bool { + if o != nil && !IsNil(o.AccessLevel) { + return true + } + + return false +} + +// SetAccessLevel gets a reference to the given MemberAccessLevel and assigns it to the AccessLevel field. +func (o *APIKeyRead) SetAccessLevel(v MemberAccessLevel) { + o.AccessLevel = &v +} + +// GetOwnerType returns the OwnerType field value +func (o *APIKeyRead) GetOwnerType() APIKeyOwnerType { + if o == nil { + var ret APIKeyOwnerType + return ret + } + + return o.OwnerType +} + +// GetOwnerTypeOk returns a tuple with the OwnerType field value +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetOwnerTypeOk() (*APIKeyOwnerType, bool) { + if o == nil { + return nil, false + } + return &o.OwnerType, true +} + +// SetOwnerType sets field value +func (o *APIKeyRead) SetOwnerType(v APIKeyOwnerType) { + o.OwnerType = v +} + +// GetId returns the Id field value +func (o *APIKeyRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *APIKeyRead) SetId(v string) { + o.Id = v +} + +// GetSecret returns the Secret field value if set, zero value otherwise. +func (o *APIKeyRead) GetSecret() string { + if o == nil || IsNil(o.Secret) { + var ret string + return ret + } + return *o.Secret +} + +// GetSecretOk returns a tuple with the Secret field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetSecretOk() (*string, bool) { + if o == nil || IsNil(o.Secret) { + return nil, false + } + return o.Secret, true +} + +// HasSecret returns a boolean if a field has been set. +func (o *APIKeyRead) HasSecret() bool { + if o != nil && !IsNil(o.Secret) { + return true + } + + return false +} + +// SetSecret gets a reference to the given string and assigns it to the Secret field. +func (o *APIKeyRead) SetSecret(v string) { + o.Secret = &v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *APIKeyRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *APIKeyRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetCreatedByMember returns the CreatedByMember field value +func (o *APIKeyRead) GetCreatedByMember() OrgMemberRead { + if o == nil { + var ret OrgMemberRead + return ret + } + + return o.CreatedByMember +} + +// GetCreatedByMemberOk returns a tuple with the CreatedByMember field value +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetCreatedByMemberOk() (*OrgMemberRead, bool) { + if o == nil { + return nil, false + } + return &o.CreatedByMember, true +} + +// SetCreatedByMember sets field value +func (o *APIKeyRead) SetCreatedByMember(v OrgMemberRead) { + o.CreatedByMember = v +} + +// GetLastUsedAt returns the LastUsedAt field value if set, zero value otherwise. +func (o *APIKeyRead) GetLastUsedAt() time.Time { + if o == nil || IsNil(o.LastUsedAt) { + var ret time.Time + return ret + } + return *o.LastUsedAt +} + +// GetLastUsedAtOk returns a tuple with the LastUsedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyRead) GetLastUsedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.LastUsedAt) { + return nil, false + } + return o.LastUsedAt, true +} + +// HasLastUsedAt returns a boolean if a field has been set. +func (o *APIKeyRead) HasLastUsedAt() bool { + if o != nil && !IsNil(o.LastUsedAt) { + return true + } + + return false +} + +// SetLastUsedAt gets a reference to the given time.Time and assigns it to the LastUsedAt field. +func (o *APIKeyRead) SetLastUsedAt(v time.Time) { + o.LastUsedAt = &v +} + +func (o APIKeyRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if !IsNil(o.ProjectId) { + toSerialize["project_id"] = o.ProjectId + } + if !IsNil(o.EnvironmentId) { + toSerialize["environment_id"] = o.EnvironmentId + } + if !IsNil(o.ObjectType) { + toSerialize["object_type"] = o.ObjectType + } + if !IsNil(o.AccessLevel) { + toSerialize["access_level"] = o.AccessLevel + } + if true { + toSerialize["owner_type"] = o.OwnerType + } + if true { + toSerialize["id"] = o.Id + } + if !IsNil(o.Secret) { + toSerialize["secret"] = o.Secret + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["created_by_member"] = o.CreatedByMember + } + if !IsNil(o.LastUsedAt) { + toSerialize["last_used_at"] = o.LastUsedAt + } + return json.Marshal(toSerialize) +} + +type NullableAPIKeyRead struct { + value *APIKeyRead + isSet bool +} + +func (v NullableAPIKeyRead) Get() *APIKeyRead { + return v.value +} + +func (v *NullableAPIKeyRead) Set(val *APIKeyRead) { + v.value = val + v.isSet = true +} + +func (v NullableAPIKeyRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAPIKeyRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAPIKeyRead(val *APIKeyRead) *NullableAPIKeyRead { + return &NullableAPIKeyRead{value: val, isSet: true} +} + +func (v NullableAPIKeyRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAPIKeyRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_scope_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_scope_read.go new file mode 100644 index 00000000..e20ed4e3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_api_key_scope_read.go @@ -0,0 +1,181 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// APIKeyScopeRead struct for APIKeyScopeRead +type APIKeyScopeRead struct { + // Unique id of the organization that the api_key belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the api_key belongs to. + ProjectId *string `json:"project_id,omitempty"` + // Unique id of the environment that the api_key belongs to. + EnvironmentId *string `json:"environment_id,omitempty"` +} + +// NewAPIKeyScopeRead instantiates a new APIKeyScopeRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAPIKeyScopeRead(organizationId string) *APIKeyScopeRead { + this := APIKeyScopeRead{} + this.OrganizationId = organizationId + return &this +} + +// NewAPIKeyScopeReadWithDefaults instantiates a new APIKeyScopeRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAPIKeyScopeReadWithDefaults() *APIKeyScopeRead { + this := APIKeyScopeRead{} + return &this +} + +// GetOrganizationId returns the OrganizationId field value +func (o *APIKeyScopeRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *APIKeyScopeRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *APIKeyScopeRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value if set, zero value otherwise. +func (o *APIKeyScopeRead) GetProjectId() string { + if o == nil || IsNil(o.ProjectId) { + var ret string + return ret + } + return *o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyScopeRead) GetProjectIdOk() (*string, bool) { + if o == nil || IsNil(o.ProjectId) { + return nil, false + } + return o.ProjectId, true +} + +// HasProjectId returns a boolean if a field has been set. +func (o *APIKeyScopeRead) HasProjectId() bool { + if o != nil && !IsNil(o.ProjectId) { + return true + } + + return false +} + +// SetProjectId gets a reference to the given string and assigns it to the ProjectId field. +func (o *APIKeyScopeRead) SetProjectId(v string) { + o.ProjectId = &v +} + +// GetEnvironmentId returns the EnvironmentId field value if set, zero value otherwise. +func (o *APIKeyScopeRead) GetEnvironmentId() string { + if o == nil || IsNil(o.EnvironmentId) { + var ret string + return ret + } + return *o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *APIKeyScopeRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentId) { + return nil, false + } + return o.EnvironmentId, true +} + +// HasEnvironmentId returns a boolean if a field has been set. +func (o *APIKeyScopeRead) HasEnvironmentId() bool { + if o != nil && !IsNil(o.EnvironmentId) { + return true + } + + return false +} + +// SetEnvironmentId gets a reference to the given string and assigns it to the EnvironmentId field. +func (o *APIKeyScopeRead) SetEnvironmentId(v string) { + o.EnvironmentId = &v +} + +func (o APIKeyScopeRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if !IsNil(o.ProjectId) { + toSerialize["project_id"] = o.ProjectId + } + if !IsNil(o.EnvironmentId) { + toSerialize["environment_id"] = o.EnvironmentId + } + return json.Marshal(toSerialize) +} + +type NullableAPIKeyScopeRead struct { + value *APIKeyScopeRead + isSet bool +} + +func (v NullableAPIKeyScopeRead) Get() *APIKeyScopeRead { + return v.value +} + +func (v *NullableAPIKeyScopeRead) Set(val *APIKeyScopeRead) { + v.value = val + v.isSet = true +} + +func (v NullableAPIKeyScopeRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAPIKeyScopeRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAPIKeyScopeRead(val *APIKeyScopeRead) *NullableAPIKeyScopeRead { + return &NullableAPIKeyScopeRead{value: val, isSet: true} +} + +func (v NullableAPIKeyScopeRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAPIKeyScopeRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_editable.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_editable.go new file mode 100644 index 00000000..846d76f4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_editable.go @@ -0,0 +1,144 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AttributeBlockEditable struct for AttributeBlockEditable +type AttributeBlockEditable struct { + // The type of the attribute, we currently support: `bool`, `number` (ints, floats), `time` (a timestamp), `string`, and `json`. + Type AttributeType `json:"type"` + // optional description string explaining what data this attribute will store + Description *string `json:"description,omitempty"` +} + +// NewAttributeBlockEditable instantiates a new AttributeBlockEditable object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAttributeBlockEditable(type_ AttributeType) *AttributeBlockEditable { + this := AttributeBlockEditable{} + this.Type = type_ + return &this +} + +// NewAttributeBlockEditableWithDefaults instantiates a new AttributeBlockEditable object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAttributeBlockEditableWithDefaults() *AttributeBlockEditable { + this := AttributeBlockEditable{} + return &this +} + +// GetType returns the Type field value +func (o *AttributeBlockEditable) GetType() AttributeType { + if o == nil { + var ret AttributeType + return ret + } + + return o.Type +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +func (o *AttributeBlockEditable) GetTypeOk() (*AttributeType, bool) { + if o == nil { + return nil, false + } + return &o.Type, true +} + +// SetType sets field value +func (o *AttributeBlockEditable) SetType(v AttributeType) { + o.Type = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *AttributeBlockEditable) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AttributeBlockEditable) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *AttributeBlockEditable) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *AttributeBlockEditable) SetDescription(v string) { + o.Description = &v +} + +func (o AttributeBlockEditable) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["type"] = o.Type + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + return json.Marshal(toSerialize) +} + +type NullableAttributeBlockEditable struct { + value *AttributeBlockEditable + isSet bool +} + +func (v NullableAttributeBlockEditable) Get() *AttributeBlockEditable { + return v.value +} + +func (v *NullableAttributeBlockEditable) Set(val *AttributeBlockEditable) { + v.value = val + v.isSet = true +} + +func (v NullableAttributeBlockEditable) IsSet() bool { + return v.isSet +} + +func (v *NullableAttributeBlockEditable) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAttributeBlockEditable(val *AttributeBlockEditable) *NullableAttributeBlockEditable { + return &NullableAttributeBlockEditable{value: val, isSet: true} +} + +func (v NullableAttributeBlockEditable) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAttributeBlockEditable) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_read.go new file mode 100644 index 00000000..bd744824 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_block_read.go @@ -0,0 +1,211 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AttributeBlockRead struct for AttributeBlockRead +type AttributeBlockRead struct { + // The type of the attribute, we currently support: `bool`, `number` (ints, floats), `time` (a timestamp), `string`, and `json`. + Type AttributeType `json:"type"` + // optional description string explaining what data this attribute will store + Description *string `json:"description,omitempty"` + // Unique id of the attribute + Id string `json:"id"` + // action key + Key *string `json:"key,omitempty"` +} + +// NewAttributeBlockRead instantiates a new AttributeBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAttributeBlockRead(type_ AttributeType, id string) *AttributeBlockRead { + this := AttributeBlockRead{} + this.Type = type_ + this.Id = id + return &this +} + +// NewAttributeBlockReadWithDefaults instantiates a new AttributeBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAttributeBlockReadWithDefaults() *AttributeBlockRead { + this := AttributeBlockRead{} + return &this +} + +// GetType returns the Type field value +func (o *AttributeBlockRead) GetType() AttributeType { + if o == nil { + var ret AttributeType + return ret + } + + return o.Type +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +func (o *AttributeBlockRead) GetTypeOk() (*AttributeType, bool) { + if o == nil { + return nil, false + } + return &o.Type, true +} + +// SetType sets field value +func (o *AttributeBlockRead) SetType(v AttributeType) { + o.Type = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *AttributeBlockRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AttributeBlockRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *AttributeBlockRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *AttributeBlockRead) SetDescription(v string) { + o.Description = &v +} + +// GetId returns the Id field value +func (o *AttributeBlockRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *AttributeBlockRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *AttributeBlockRead) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value if set, zero value otherwise. +func (o *AttributeBlockRead) GetKey() string { + if o == nil || IsNil(o.Key) { + var ret string + return ret + } + return *o.Key +} + +// GetKeyOk returns a tuple with the Key field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AttributeBlockRead) GetKeyOk() (*string, bool) { + if o == nil || IsNil(o.Key) { + return nil, false + } + return o.Key, true +} + +// HasKey returns a boolean if a field has been set. +func (o *AttributeBlockRead) HasKey() bool { + if o != nil && !IsNil(o.Key) { + return true + } + + return false +} + +// SetKey gets a reference to the given string and assigns it to the Key field. +func (o *AttributeBlockRead) SetKey(v string) { + o.Key = &v +} + +func (o AttributeBlockRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["type"] = o.Type + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if true { + toSerialize["id"] = o.Id + } + if !IsNil(o.Key) { + toSerialize["key"] = o.Key + } + return json.Marshal(toSerialize) +} + +type NullableAttributeBlockRead struct { + value *AttributeBlockRead + isSet bool +} + +func (v NullableAttributeBlockRead) Get() *AttributeBlockRead { + return v.value +} + +func (v *NullableAttributeBlockRead) Set(val *AttributeBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableAttributeBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAttributeBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAttributeBlockRead(val *AttributeBlockRead) *NullableAttributeBlockRead { + return &NullableAttributeBlockRead{value: val, isSet: true} +} + +func (v NullableAttributeBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAttributeBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_type.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_type.go new file mode 100644 index 00000000..53dbeed9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_attribute_type.go @@ -0,0 +1,118 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// AttributeType supported attribute primitives +type AttributeType string + +// List of AttributeType +const ( + BOOL AttributeType = "bool" + NUMBER AttributeType = "number" + STRING AttributeType = "string" + TIME AttributeType = "time" + ARRAY AttributeType = "array" + JSON AttributeType = "json" +) + +// All allowed values of AttributeType enum +var AllowedAttributeTypeEnumValues = []AttributeType{ + "bool", + "number", + "string", + "time", + "array", + "json", +} + +func (v *AttributeType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := AttributeType(value) + for _, existing := range AllowedAttributeTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid AttributeType", value) +} + +// NewAttributeTypeFromValue returns a pointer to a valid AttributeType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewAttributeTypeFromValue(v string) (*AttributeType, error) { + ev := AttributeType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for AttributeType: valid values are %v", v, AllowedAttributeTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v AttributeType) IsValid() bool { + for _, existing := range AllowedAttributeTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to AttributeType value +func (v AttributeType) Ptr() *AttributeType { + return &v +} + +type NullableAttributeType struct { + value *AttributeType + isSet bool +} + +func (v NullableAttributeType) Get() *AttributeType { + return v.value +} + +func (v *NullableAttributeType) Set(val *AttributeType) { + v.value = val + v.isSet = true +} + +func (v NullableAttributeType) IsSet() bool { + return v.isSet +} + +func (v *NullableAttributeType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAttributeType(val *AttributeType) *NullableAttributeType { + return &NullableAttributeType{value: val, isSet: true} +} + +func (v NullableAttributeType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAttributeType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_attributes.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_attributes.go new file mode 100644 index 00000000..2aca2ae9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_attributes.go @@ -0,0 +1,121 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// Attributes struct for Attributes +type Attributes struct { + bool *bool + int32 *int32 + string *string +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *Attributes) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into bool + err = json.Unmarshal(data, &dst.bool) + if err == nil { + jsonbool, _ := json.Marshal(dst.bool) + if string(jsonbool) == "{}" { // empty struct + dst.bool = nil + } else { + return nil // data stored in dst.bool, return on the first match + } + } else { + dst.bool = nil + } + + // try to unmarshal JSON data into int32 + err = json.Unmarshal(data, &dst.int32) + if err == nil { + jsonint32, _ := json.Marshal(dst.int32) + if string(jsonint32) == "{}" { // empty struct + dst.int32 = nil + } else { + return nil // data stored in dst.int32, return on the first match + } + } else { + dst.int32 = nil + } + + // try to unmarshal JSON data into string + err = json.Unmarshal(data, &dst.string) + if err == nil { + jsonstring, _ := json.Marshal(dst.string) + if string(jsonstring) == "{}" { // empty struct + dst.string = nil + } else { + return nil // data stored in dst.string, return on the first match + } + } else { + dst.string = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(Attributes)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *Attributes) MarshalJSON() ([]byte, error) { + if src.bool != nil { + return json.Marshal(&src.bool) + } + + if src.int32 != nil { + return json.Marshal(&src.int32) + } + + if src.string != nil { + return json.Marshal(&src.string) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableAttributes struct { + value *Attributes + isSet bool +} + +func (v NullableAttributes) Get() *Attributes { + return v.value +} + +func (v *NullableAttributes) Set(val *Attributes) { + v.value = val + v.isSet = true +} + +func (v NullableAttributes) IsSet() bool { + return v.isSet +} + +func (v *NullableAttributes) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAttributes(val *Attributes) *NullableAttributes { + return &NullableAttributes{value: val, isSet: true} +} + +func (v NullableAttributes) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAttributes) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_auth_mechanism.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_auth_mechanism.go new file mode 100644 index 00000000..99fdd96a --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_auth_mechanism.go @@ -0,0 +1,112 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// AuthMechanism An enumeration. +type AuthMechanism string + +// List of AuthMechanism +const ( + BEARER AuthMechanism = "Bearer" + BASIC AuthMechanism = "Basic" + HEADERS AuthMechanism = "Headers" +) + +// All allowed values of AuthMechanism enum +var AllowedAuthMechanismEnumValues = []AuthMechanism{ + "Bearer", + "Basic", + "Headers", +} + +func (v *AuthMechanism) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := AuthMechanism(value) + for _, existing := range AllowedAuthMechanismEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid AuthMechanism", value) +} + +// NewAuthMechanismFromValue returns a pointer to a valid AuthMechanism +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewAuthMechanismFromValue(v string) (*AuthMechanism, error) { + ev := AuthMechanism(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for AuthMechanism: valid values are %v", v, AllowedAuthMechanismEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v AuthMechanism) IsValid() bool { + for _, existing := range AllowedAuthMechanismEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to AuthMechanism value +func (v AuthMechanism) Ptr() *AuthMechanism { + return &v +} + +type NullableAuthMechanism struct { + value *AuthMechanism + isSet bool +} + +func (v NullableAuthMechanism) Get() *AuthMechanism { + return v.value +} + +func (v *NullableAuthMechanism) Set(val *AuthMechanism) { + v.value = val + v.isSet = true +} + +func (v NullableAuthMechanism) IsSet() bool { + return v.isSet +} + +func (v *NullableAuthMechanism) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAuthMechanism(val *AuthMechanism) *NullableAuthMechanism { + return &NullableAuthMechanism{value: val, isSet: true} +} + +func (v NullableAuthMechanism) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAuthMechanism) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_api_key_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_api_key_read.go new file mode 100644 index 00000000..78ff2b69 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_api_key_read.go @@ -0,0 +1,305 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AuthnMeAPIKeyRead struct for AuthnMeAPIKeyRead +type AuthnMeAPIKeyRead struct { + ActorType *string `json:"actor_type,omitempty"` + Id string `json:"id"` + ObjectType MemberAccessObj `json:"object_type"` + OwnerType APIKeyOwnerType `json:"owner_type"` + OrgId string `json:"org_id"` + ProjectId *string `json:"project_id,omitempty"` + EnvId *string `json:"env_id,omitempty"` +} + +// NewAuthnMeAPIKeyRead instantiates a new AuthnMeAPIKeyRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAuthnMeAPIKeyRead(id string, objectType MemberAccessObj, ownerType APIKeyOwnerType, orgId string) *AuthnMeAPIKeyRead { + this := AuthnMeAPIKeyRead{} + var actorType string = "api_key" + this.ActorType = &actorType + this.Id = id + this.ObjectType = objectType + this.OwnerType = ownerType + this.OrgId = orgId + return &this +} + +// NewAuthnMeAPIKeyReadWithDefaults instantiates a new AuthnMeAPIKeyRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAuthnMeAPIKeyReadWithDefaults() *AuthnMeAPIKeyRead { + this := AuthnMeAPIKeyRead{} + var actorType string = "api_key" + this.ActorType = &actorType + return &this +} + +// GetActorType returns the ActorType field value if set, zero value otherwise. +func (o *AuthnMeAPIKeyRead) GetActorType() string { + if o == nil || IsNil(o.ActorType) { + var ret string + return ret + } + return *o.ActorType +} + +// GetActorTypeOk returns a tuple with the ActorType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetActorTypeOk() (*string, bool) { + if o == nil || IsNil(o.ActorType) { + return nil, false + } + return o.ActorType, true +} + +// HasActorType returns a boolean if a field has been set. +func (o *AuthnMeAPIKeyRead) HasActorType() bool { + if o != nil && !IsNil(o.ActorType) { + return true + } + + return false +} + +// SetActorType gets a reference to the given string and assigns it to the ActorType field. +func (o *AuthnMeAPIKeyRead) SetActorType(v string) { + o.ActorType = &v +} + +// GetId returns the Id field value +func (o *AuthnMeAPIKeyRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *AuthnMeAPIKeyRead) SetId(v string) { + o.Id = v +} + +// GetObjectType returns the ObjectType field value +func (o *AuthnMeAPIKeyRead) GetObjectType() MemberAccessObj { + if o == nil { + var ret MemberAccessObj + return ret + } + + return o.ObjectType +} + +// GetObjectTypeOk returns a tuple with the ObjectType field value +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetObjectTypeOk() (*MemberAccessObj, bool) { + if o == nil { + return nil, false + } + return &o.ObjectType, true +} + +// SetObjectType sets field value +func (o *AuthnMeAPIKeyRead) SetObjectType(v MemberAccessObj) { + o.ObjectType = v +} + +// GetOwnerType returns the OwnerType field value +func (o *AuthnMeAPIKeyRead) GetOwnerType() APIKeyOwnerType { + if o == nil { + var ret APIKeyOwnerType + return ret + } + + return o.OwnerType +} + +// GetOwnerTypeOk returns a tuple with the OwnerType field value +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetOwnerTypeOk() (*APIKeyOwnerType, bool) { + if o == nil { + return nil, false + } + return &o.OwnerType, true +} + +// SetOwnerType sets field value +func (o *AuthnMeAPIKeyRead) SetOwnerType(v APIKeyOwnerType) { + o.OwnerType = v +} + +// GetOrgId returns the OrgId field value +func (o *AuthnMeAPIKeyRead) GetOrgId() string { + if o == nil { + var ret string + return ret + } + + return o.OrgId +} + +// GetOrgIdOk returns a tuple with the OrgId field value +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetOrgIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrgId, true +} + +// SetOrgId sets field value +func (o *AuthnMeAPIKeyRead) SetOrgId(v string) { + o.OrgId = v +} + +// GetProjectId returns the ProjectId field value if set, zero value otherwise. +func (o *AuthnMeAPIKeyRead) GetProjectId() string { + if o == nil || IsNil(o.ProjectId) { + var ret string + return ret + } + return *o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetProjectIdOk() (*string, bool) { + if o == nil || IsNil(o.ProjectId) { + return nil, false + } + return o.ProjectId, true +} + +// HasProjectId returns a boolean if a field has been set. +func (o *AuthnMeAPIKeyRead) HasProjectId() bool { + if o != nil && !IsNil(o.ProjectId) { + return true + } + + return false +} + +// SetProjectId gets a reference to the given string and assigns it to the ProjectId field. +func (o *AuthnMeAPIKeyRead) SetProjectId(v string) { + o.ProjectId = &v +} + +// GetEnvId returns the EnvId field value if set, zero value otherwise. +func (o *AuthnMeAPIKeyRead) GetEnvId() string { + if o == nil || IsNil(o.EnvId) { + var ret string + return ret + } + return *o.EnvId +} + +// GetEnvIdOk returns a tuple with the EnvId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeAPIKeyRead) GetEnvIdOk() (*string, bool) { + if o == nil || IsNil(o.EnvId) { + return nil, false + } + return o.EnvId, true +} + +// HasEnvId returns a boolean if a field has been set. +func (o *AuthnMeAPIKeyRead) HasEnvId() bool { + if o != nil && !IsNil(o.EnvId) { + return true + } + + return false +} + +// SetEnvId gets a reference to the given string and assigns it to the EnvId field. +func (o *AuthnMeAPIKeyRead) SetEnvId(v string) { + o.EnvId = &v +} + +func (o AuthnMeAPIKeyRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.ActorType) { + toSerialize["actor_type"] = o.ActorType + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["object_type"] = o.ObjectType + } + if true { + toSerialize["owner_type"] = o.OwnerType + } + if true { + toSerialize["org_id"] = o.OrgId + } + if !IsNil(o.ProjectId) { + toSerialize["project_id"] = o.ProjectId + } + if !IsNil(o.EnvId) { + toSerialize["env_id"] = o.EnvId + } + return json.Marshal(toSerialize) +} + +type NullableAuthnMeAPIKeyRead struct { + value *AuthnMeAPIKeyRead + isSet bool +} + +func (v NullableAuthnMeAPIKeyRead) Get() *AuthnMeAPIKeyRead { + return v.value +} + +func (v *NullableAuthnMeAPIKeyRead) Set(val *AuthnMeAPIKeyRead) { + v.value = val + v.isSet = true +} + +func (v NullableAuthnMeAPIKeyRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAuthnMeAPIKeyRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAuthnMeAPIKeyRead(val *AuthnMeAPIKeyRead) *NullableAuthnMeAPIKeyRead { + return &NullableAuthnMeAPIKeyRead{value: val, isSet: true} +} + +func (v NullableAuthnMeAPIKeyRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAuthnMeAPIKeyRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_member_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_member_read.go new file mode 100644 index 00000000..3e37bb2a --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_member_read.go @@ -0,0 +1,382 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AuthnMeMemberRead struct for AuthnMeMemberRead +type AuthnMeMemberRead struct { + ActorType *string `json:"actor_type,omitempty"` + Id string `json:"id"` + // Email of the user controlling this account + Email string `json:"email"` + // Name of this user + Name *string `json:"name,omitempty"` + // Given name of the user + GivenName *string `json:"given_name,omitempty"` + // Family name of the user + FamilyName *string `json:"family_name,omitempty"` + // URL to picture, photo, or avatar of the user that controls this account. + Picture *string `json:"picture,omitempty"` + IsOnboarding bool `json:"is_onboarding"` + OnboardingStep OnboardingStep `json:"onboarding_step"` +} + +// NewAuthnMeMemberRead instantiates a new AuthnMeMemberRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAuthnMeMemberRead(id string, email string, isOnboarding bool, onboardingStep OnboardingStep) *AuthnMeMemberRead { + this := AuthnMeMemberRead{} + var actorType string = "member" + this.ActorType = &actorType + this.Id = id + this.Email = email + this.IsOnboarding = isOnboarding + this.OnboardingStep = onboardingStep + return &this +} + +// NewAuthnMeMemberReadWithDefaults instantiates a new AuthnMeMemberRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAuthnMeMemberReadWithDefaults() *AuthnMeMemberRead { + this := AuthnMeMemberRead{} + var actorType string = "member" + this.ActorType = &actorType + return &this +} + +// GetActorType returns the ActorType field value if set, zero value otherwise. +func (o *AuthnMeMemberRead) GetActorType() string { + if o == nil || IsNil(o.ActorType) { + var ret string + return ret + } + return *o.ActorType +} + +// GetActorTypeOk returns a tuple with the ActorType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetActorTypeOk() (*string, bool) { + if o == nil || IsNil(o.ActorType) { + return nil, false + } + return o.ActorType, true +} + +// HasActorType returns a boolean if a field has been set. +func (o *AuthnMeMemberRead) HasActorType() bool { + if o != nil && !IsNil(o.ActorType) { + return true + } + + return false +} + +// SetActorType gets a reference to the given string and assigns it to the ActorType field. +func (o *AuthnMeMemberRead) SetActorType(v string) { + o.ActorType = &v +} + +// GetId returns the Id field value +func (o *AuthnMeMemberRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *AuthnMeMemberRead) SetId(v string) { + o.Id = v +} + +// GetEmail returns the Email field value +func (o *AuthnMeMemberRead) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *AuthnMeMemberRead) SetEmail(v string) { + o.Email = v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *AuthnMeMemberRead) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *AuthnMeMemberRead) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *AuthnMeMemberRead) SetName(v string) { + o.Name = &v +} + +// GetGivenName returns the GivenName field value if set, zero value otherwise. +func (o *AuthnMeMemberRead) GetGivenName() string { + if o == nil || IsNil(o.GivenName) { + var ret string + return ret + } + return *o.GivenName +} + +// GetGivenNameOk returns a tuple with the GivenName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetGivenNameOk() (*string, bool) { + if o == nil || IsNil(o.GivenName) { + return nil, false + } + return o.GivenName, true +} + +// HasGivenName returns a boolean if a field has been set. +func (o *AuthnMeMemberRead) HasGivenName() bool { + if o != nil && !IsNil(o.GivenName) { + return true + } + + return false +} + +// SetGivenName gets a reference to the given string and assigns it to the GivenName field. +func (o *AuthnMeMemberRead) SetGivenName(v string) { + o.GivenName = &v +} + +// GetFamilyName returns the FamilyName field value if set, zero value otherwise. +func (o *AuthnMeMemberRead) GetFamilyName() string { + if o == nil || IsNil(o.FamilyName) { + var ret string + return ret + } + return *o.FamilyName +} + +// GetFamilyNameOk returns a tuple with the FamilyName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetFamilyNameOk() (*string, bool) { + if o == nil || IsNil(o.FamilyName) { + return nil, false + } + return o.FamilyName, true +} + +// HasFamilyName returns a boolean if a field has been set. +func (o *AuthnMeMemberRead) HasFamilyName() bool { + if o != nil && !IsNil(o.FamilyName) { + return true + } + + return false +} + +// SetFamilyName gets a reference to the given string and assigns it to the FamilyName field. +func (o *AuthnMeMemberRead) SetFamilyName(v string) { + o.FamilyName = &v +} + +// GetPicture returns the Picture field value if set, zero value otherwise. +func (o *AuthnMeMemberRead) GetPicture() string { + if o == nil || IsNil(o.Picture) { + var ret string + return ret + } + return *o.Picture +} + +// GetPictureOk returns a tuple with the Picture field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetPictureOk() (*string, bool) { + if o == nil || IsNil(o.Picture) { + return nil, false + } + return o.Picture, true +} + +// HasPicture returns a boolean if a field has been set. +func (o *AuthnMeMemberRead) HasPicture() bool { + if o != nil && !IsNil(o.Picture) { + return true + } + + return false +} + +// SetPicture gets a reference to the given string and assigns it to the Picture field. +func (o *AuthnMeMemberRead) SetPicture(v string) { + o.Picture = &v +} + +// GetIsOnboarding returns the IsOnboarding field value +func (o *AuthnMeMemberRead) GetIsOnboarding() bool { + if o == nil { + var ret bool + return ret + } + + return o.IsOnboarding +} + +// GetIsOnboardingOk returns a tuple with the IsOnboarding field value +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetIsOnboardingOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.IsOnboarding, true +} + +// SetIsOnboarding sets field value +func (o *AuthnMeMemberRead) SetIsOnboarding(v bool) { + o.IsOnboarding = v +} + +// GetOnboardingStep returns the OnboardingStep field value +func (o *AuthnMeMemberRead) GetOnboardingStep() OnboardingStep { + if o == nil { + var ret OnboardingStep + return ret + } + + return o.OnboardingStep +} + +// GetOnboardingStepOk returns a tuple with the OnboardingStep field value +// and a boolean to check if the value has been set. +func (o *AuthnMeMemberRead) GetOnboardingStepOk() (*OnboardingStep, bool) { + if o == nil { + return nil, false + } + return &o.OnboardingStep, true +} + +// SetOnboardingStep sets field value +func (o *AuthnMeMemberRead) SetOnboardingStep(v OnboardingStep) { + o.OnboardingStep = v +} + +func (o AuthnMeMemberRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.ActorType) { + toSerialize["actor_type"] = o.ActorType + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["email"] = o.Email + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.GivenName) { + toSerialize["given_name"] = o.GivenName + } + if !IsNil(o.FamilyName) { + toSerialize["family_name"] = o.FamilyName + } + if !IsNil(o.Picture) { + toSerialize["picture"] = o.Picture + } + if true { + toSerialize["is_onboarding"] = o.IsOnboarding + } + if true { + toSerialize["onboarding_step"] = o.OnboardingStep + } + return json.Marshal(toSerialize) +} + +type NullableAuthnMeMemberRead struct { + value *AuthnMeMemberRead + isSet bool +} + +func (v NullableAuthnMeMemberRead) Get() *AuthnMeMemberRead { + return v.value +} + +func (v *NullableAuthnMeMemberRead) Set(val *AuthnMeMemberRead) { + v.value = val + v.isSet = true +} + +func (v NullableAuthnMeMemberRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAuthnMeMemberRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAuthnMeMemberRead(val *AuthnMeMemberRead) *NullableAuthnMeMemberRead { + return &NullableAuthnMeMemberRead{value: val, isSet: true} +} + +func (v NullableAuthnMeMemberRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAuthnMeMemberRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_read.go new file mode 100644 index 00000000..bdab6cea --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_read.go @@ -0,0 +1,106 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AuthnMeRead struct for AuthnMeRead +type AuthnMeRead struct { + Actor Actor `json:"actor"` +} + +// NewAuthnMeRead instantiates a new AuthnMeRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAuthnMeRead(actor Actor) *AuthnMeRead { + this := AuthnMeRead{} + this.Actor = actor + return &this +} + +// NewAuthnMeReadWithDefaults instantiates a new AuthnMeRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAuthnMeReadWithDefaults() *AuthnMeRead { + this := AuthnMeRead{} + return &this +} + +// GetActor returns the Actor field value +func (o *AuthnMeRead) GetActor() Actor { + if o == nil { + var ret Actor + return ret + } + + return o.Actor +} + +// GetActorOk returns a tuple with the Actor field value +// and a boolean to check if the value has been set. +func (o *AuthnMeRead) GetActorOk() (*Actor, bool) { + if o == nil { + return nil, false + } + return &o.Actor, true +} + +// SetActor sets field value +func (o *AuthnMeRead) SetActor(v Actor) { + o.Actor = v +} + +func (o AuthnMeRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["actor"] = o.Actor + } + return json.Marshal(toSerialize) +} + +type NullableAuthnMeRead struct { + value *AuthnMeRead + isSet bool +} + +func (v NullableAuthnMeRead) Get() *AuthnMeRead { + return v.value +} + +func (v *NullableAuthnMeRead) Set(val *AuthnMeRead) { + v.value = val + v.isSet = true +} + +func (v NullableAuthnMeRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAuthnMeRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAuthnMeRead(val *AuthnMeRead) *NullableAuthnMeRead { + return &NullableAuthnMeRead{value: val, isSet: true} +} + +func (v NullableAuthnMeRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAuthnMeRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_user_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_user_read.go new file mode 100644 index 00000000..1f2fefa7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_authn_me_user_read.go @@ -0,0 +1,578 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// AuthnMeUserRead struct for AuthnMeUserRead +type AuthnMeUserRead struct { + ActorType *string `json:"actor_type,omitempty"` + Id string `json:"id"` + Key string `json:"key"` + OrgId string `json:"org_id"` + ProjectId string `json:"project_id"` + EnvId string `json:"env_id"` + TenantId string `json:"tenant_id"` + // Email of the user controlling this account + Email string `json:"email"` + // Name of this user + Name *string `json:"name,omitempty"` + // Given name of the user + GivenName *string `json:"given_name,omitempty"` + // Family name of the user + FamilyName *string `json:"family_name,omitempty"` + // URL to picture, photo, or avatar of the user that controls this account. + Picture *string `json:"picture,omitempty"` + PermissionLevel ElementsPermissionLevel `json:"permission_level"` + IsOnboarding *bool `json:"is_onboarding,omitempty"` + OnboardingStep *string `json:"onboarding_step,omitempty"` +} + +// NewAuthnMeUserRead instantiates a new AuthnMeUserRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAuthnMeUserRead(id string, key string, orgId string, projectId string, envId string, tenantId string, email string, permissionLevel ElementsPermissionLevel) *AuthnMeUserRead { + this := AuthnMeUserRead{} + var actorType string = "user" + this.ActorType = &actorType + this.Id = id + this.Key = key + this.OrgId = orgId + this.ProjectId = projectId + this.EnvId = envId + this.TenantId = tenantId + this.Email = email + this.PermissionLevel = permissionLevel + var isOnboarding bool = false + this.IsOnboarding = &isOnboarding + var onboardingStep string = "done" + this.OnboardingStep = &onboardingStep + return &this +} + +// NewAuthnMeUserReadWithDefaults instantiates a new AuthnMeUserRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAuthnMeUserReadWithDefaults() *AuthnMeUserRead { + this := AuthnMeUserRead{} + var actorType string = "user" + this.ActorType = &actorType + var isOnboarding bool = false + this.IsOnboarding = &isOnboarding + var onboardingStep string = "done" + this.OnboardingStep = &onboardingStep + return &this +} + +// GetActorType returns the ActorType field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetActorType() string { + if o == nil || IsNil(o.ActorType) { + var ret string + return ret + } + return *o.ActorType +} + +// GetActorTypeOk returns a tuple with the ActorType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetActorTypeOk() (*string, bool) { + if o == nil || IsNil(o.ActorType) { + return nil, false + } + return o.ActorType, true +} + +// HasActorType returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasActorType() bool { + if o != nil && !IsNil(o.ActorType) { + return true + } + + return false +} + +// SetActorType gets a reference to the given string and assigns it to the ActorType field. +func (o *AuthnMeUserRead) SetActorType(v string) { + o.ActorType = &v +} + +// GetId returns the Id field value +func (o *AuthnMeUserRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *AuthnMeUserRead) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *AuthnMeUserRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *AuthnMeUserRead) SetKey(v string) { + o.Key = v +} + +// GetOrgId returns the OrgId field value +func (o *AuthnMeUserRead) GetOrgId() string { + if o == nil { + var ret string + return ret + } + + return o.OrgId +} + +// GetOrgIdOk returns a tuple with the OrgId field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetOrgIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrgId, true +} + +// SetOrgId sets field value +func (o *AuthnMeUserRead) SetOrgId(v string) { + o.OrgId = v +} + +// GetProjectId returns the ProjectId field value +func (o *AuthnMeUserRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *AuthnMeUserRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvId returns the EnvId field value +func (o *AuthnMeUserRead) GetEnvId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvId +} + +// GetEnvIdOk returns a tuple with the EnvId field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetEnvIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvId, true +} + +// SetEnvId sets field value +func (o *AuthnMeUserRead) SetEnvId(v string) { + o.EnvId = v +} + +// GetTenantId returns the TenantId field value +func (o *AuthnMeUserRead) GetTenantId() string { + if o == nil { + var ret string + return ret + } + + return o.TenantId +} + +// GetTenantIdOk returns a tuple with the TenantId field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetTenantIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.TenantId, true +} + +// SetTenantId sets field value +func (o *AuthnMeUserRead) SetTenantId(v string) { + o.TenantId = v +} + +// GetEmail returns the Email field value +func (o *AuthnMeUserRead) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *AuthnMeUserRead) SetEmail(v string) { + o.Email = v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *AuthnMeUserRead) SetName(v string) { + o.Name = &v +} + +// GetGivenName returns the GivenName field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetGivenName() string { + if o == nil || IsNil(o.GivenName) { + var ret string + return ret + } + return *o.GivenName +} + +// GetGivenNameOk returns a tuple with the GivenName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetGivenNameOk() (*string, bool) { + if o == nil || IsNil(o.GivenName) { + return nil, false + } + return o.GivenName, true +} + +// HasGivenName returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasGivenName() bool { + if o != nil && !IsNil(o.GivenName) { + return true + } + + return false +} + +// SetGivenName gets a reference to the given string and assigns it to the GivenName field. +func (o *AuthnMeUserRead) SetGivenName(v string) { + o.GivenName = &v +} + +// GetFamilyName returns the FamilyName field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetFamilyName() string { + if o == nil || IsNil(o.FamilyName) { + var ret string + return ret + } + return *o.FamilyName +} + +// GetFamilyNameOk returns a tuple with the FamilyName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetFamilyNameOk() (*string, bool) { + if o == nil || IsNil(o.FamilyName) { + return nil, false + } + return o.FamilyName, true +} + +// HasFamilyName returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasFamilyName() bool { + if o != nil && !IsNil(o.FamilyName) { + return true + } + + return false +} + +// SetFamilyName gets a reference to the given string and assigns it to the FamilyName field. +func (o *AuthnMeUserRead) SetFamilyName(v string) { + o.FamilyName = &v +} + +// GetPicture returns the Picture field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetPicture() string { + if o == nil || IsNil(o.Picture) { + var ret string + return ret + } + return *o.Picture +} + +// GetPictureOk returns a tuple with the Picture field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetPictureOk() (*string, bool) { + if o == nil || IsNil(o.Picture) { + return nil, false + } + return o.Picture, true +} + +// HasPicture returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasPicture() bool { + if o != nil && !IsNil(o.Picture) { + return true + } + + return false +} + +// SetPicture gets a reference to the given string and assigns it to the Picture field. +func (o *AuthnMeUserRead) SetPicture(v string) { + o.Picture = &v +} + +// GetPermissionLevel returns the PermissionLevel field value +func (o *AuthnMeUserRead) GetPermissionLevel() ElementsPermissionLevel { + if o == nil { + var ret ElementsPermissionLevel + return ret + } + + return o.PermissionLevel +} + +// GetPermissionLevelOk returns a tuple with the PermissionLevel field value +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetPermissionLevelOk() (*ElementsPermissionLevel, bool) { + if o == nil { + return nil, false + } + return &o.PermissionLevel, true +} + +// SetPermissionLevel sets field value +func (o *AuthnMeUserRead) SetPermissionLevel(v ElementsPermissionLevel) { + o.PermissionLevel = v +} + +// GetIsOnboarding returns the IsOnboarding field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetIsOnboarding() bool { + if o == nil || IsNil(o.IsOnboarding) { + var ret bool + return ret + } + return *o.IsOnboarding +} + +// GetIsOnboardingOk returns a tuple with the IsOnboarding field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetIsOnboardingOk() (*bool, bool) { + if o == nil || IsNil(o.IsOnboarding) { + return nil, false + } + return o.IsOnboarding, true +} + +// HasIsOnboarding returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasIsOnboarding() bool { + if o != nil && !IsNil(o.IsOnboarding) { + return true + } + + return false +} + +// SetIsOnboarding gets a reference to the given bool and assigns it to the IsOnboarding field. +func (o *AuthnMeUserRead) SetIsOnboarding(v bool) { + o.IsOnboarding = &v +} + +// GetOnboardingStep returns the OnboardingStep field value if set, zero value otherwise. +func (o *AuthnMeUserRead) GetOnboardingStep() string { + if o == nil || IsNil(o.OnboardingStep) { + var ret string + return ret + } + return *o.OnboardingStep +} + +// GetOnboardingStepOk returns a tuple with the OnboardingStep field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *AuthnMeUserRead) GetOnboardingStepOk() (*string, bool) { + if o == nil || IsNil(o.OnboardingStep) { + return nil, false + } + return o.OnboardingStep, true +} + +// HasOnboardingStep returns a boolean if a field has been set. +func (o *AuthnMeUserRead) HasOnboardingStep() bool { + if o != nil && !IsNil(o.OnboardingStep) { + return true + } + + return false +} + +// SetOnboardingStep gets a reference to the given string and assigns it to the OnboardingStep field. +func (o *AuthnMeUserRead) SetOnboardingStep(v string) { + o.OnboardingStep = &v +} + +func (o AuthnMeUserRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.ActorType) { + toSerialize["actor_type"] = o.ActorType + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["org_id"] = o.OrgId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["env_id"] = o.EnvId + } + if true { + toSerialize["tenant_id"] = o.TenantId + } + if true { + toSerialize["email"] = o.Email + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.GivenName) { + toSerialize["given_name"] = o.GivenName + } + if !IsNil(o.FamilyName) { + toSerialize["family_name"] = o.FamilyName + } + if !IsNil(o.Picture) { + toSerialize["picture"] = o.Picture + } + if true { + toSerialize["permission_level"] = o.PermissionLevel + } + if !IsNil(o.IsOnboarding) { + toSerialize["is_onboarding"] = o.IsOnboarding + } + if !IsNil(o.OnboardingStep) { + toSerialize["onboarding_step"] = o.OnboardingStep + } + return json.Marshal(toSerialize) +} + +type NullableAuthnMeUserRead struct { + value *AuthnMeUserRead + isSet bool +} + +func (v NullableAuthnMeUserRead) Get() *AuthnMeUserRead { + return v.value +} + +func (v *NullableAuthnMeUserRead) Set(val *AuthnMeUserRead) { + v.value = val + v.isSet = true +} + +func (v NullableAuthnMeUserRead) IsSet() bool { + return v.isSet +} + +func (v *NullableAuthnMeUserRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAuthnMeUserRead(val *AuthnMeUserRead) *NullableAuthnMeUserRead { + return &NullableAuthnMeUserRead{value: val, isSet: true} +} + +func (v NullableAuthnMeUserRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAuthnMeUserRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_assignment_report.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_assignment_report.go new file mode 100644 index 00000000..a1d13307 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_assignment_report.go @@ -0,0 +1,128 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the BulkRoleAssignmentReport type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &BulkRoleAssignmentReport{} + +// BulkRoleAssignmentReport struct for BulkRoleAssignmentReport +type BulkRoleAssignmentReport struct { + AssignmentsCreated *int32 `json:"assignments_created,omitempty"` +} + +// NewBulkRoleAssignmentReport instantiates a new BulkRoleAssignmentReport object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewBulkRoleAssignmentReport() *BulkRoleAssignmentReport { + this := BulkRoleAssignmentReport{} + var assignmentsCreated int32 = 0 + this.AssignmentsCreated = &assignmentsCreated + return &this +} + +// NewBulkRoleAssignmentReportWithDefaults instantiates a new BulkRoleAssignmentReport object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewBulkRoleAssignmentReportWithDefaults() *BulkRoleAssignmentReport { + this := BulkRoleAssignmentReport{} + var assignmentsCreated int32 = 0 + this.AssignmentsCreated = &assignmentsCreated + return &this +} + +// GetAssignmentsCreated returns the AssignmentsCreated field value if set, zero value otherwise. +func (o *BulkRoleAssignmentReport) GetAssignmentsCreated() int32 { + if o == nil || IsNil(o.AssignmentsCreated) { + var ret int32 + return ret + } + return *o.AssignmentsCreated +} + +// GetAssignmentsCreatedOk returns a tuple with the AssignmentsCreated field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *BulkRoleAssignmentReport) GetAssignmentsCreatedOk() (*int32, bool) { + if o == nil || IsNil(o.AssignmentsCreated) { + return nil, false + } + return o.AssignmentsCreated, true +} + +// HasAssignmentsCreated returns a boolean if a field has been set. +func (o *BulkRoleAssignmentReport) HasAssignmentsCreated() bool { + if o != nil && !IsNil(o.AssignmentsCreated) { + return true + } + + return false +} + +// SetAssignmentsCreated gets a reference to the given int32 and assigns it to the AssignmentsCreated field. +func (o *BulkRoleAssignmentReport) SetAssignmentsCreated(v int32) { + o.AssignmentsCreated = &v +} + +func (o BulkRoleAssignmentReport) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o BulkRoleAssignmentReport) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.AssignmentsCreated) { + toSerialize["assignments_created"] = o.AssignmentsCreated + } + return toSerialize, nil +} + +type NullableBulkRoleAssignmentReport struct { + value *BulkRoleAssignmentReport + isSet bool +} + +func (v NullableBulkRoleAssignmentReport) Get() *BulkRoleAssignmentReport { + return v.value +} + +func (v *NullableBulkRoleAssignmentReport) Set(val *BulkRoleAssignmentReport) { + v.value = val + v.isSet = true +} + +func (v NullableBulkRoleAssignmentReport) IsSet() bool { + return v.isSet +} + +func (v *NullableBulkRoleAssignmentReport) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBulkRoleAssignmentReport(val *BulkRoleAssignmentReport) *NullableBulkRoleAssignmentReport { + return &NullableBulkRoleAssignmentReport{value: val, isSet: true} +} + +func (v NullableBulkRoleAssignmentReport) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBulkRoleAssignmentReport) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_un_assignment_report.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_un_assignment_report.go new file mode 100644 index 00000000..0d8103c2 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_bulk_role_un_assignment_report.go @@ -0,0 +1,128 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the BulkRoleUnAssignmentReport type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &BulkRoleUnAssignmentReport{} + +// BulkRoleUnAssignmentReport struct for BulkRoleUnAssignmentReport +type BulkRoleUnAssignmentReport struct { + AssignmentsRemoved *int32 `json:"assignments_removed,omitempty"` +} + +// NewBulkRoleUnAssignmentReport instantiates a new BulkRoleUnAssignmentReport object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewBulkRoleUnAssignmentReport() *BulkRoleUnAssignmentReport { + this := BulkRoleUnAssignmentReport{} + var assignmentsRemoved int32 = 0 + this.AssignmentsRemoved = &assignmentsRemoved + return &this +} + +// NewBulkRoleUnAssignmentReportWithDefaults instantiates a new BulkRoleUnAssignmentReport object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewBulkRoleUnAssignmentReportWithDefaults() *BulkRoleUnAssignmentReport { + this := BulkRoleUnAssignmentReport{} + var assignmentsRemoved int32 = 0 + this.AssignmentsRemoved = &assignmentsRemoved + return &this +} + +// GetAssignmentsRemoved returns the AssignmentsRemoved field value if set, zero value otherwise. +func (o *BulkRoleUnAssignmentReport) GetAssignmentsRemoved() int32 { + if o == nil || IsNil(o.AssignmentsRemoved) { + var ret int32 + return ret + } + return *o.AssignmentsRemoved +} + +// GetAssignmentsRemovedOk returns a tuple with the AssignmentsRemoved field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *BulkRoleUnAssignmentReport) GetAssignmentsRemovedOk() (*int32, bool) { + if o == nil || IsNil(o.AssignmentsRemoved) { + return nil, false + } + return o.AssignmentsRemoved, true +} + +// HasAssignmentsRemoved returns a boolean if a field has been set. +func (o *BulkRoleUnAssignmentReport) HasAssignmentsRemoved() bool { + if o != nil && !IsNil(o.AssignmentsRemoved) { + return true + } + + return false +} + +// SetAssignmentsRemoved gets a reference to the given int32 and assigns it to the AssignmentsRemoved field. +func (o *BulkRoleUnAssignmentReport) SetAssignmentsRemoved(v int32) { + o.AssignmentsRemoved = &v +} + +func (o BulkRoleUnAssignmentReport) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o BulkRoleUnAssignmentReport) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.AssignmentsRemoved) { + toSerialize["assignments_removed"] = o.AssignmentsRemoved + } + return toSerialize, nil +} + +type NullableBulkRoleUnAssignmentReport struct { + value *BulkRoleUnAssignmentReport + isSet bool +} + +func (v NullableBulkRoleUnAssignmentReport) Get() *BulkRoleUnAssignmentReport { + return v.value +} + +func (v *NullableBulkRoleUnAssignmentReport) Set(val *BulkRoleUnAssignmentReport) { + v.value = val + v.isSet = true +} + +func (v NullableBulkRoleUnAssignmentReport) IsSet() bool { + return v.isSet +} + +func (v *NullableBulkRoleUnAssignmentReport) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBulkRoleUnAssignmentReport(val *BulkRoleUnAssignmentReport) *NullableBulkRoleUnAssignmentReport { + return &NullableBulkRoleUnAssignmentReport{value: val, isSet: true} +} + +func (v NullableBulkRoleUnAssignmentReport) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBulkRoleUnAssignmentReport) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_create.go new file mode 100644 index 00000000..55ccbc44 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_create.go @@ -0,0 +1,371 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ConditionSetCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetCreate{} + +// ConditionSetCreate struct for ConditionSetCreate +type ConditionSetCreate struct { + // A unique id by which Permit will identify the condition set. The key will be used as the generated rego rule name. + Key string `json:"key"` + Type *ConditionSetType `json:"type,omitempty"` + // whether the set was autogenerated by the system. + Autogenerated *bool `json:"autogenerated,omitempty"` + ResourceId *ResourceId `json:"resource_id,omitempty"` + // A descriptive name for the set, i.e: 'US based employees' or 'Users behind VPN' + Name string `json:"name"` + // an optional longer description of the set + Description *string `json:"description,omitempty"` + // a boolean expression that consists of multiple conditions, with and/or logic. + Conditions map[string]interface{} `json:"conditions,omitempty"` + ParentId *ParentId `json:"parent_id,omitempty"` +} + +// NewConditionSetCreate instantiates a new ConditionSetCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetCreate(key string, name string) *ConditionSetCreate { + this := ConditionSetCreate{} + this.Key = key + var type_ ConditionSetType = USERSET + this.Type = &type_ + var autogenerated bool = false + this.Autogenerated = &autogenerated + this.Name = name + return &this +} + +// NewConditionSetCreateWithDefaults instantiates a new ConditionSetCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetCreateWithDefaults() *ConditionSetCreate { + this := ConditionSetCreate{} + var type_ ConditionSetType = USERSET + this.Type = &type_ + var autogenerated bool = false + this.Autogenerated = &autogenerated + return &this +} + +// GetKey returns the Key field value +func (o *ConditionSetCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ConditionSetCreate) SetKey(v string) { + o.Key = v +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *ConditionSetCreate) GetType() ConditionSetType { + if o == nil || IsNil(o.Type) { + var ret ConditionSetType + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetTypeOk() (*ConditionSetType, bool) { + if o == nil || IsNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *ConditionSetCreate) HasType() bool { + if o != nil && !IsNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given ConditionSetType and assigns it to the Type field. +func (o *ConditionSetCreate) SetType(v ConditionSetType) { + o.Type = &v +} + +// GetAutogenerated returns the Autogenerated field value if set, zero value otherwise. +func (o *ConditionSetCreate) GetAutogenerated() bool { + if o == nil || IsNil(o.Autogenerated) { + var ret bool + return ret + } + return *o.Autogenerated +} + +// GetAutogeneratedOk returns a tuple with the Autogenerated field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetAutogeneratedOk() (*bool, bool) { + if o == nil || IsNil(o.Autogenerated) { + return nil, false + } + return o.Autogenerated, true +} + +// HasAutogenerated returns a boolean if a field has been set. +func (o *ConditionSetCreate) HasAutogenerated() bool { + if o != nil && !IsNil(o.Autogenerated) { + return true + } + + return false +} + +// SetAutogenerated gets a reference to the given bool and assigns it to the Autogenerated field. +func (o *ConditionSetCreate) SetAutogenerated(v bool) { + o.Autogenerated = &v +} + +// GetResourceId returns the ResourceId field value if set, zero value otherwise. +func (o *ConditionSetCreate) GetResourceId() ResourceId { + if o == nil || IsNil(o.ResourceId) { + var ret ResourceId + return ret + } + return *o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetResourceIdOk() (*ResourceId, bool) { + if o == nil || IsNil(o.ResourceId) { + return nil, false + } + return o.ResourceId, true +} + +// HasResourceId returns a boolean if a field has been set. +func (o *ConditionSetCreate) HasResourceId() bool { + if o != nil && !IsNil(o.ResourceId) { + return true + } + + return false +} + +// SetResourceId gets a reference to the given ResourceId and assigns it to the ResourceId field. +func (o *ConditionSetCreate) SetResourceId(v ResourceId) { + o.ResourceId = &v +} + +// GetName returns the Name field value +func (o *ConditionSetCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ConditionSetCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ConditionSetCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ConditionSetCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ConditionSetCreate) SetDescription(v string) { + o.Description = &v +} + +// GetConditions returns the Conditions field value if set, zero value otherwise. +func (o *ConditionSetCreate) GetConditions() map[string]interface{} { + if o == nil || IsNil(o.Conditions) { + var ret map[string]interface{} + return ret + } + return o.Conditions +} + +// GetConditionsOk returns a tuple with the Conditions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetConditionsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Conditions) { + return map[string]interface{}{}, false + } + return o.Conditions, true +} + +// HasConditions returns a boolean if a field has been set. +func (o *ConditionSetCreate) HasConditions() bool { + if o != nil && !IsNil(o.Conditions) { + return true + } + + return false +} + +// SetConditions gets a reference to the given map[string]interface{} and assigns it to the Conditions field. +func (o *ConditionSetCreate) SetConditions(v map[string]interface{}) { + o.Conditions = v +} + +// GetParentId returns the ParentId field value if set, zero value otherwise. +func (o *ConditionSetCreate) GetParentId() ParentId { + if o == nil || IsNil(o.ParentId) { + var ret ParentId + return ret + } + return *o.ParentId +} + +// GetParentIdOk returns a tuple with the ParentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetCreate) GetParentIdOk() (*ParentId, bool) { + if o == nil || IsNil(o.ParentId) { + return nil, false + } + return o.ParentId, true +} + +// HasParentId returns a boolean if a field has been set. +func (o *ConditionSetCreate) HasParentId() bool { + if o != nil && !IsNil(o.ParentId) { + return true + } + + return false +} + +// SetParentId gets a reference to the given ParentId and assigns it to the ParentId field. +func (o *ConditionSetCreate) SetParentId(v ParentId) { + o.ParentId = &v +} + +func (o ConditionSetCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + if !IsNil(o.Type) { + toSerialize["type"] = o.Type + } + if !IsNil(o.Autogenerated) { + toSerialize["autogenerated"] = o.Autogenerated + } + if !IsNil(o.ResourceId) { + toSerialize["resource_id"] = o.ResourceId + } + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Conditions) { + toSerialize["conditions"] = o.Conditions + } + if !IsNil(o.ParentId) { + toSerialize["parent_id"] = o.ParentId + } + return toSerialize, nil +} + +type NullableConditionSetCreate struct { + value *ConditionSetCreate + isSet bool +} + +func (v NullableConditionSetCreate) Get() *ConditionSetCreate { + return v.value +} + +func (v *NullableConditionSetCreate) Set(val *ConditionSetCreate) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetCreate(val *ConditionSetCreate) *NullableConditionSetCreate { + return &NullableConditionSetCreate{value: val, isSet: true} +} + +func (v NullableConditionSetCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_data.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_data.go new file mode 100644 index 00000000..91799bb5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_data.go @@ -0,0 +1,142 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ConditionSetData type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetData{} + +// ConditionSetData struct for ConditionSetData +type ConditionSetData struct { + Type ConditionSetType `json:"type"` + Key string `json:"key"` +} + +// NewConditionSetData instantiates a new ConditionSetData object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetData(type_ ConditionSetType, key string) *ConditionSetData { + this := ConditionSetData{} + this.Type = type_ + this.Key = key + return &this +} + +// NewConditionSetDataWithDefaults instantiates a new ConditionSetData object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetDataWithDefaults() *ConditionSetData { + this := ConditionSetData{} + return &this +} + +// GetType returns the Type field value +func (o *ConditionSetData) GetType() ConditionSetType { + if o == nil { + var ret ConditionSetType + return ret + } + + return o.Type +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +func (o *ConditionSetData) GetTypeOk() (*ConditionSetType, bool) { + if o == nil { + return nil, false + } + return &o.Type, true +} + +// SetType sets field value +func (o *ConditionSetData) SetType(v ConditionSetType) { + o.Type = v +} + +// GetKey returns the Key field value +func (o *ConditionSetData) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ConditionSetData) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ConditionSetData) SetKey(v string) { + o.Key = v +} + +func (o ConditionSetData) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetData) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["type"] = o.Type + toSerialize["key"] = o.Key + return toSerialize, nil +} + +type NullableConditionSetData struct { + value *ConditionSetData + isSet bool +} + +func (v NullableConditionSetData) Get() *ConditionSetData { + return v.value +} + +func (v *NullableConditionSetData) Set(val *ConditionSetData) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetData) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetData) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetData(val *ConditionSetData) *NullableConditionSetData { + return &NullableConditionSetData{value: val, isSet: true} +} + +func (v NullableConditionSetData) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetData) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_read.go new file mode 100644 index 00000000..4e810d7c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_read.go @@ -0,0 +1,576 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the ConditionSetRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetRead{} + +// ConditionSetRead struct for ConditionSetRead +type ConditionSetRead struct { + // A unique id by which Permit will identify the condition set. The key will be used as the generated rego rule name. + Key string `json:"key"` + Type *ConditionSetType `json:"type,omitempty"` + // whether the set was autogenerated by the system. + Autogenerated *bool `json:"autogenerated,omitempty"` + ResourceId *ResourceId `json:"resource_id,omitempty"` + // Unique id of the condition set + Id string `json:"id"` + // Unique id of the organization that the condition set belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the condition set belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the condition set belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the condition set was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the condition set was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + Resource *ResourceRead `json:"resource,omitempty"` + // A descriptive name for the set, i.e: 'US based employees' or 'Users behind VPN' + Name string `json:"name"` + // an optional longer description of the set + Description *string `json:"description,omitempty"` + // a boolean expression that consists of multiple conditions, with and/or logic. + Conditions map[string]interface{} `json:"conditions,omitempty"` + ParentId *ParentId `json:"parent_id,omitempty"` +} + +// NewConditionSetRead instantiates a new ConditionSetRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetRead(key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, name string) *ConditionSetRead { + this := ConditionSetRead{} + this.Key = key + var type_ ConditionSetType = USERSET + this.Type = &type_ + var autogenerated bool = false + this.Autogenerated = &autogenerated + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + return &this +} + +// NewConditionSetReadWithDefaults instantiates a new ConditionSetRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetReadWithDefaults() *ConditionSetRead { + this := ConditionSetRead{} + var type_ ConditionSetType = USERSET + this.Type = &type_ + var autogenerated bool = false + this.Autogenerated = &autogenerated + return &this +} + +// GetKey returns the Key field value +func (o *ConditionSetRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ConditionSetRead) SetKey(v string) { + o.Key = v +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *ConditionSetRead) GetType() ConditionSetType { + if o == nil || IsNil(o.Type) { + var ret ConditionSetType + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetTypeOk() (*ConditionSetType, bool) { + if o == nil || IsNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *ConditionSetRead) HasType() bool { + if o != nil && !IsNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given ConditionSetType and assigns it to the Type field. +func (o *ConditionSetRead) SetType(v ConditionSetType) { + o.Type = &v +} + +// GetAutogenerated returns the Autogenerated field value if set, zero value otherwise. +func (o *ConditionSetRead) GetAutogenerated() bool { + if o == nil || IsNil(o.Autogenerated) { + var ret bool + return ret + } + return *o.Autogenerated +} + +// GetAutogeneratedOk returns a tuple with the Autogenerated field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetAutogeneratedOk() (*bool, bool) { + if o == nil || IsNil(o.Autogenerated) { + return nil, false + } + return o.Autogenerated, true +} + +// HasAutogenerated returns a boolean if a field has been set. +func (o *ConditionSetRead) HasAutogenerated() bool { + if o != nil && !IsNil(o.Autogenerated) { + return true + } + + return false +} + +// SetAutogenerated gets a reference to the given bool and assigns it to the Autogenerated field. +func (o *ConditionSetRead) SetAutogenerated(v bool) { + o.Autogenerated = &v +} + +// GetResourceId returns the ResourceId field value if set, zero value otherwise. +func (o *ConditionSetRead) GetResourceId() ResourceId { + if o == nil || IsNil(o.ResourceId) { + var ret ResourceId + return ret + } + return *o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetResourceIdOk() (*ResourceId, bool) { + if o == nil || IsNil(o.ResourceId) { + return nil, false + } + return o.ResourceId, true +} + +// HasResourceId returns a boolean if a field has been set. +func (o *ConditionSetRead) HasResourceId() bool { + if o != nil && !IsNil(o.ResourceId) { + return true + } + + return false +} + +// SetResourceId gets a reference to the given ResourceId and assigns it to the ResourceId field. +func (o *ConditionSetRead) SetResourceId(v ResourceId) { + o.ResourceId = &v +} + +// GetId returns the Id field value +func (o *ConditionSetRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ConditionSetRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ConditionSetRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ConditionSetRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ConditionSetRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ConditionSetRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ConditionSetRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ConditionSetRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ConditionSetRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ConditionSetRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ConditionSetRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ConditionSetRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetResource returns the Resource field value if set, zero value otherwise. +func (o *ConditionSetRead) GetResource() ResourceRead { + if o == nil || IsNil(o.Resource) { + var ret ResourceRead + return ret + } + return *o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetResourceOk() (*ResourceRead, bool) { + if o == nil || IsNil(o.Resource) { + return nil, false + } + return o.Resource, true +} + +// HasResource returns a boolean if a field has been set. +func (o *ConditionSetRead) HasResource() bool { + if o != nil && !IsNil(o.Resource) { + return true + } + + return false +} + +// SetResource gets a reference to the given ResourceRead and assigns it to the Resource field. +func (o *ConditionSetRead) SetResource(v ResourceRead) { + o.Resource = &v +} + +// GetName returns the Name field value +func (o *ConditionSetRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ConditionSetRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ConditionSetRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ConditionSetRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ConditionSetRead) SetDescription(v string) { + o.Description = &v +} + +// GetConditions returns the Conditions field value if set, zero value otherwise. +func (o *ConditionSetRead) GetConditions() map[string]interface{} { + if o == nil || IsNil(o.Conditions) { + var ret map[string]interface{} + return ret + } + return o.Conditions +} + +// GetConditionsOk returns a tuple with the Conditions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetConditionsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Conditions) { + return map[string]interface{}{}, false + } + return o.Conditions, true +} + +// HasConditions returns a boolean if a field has been set. +func (o *ConditionSetRead) HasConditions() bool { + if o != nil && !IsNil(o.Conditions) { + return true + } + + return false +} + +// SetConditions gets a reference to the given map[string]interface{} and assigns it to the Conditions field. +func (o *ConditionSetRead) SetConditions(v map[string]interface{}) { + o.Conditions = v +} + +// GetParentId returns the ParentId field value if set, zero value otherwise. +func (o *ConditionSetRead) GetParentId() ParentId { + if o == nil || IsNil(o.ParentId) { + var ret ParentId + return ret + } + return *o.ParentId +} + +// GetParentIdOk returns a tuple with the ParentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRead) GetParentIdOk() (*ParentId, bool) { + if o == nil || IsNil(o.ParentId) { + return nil, false + } + return o.ParentId, true +} + +// HasParentId returns a boolean if a field has been set. +func (o *ConditionSetRead) HasParentId() bool { + if o != nil && !IsNil(o.ParentId) { + return true + } + + return false +} + +// SetParentId gets a reference to the given ParentId and assigns it to the ParentId field. +func (o *ConditionSetRead) SetParentId(v ParentId) { + o.ParentId = &v +} + +func (o ConditionSetRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + if !IsNil(o.Type) { + toSerialize["type"] = o.Type + } + if !IsNil(o.Autogenerated) { + toSerialize["autogenerated"] = o.Autogenerated + } + if !IsNil(o.ResourceId) { + toSerialize["resource_id"] = o.ResourceId + } + toSerialize["id"] = o.Id + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + if !IsNil(o.Resource) { + toSerialize["resource"] = o.Resource + } + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Conditions) { + toSerialize["conditions"] = o.Conditions + } + if !IsNil(o.ParentId) { + toSerialize["parent_id"] = o.ParentId + } + return toSerialize, nil +} + +type NullableConditionSetRead struct { + value *ConditionSetRead + isSet bool +} + +func (v NullableConditionSetRead) Get() *ConditionSetRead { + return v.value +} + +func (v *NullableConditionSetRead) Set(val *ConditionSetRead) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetRead) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetRead(val *ConditionSetRead) *NullableConditionSetRead { + return &NullableConditionSetRead{value: val, isSet: true} +} + +func (v NullableConditionSetRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_create.go new file mode 100644 index 00000000..86c508d4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_create.go @@ -0,0 +1,254 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ConditionSetRuleCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetRuleCreate{} + +// ConditionSetRuleCreate struct for ConditionSetRuleCreate +type ConditionSetRuleCreate struct { + // The userset that will be given permission, i.e: all the users matching this rule will be given the specified permission + UserSet string `json:"user_set"` + // The permission that will be granted to the userset *on* the resourceset. The permission can be either a resource action id, or `{resource_key}:{action_key}`, i.e: the \"permission name\". + Permission string `json:"permission"` + // The resourceset that represents the resources that are granted for access, i.e: all the resources matching this rule can be accessed by the userset to perform the granted *permission* + ResourceSet string `json:"resource_set"` + // if True, will set the condition set rule to the role's autogen user-set. + IsRole *bool `json:"is_role,omitempty"` + // if True, will set the condition set rule to the resource's autogen resource-set. + IsResource *bool `json:"is_resource,omitempty"` +} + +// NewConditionSetRuleCreate instantiates a new ConditionSetRuleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetRuleCreate(userSet string, permission string, resourceSet string) *ConditionSetRuleCreate { + this := ConditionSetRuleCreate{} + this.UserSet = userSet + this.Permission = permission + this.ResourceSet = resourceSet + var isRole bool = false + this.IsRole = &isRole + var isResource bool = false + this.IsResource = &isResource + return &this +} + +// NewConditionSetRuleCreateWithDefaults instantiates a new ConditionSetRuleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetRuleCreateWithDefaults() *ConditionSetRuleCreate { + this := ConditionSetRuleCreate{} + var isRole bool = false + this.IsRole = &isRole + var isResource bool = false + this.IsResource = &isResource + return &this +} + +// GetUserSet returns the UserSet field value +func (o *ConditionSetRuleCreate) GetUserSet() string { + if o == nil { + var ret string + return ret + } + + return o.UserSet +} + +// GetUserSetOk returns a tuple with the UserSet field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleCreate) GetUserSetOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.UserSet, true +} + +// SetUserSet sets field value +func (o *ConditionSetRuleCreate) SetUserSet(v string) { + o.UserSet = v +} + +// GetPermission returns the Permission field value +func (o *ConditionSetRuleCreate) GetPermission() string { + if o == nil { + var ret string + return ret + } + + return o.Permission +} + +// GetPermissionOk returns a tuple with the Permission field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleCreate) GetPermissionOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Permission, true +} + +// SetPermission sets field value +func (o *ConditionSetRuleCreate) SetPermission(v string) { + o.Permission = v +} + +// GetResourceSet returns the ResourceSet field value +func (o *ConditionSetRuleCreate) GetResourceSet() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceSet +} + +// GetResourceSetOk returns a tuple with the ResourceSet field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleCreate) GetResourceSetOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceSet, true +} + +// SetResourceSet sets field value +func (o *ConditionSetRuleCreate) SetResourceSet(v string) { + o.ResourceSet = v +} + +// GetIsRole returns the IsRole field value if set, zero value otherwise. +func (o *ConditionSetRuleCreate) GetIsRole() bool { + if o == nil || IsNil(o.IsRole) { + var ret bool + return ret + } + return *o.IsRole +} + +// GetIsRoleOk returns a tuple with the IsRole field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleCreate) GetIsRoleOk() (*bool, bool) { + if o == nil || IsNil(o.IsRole) { + return nil, false + } + return o.IsRole, true +} + +// HasIsRole returns a boolean if a field has been set. +func (o *ConditionSetRuleCreate) HasIsRole() bool { + if o != nil && !IsNil(o.IsRole) { + return true + } + + return false +} + +// SetIsRole gets a reference to the given bool and assigns it to the IsRole field. +func (o *ConditionSetRuleCreate) SetIsRole(v bool) { + o.IsRole = &v +} + +// GetIsResource returns the IsResource field value if set, zero value otherwise. +func (o *ConditionSetRuleCreate) GetIsResource() bool { + if o == nil || IsNil(o.IsResource) { + var ret bool + return ret + } + return *o.IsResource +} + +// GetIsResourceOk returns a tuple with the IsResource field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleCreate) GetIsResourceOk() (*bool, bool) { + if o == nil || IsNil(o.IsResource) { + return nil, false + } + return o.IsResource, true +} + +// HasIsResource returns a boolean if a field has been set. +func (o *ConditionSetRuleCreate) HasIsResource() bool { + if o != nil && !IsNil(o.IsResource) { + return true + } + + return false +} + +// SetIsResource gets a reference to the given bool and assigns it to the IsResource field. +func (o *ConditionSetRuleCreate) SetIsResource(v bool) { + o.IsResource = &v +} + +func (o ConditionSetRuleCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetRuleCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["user_set"] = o.UserSet + toSerialize["permission"] = o.Permission + toSerialize["resource_set"] = o.ResourceSet + if !IsNil(o.IsRole) { + toSerialize["is_role"] = o.IsRole + } + if !IsNil(o.IsResource) { + toSerialize["is_resource"] = o.IsResource + } + return toSerialize, nil +} + +type NullableConditionSetRuleCreate struct { + value *ConditionSetRuleCreate + isSet bool +} + +func (v NullableConditionSetRuleCreate) Get() *ConditionSetRuleCreate { + return v.value +} + +func (v *NullableConditionSetRuleCreate) Set(val *ConditionSetRuleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetRuleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetRuleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetRuleCreate(val *ConditionSetRuleCreate) *NullableConditionSetRuleCreate { + return &NullableConditionSetRuleCreate{value: val, isSet: true} +} + +func (v NullableConditionSetRuleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetRuleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_read.go new file mode 100644 index 00000000..205ff7c6 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_read.go @@ -0,0 +1,369 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the ConditionSetRuleRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetRuleRead{} + +// ConditionSetRuleRead struct for ConditionSetRuleRead +type ConditionSetRuleRead struct { + // Unique id of the condition set rule + Id string `json:"id"` + // A unique id by which Permit will identify this condition set rule. + Key string `json:"key"` + // the userset that is currently granted permissions, i.e: all the users matching this rule are granted the permission on the resourceset + UserSet string `json:"user_set"` + // a permission that is currently granted to the userset *on* the resourceset. + Permission string `json:"permission"` + // the resourceset that represents the resources that are currently granted for access, i.e: all the resources matching this rule can be accessed by the userset to perform the granted *permission* + ResourceSet string `json:"resource_set"` + // Unique id of the organization that the condition set rule belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the condition set rule belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the condition set rule belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the condition set rule was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the condition set rule was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` +} + +// NewConditionSetRuleRead instantiates a new ConditionSetRuleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetRuleRead(id string, key string, userSet string, permission string, resourceSet string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time) *ConditionSetRuleRead { + this := ConditionSetRuleRead{} + this.Id = id + this.Key = key + this.UserSet = userSet + this.Permission = permission + this.ResourceSet = resourceSet + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewConditionSetRuleReadWithDefaults instantiates a new ConditionSetRuleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetRuleReadWithDefaults() *ConditionSetRuleRead { + this := ConditionSetRuleRead{} + return &this +} + +// GetId returns the Id field value +func (o *ConditionSetRuleRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ConditionSetRuleRead) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *ConditionSetRuleRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ConditionSetRuleRead) SetKey(v string) { + o.Key = v +} + +// GetUserSet returns the UserSet field value +func (o *ConditionSetRuleRead) GetUserSet() string { + if o == nil { + var ret string + return ret + } + + return o.UserSet +} + +// GetUserSetOk returns a tuple with the UserSet field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetUserSetOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.UserSet, true +} + +// SetUserSet sets field value +func (o *ConditionSetRuleRead) SetUserSet(v string) { + o.UserSet = v +} + +// GetPermission returns the Permission field value +func (o *ConditionSetRuleRead) GetPermission() string { + if o == nil { + var ret string + return ret + } + + return o.Permission +} + +// GetPermissionOk returns a tuple with the Permission field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetPermissionOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Permission, true +} + +// SetPermission sets field value +func (o *ConditionSetRuleRead) SetPermission(v string) { + o.Permission = v +} + +// GetResourceSet returns the ResourceSet field value +func (o *ConditionSetRuleRead) GetResourceSet() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceSet +} + +// GetResourceSetOk returns a tuple with the ResourceSet field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetResourceSetOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceSet, true +} + +// SetResourceSet sets field value +func (o *ConditionSetRuleRead) SetResourceSet(v string) { + o.ResourceSet = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ConditionSetRuleRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ConditionSetRuleRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ConditionSetRuleRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ConditionSetRuleRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ConditionSetRuleRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ConditionSetRuleRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ConditionSetRuleRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ConditionSetRuleRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ConditionSetRuleRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ConditionSetRuleRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +func (o ConditionSetRuleRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetRuleRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["key"] = o.Key + toSerialize["user_set"] = o.UserSet + toSerialize["permission"] = o.Permission + toSerialize["resource_set"] = o.ResourceSet + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + return toSerialize, nil +} + +type NullableConditionSetRuleRead struct { + value *ConditionSetRuleRead + isSet bool +} + +func (v NullableConditionSetRuleRead) Get() *ConditionSetRuleRead { + return v.value +} + +func (v *NullableConditionSetRuleRead) Set(val *ConditionSetRuleRead) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetRuleRead) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetRuleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetRuleRead(val *ConditionSetRuleRead) *NullableConditionSetRuleRead { + return &NullableConditionSetRuleRead{value: val, isSet: true} +} + +func (v NullableConditionSetRuleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetRuleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_remove.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_remove.go new file mode 100644 index 00000000..36fea383 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_rule_remove.go @@ -0,0 +1,254 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ConditionSetRuleRemove type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetRuleRemove{} + +// ConditionSetRuleRemove struct for ConditionSetRuleRemove +type ConditionSetRuleRemove struct { + // The userset that will be unassigned these permission, i.e: all the users matching this rule will lose the specified permission + UserSet string `json:"user_set"` + // The permission that will be removed from the userset *on* the resourceset. The permission can be either a resource action id, or `{resource_key}:{action_key}`, i.e: the \"permission name\". + Permission string `json:"permission"` + // The resourceset that represents the resources that are no longer granted for access, i.e: all the resources matching this rule can no longer be accessed by the userset, and will be revoked the specified *permission* + ResourceSet string `json:"resource_set"` + // if True, will set the condition set rule to the role's autogen user-set. + IsRole *bool `json:"is_role,omitempty"` + // if True, will set the condition set rule to the resource's autogen resource-set. + IsResource *bool `json:"is_resource,omitempty"` +} + +// NewConditionSetRuleRemove instantiates a new ConditionSetRuleRemove object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetRuleRemove(userSet string, permission string, resourceSet string) *ConditionSetRuleRemove { + this := ConditionSetRuleRemove{} + this.UserSet = userSet + this.Permission = permission + this.ResourceSet = resourceSet + var isRole bool = false + this.IsRole = &isRole + var isResource bool = false + this.IsResource = &isResource + return &this +} + +// NewConditionSetRuleRemoveWithDefaults instantiates a new ConditionSetRuleRemove object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetRuleRemoveWithDefaults() *ConditionSetRuleRemove { + this := ConditionSetRuleRemove{} + var isRole bool = false + this.IsRole = &isRole + var isResource bool = false + this.IsResource = &isResource + return &this +} + +// GetUserSet returns the UserSet field value +func (o *ConditionSetRuleRemove) GetUserSet() string { + if o == nil { + var ret string + return ret + } + + return o.UserSet +} + +// GetUserSetOk returns a tuple with the UserSet field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRemove) GetUserSetOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.UserSet, true +} + +// SetUserSet sets field value +func (o *ConditionSetRuleRemove) SetUserSet(v string) { + o.UserSet = v +} + +// GetPermission returns the Permission field value +func (o *ConditionSetRuleRemove) GetPermission() string { + if o == nil { + var ret string + return ret + } + + return o.Permission +} + +// GetPermissionOk returns a tuple with the Permission field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRemove) GetPermissionOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Permission, true +} + +// SetPermission sets field value +func (o *ConditionSetRuleRemove) SetPermission(v string) { + o.Permission = v +} + +// GetResourceSet returns the ResourceSet field value +func (o *ConditionSetRuleRemove) GetResourceSet() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceSet +} + +// GetResourceSetOk returns a tuple with the ResourceSet field value +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRemove) GetResourceSetOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceSet, true +} + +// SetResourceSet sets field value +func (o *ConditionSetRuleRemove) SetResourceSet(v string) { + o.ResourceSet = v +} + +// GetIsRole returns the IsRole field value if set, zero value otherwise. +func (o *ConditionSetRuleRemove) GetIsRole() bool { + if o == nil || IsNil(o.IsRole) { + var ret bool + return ret + } + return *o.IsRole +} + +// GetIsRoleOk returns a tuple with the IsRole field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRemove) GetIsRoleOk() (*bool, bool) { + if o == nil || IsNil(o.IsRole) { + return nil, false + } + return o.IsRole, true +} + +// HasIsRole returns a boolean if a field has been set. +func (o *ConditionSetRuleRemove) HasIsRole() bool { + if o != nil && !IsNil(o.IsRole) { + return true + } + + return false +} + +// SetIsRole gets a reference to the given bool and assigns it to the IsRole field. +func (o *ConditionSetRuleRemove) SetIsRole(v bool) { + o.IsRole = &v +} + +// GetIsResource returns the IsResource field value if set, zero value otherwise. +func (o *ConditionSetRuleRemove) GetIsResource() bool { + if o == nil || IsNil(o.IsResource) { + var ret bool + return ret + } + return *o.IsResource +} + +// GetIsResourceOk returns a tuple with the IsResource field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetRuleRemove) GetIsResourceOk() (*bool, bool) { + if o == nil || IsNil(o.IsResource) { + return nil, false + } + return o.IsResource, true +} + +// HasIsResource returns a boolean if a field has been set. +func (o *ConditionSetRuleRemove) HasIsResource() bool { + if o != nil && !IsNil(o.IsResource) { + return true + } + + return false +} + +// SetIsResource gets a reference to the given bool and assigns it to the IsResource field. +func (o *ConditionSetRuleRemove) SetIsResource(v bool) { + o.IsResource = &v +} + +func (o ConditionSetRuleRemove) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetRuleRemove) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["user_set"] = o.UserSet + toSerialize["permission"] = o.Permission + toSerialize["resource_set"] = o.ResourceSet + if !IsNil(o.IsRole) { + toSerialize["is_role"] = o.IsRole + } + if !IsNil(o.IsResource) { + toSerialize["is_resource"] = o.IsResource + } + return toSerialize, nil +} + +type NullableConditionSetRuleRemove struct { + value *ConditionSetRuleRemove + isSet bool +} + +func (v NullableConditionSetRuleRemove) Get() *ConditionSetRuleRemove { + return v.value +} + +func (v *NullableConditionSetRuleRemove) Set(val *ConditionSetRuleRemove) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetRuleRemove) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetRuleRemove) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetRuleRemove(val *ConditionSetRuleRemove) *NullableConditionSetRuleRemove { + return &NullableConditionSetRuleRemove{value: val, isSet: true} +} + +func (v NullableConditionSetRuleRemove) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetRuleRemove) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_type.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_type.go new file mode 100644 index 00000000..311a3630 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_type.go @@ -0,0 +1,110 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ConditionSetType An enumeration. +type ConditionSetType string + +// List of ConditionSetType +const ( + USERSET ConditionSetType = "userset" + RESOURCESET ConditionSetType = "resourceset" +) + +// All allowed values of ConditionSetType enum +var AllowedConditionSetTypeEnumValues = []ConditionSetType{ + "userset", + "resourceset", +} + +func (v *ConditionSetType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ConditionSetType(value) + for _, existing := range AllowedConditionSetTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ConditionSetType", value) +} + +// NewConditionSetTypeFromValue returns a pointer to a valid ConditionSetType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewConditionSetTypeFromValue(v string) (*ConditionSetType, error) { + ev := ConditionSetType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ConditionSetType: valid values are %v", v, AllowedConditionSetTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ConditionSetType) IsValid() bool { + for _, existing := range AllowedConditionSetTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ConditionSetType value +func (v ConditionSetType) Ptr() *ConditionSetType { + return &v +} + +type NullableConditionSetType struct { + value *ConditionSetType + isSet bool +} + +func (v NullableConditionSetType) Get() *ConditionSetType { + return v.value +} + +func (v *NullableConditionSetType) Set(val *ConditionSetType) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetType) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetType(val *ConditionSetType) *NullableConditionSetType { + return &NullableConditionSetType{value: val, isSet: true} +} + +func (v NullableConditionSetType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_update.go new file mode 100644 index 00000000..e5c621e5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_condition_set_update.go @@ -0,0 +1,235 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ConditionSetUpdate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ConditionSetUpdate{} + +// ConditionSetUpdate struct for ConditionSetUpdate +type ConditionSetUpdate struct { + // A descriptive name for the set, i.e: 'US based employees' or 'Users behind VPN' + Name *string `json:"name,omitempty"` + // an optional longer description of the set + Description *string `json:"description,omitempty"` + // a boolean expression that consists of multiple conditions, with and/or logic. + Conditions map[string]interface{} `json:"conditions,omitempty"` + ParentId *ParentId `json:"parent_id,omitempty"` +} + +// NewConditionSetUpdate instantiates a new ConditionSetUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConditionSetUpdate() *ConditionSetUpdate { + this := ConditionSetUpdate{} + return &this +} + +// NewConditionSetUpdateWithDefaults instantiates a new ConditionSetUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConditionSetUpdateWithDefaults() *ConditionSetUpdate { + this := ConditionSetUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ConditionSetUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ConditionSetUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ConditionSetUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ConditionSetUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ConditionSetUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ConditionSetUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetConditions returns the Conditions field value if set, zero value otherwise. +func (o *ConditionSetUpdate) GetConditions() map[string]interface{} { + if o == nil || IsNil(o.Conditions) { + var ret map[string]interface{} + return ret + } + return o.Conditions +} + +// GetConditionsOk returns a tuple with the Conditions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetUpdate) GetConditionsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Conditions) { + return map[string]interface{}{}, false + } + return o.Conditions, true +} + +// HasConditions returns a boolean if a field has been set. +func (o *ConditionSetUpdate) HasConditions() bool { + if o != nil && !IsNil(o.Conditions) { + return true + } + + return false +} + +// SetConditions gets a reference to the given map[string]interface{} and assigns it to the Conditions field. +func (o *ConditionSetUpdate) SetConditions(v map[string]interface{}) { + o.Conditions = v +} + +// GetParentId returns the ParentId field value if set, zero value otherwise. +func (o *ConditionSetUpdate) GetParentId() ParentId { + if o == nil || IsNil(o.ParentId) { + var ret ParentId + return ret + } + return *o.ParentId +} + +// GetParentIdOk returns a tuple with the ParentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ConditionSetUpdate) GetParentIdOk() (*ParentId, bool) { + if o == nil || IsNil(o.ParentId) { + return nil, false + } + return o.ParentId, true +} + +// HasParentId returns a boolean if a field has been set. +func (o *ConditionSetUpdate) HasParentId() bool { + if o != nil && !IsNil(o.ParentId) { + return true + } + + return false +} + +// SetParentId gets a reference to the given ParentId and assigns it to the ParentId field. +func (o *ConditionSetUpdate) SetParentId(v ParentId) { + o.ParentId = &v +} + +func (o ConditionSetUpdate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ConditionSetUpdate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Conditions) { + toSerialize["conditions"] = o.Conditions + } + if !IsNil(o.ParentId) { + toSerialize["parent_id"] = o.ParentId + } + return toSerialize, nil +} + +type NullableConditionSetUpdate struct { + value *ConditionSetUpdate + isSet bool +} + +func (v NullableConditionSetUpdate) Get() *ConditionSetUpdate { + return v.value +} + +func (v *NullableConditionSetUpdate) Set(val *ConditionSetUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableConditionSetUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableConditionSetUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConditionSetUpdate(val *ConditionSetUpdate) *NullableConditionSetUpdate { + return &NullableConditionSetUpdate{value: val, isSet: true} +} + +func (v NullableConditionSetUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConditionSetUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_copy_environment_scope_roles.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_copy_environment_scope_roles.go new file mode 100644 index 00000000..92c6f988 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_copy_environment_scope_roles.go @@ -0,0 +1,162 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the CopyEnvironmentScopeRoles type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &CopyEnvironmentScopeRoles{} + +// CopyEnvironmentScopeRoles CopyEnvironmentScopeRoles to copy +type CopyEnvironmentScopeRoles struct { + // Objects to include (use * as wildcard) + Include []string `json:"include,omitempty"` + // Object to exclude (use * as wildcard) + Exclude []string `json:"exclude,omitempty"` +} + +// NewCopyEnvironmentScopeRoles instantiates a new CopyEnvironmentScopeRoles object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewCopyEnvironmentScopeRoles() *CopyEnvironmentScopeRoles { + this := CopyEnvironmentScopeRoles{} + return &this +} + +// NewCopyEnvironmentScopeRolesWithDefaults instantiates a new CopyEnvironmentScopeRoles object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewCopyEnvironmentScopeRolesWithDefaults() *CopyEnvironmentScopeRoles { + this := CopyEnvironmentScopeRoles{} + return &this +} + +// GetInclude returns the Include field value if set, zero value otherwise. +func (o *CopyEnvironmentScopeRoles) GetInclude() []string { + if o == nil || IsNil(o.Include) { + var ret []string + return ret + } + return o.Include +} + +// GetIncludeOk returns a tuple with the Include field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *CopyEnvironmentScopeRoles) GetIncludeOk() ([]string, bool) { + if o == nil || IsNil(o.Include) { + return nil, false + } + return o.Include, true +} + +// HasInclude returns a boolean if a field has been set. +func (o *CopyEnvironmentScopeRoles) HasInclude() bool { + if o != nil && !IsNil(o.Include) { + return true + } + + return false +} + +// SetInclude gets a reference to the given []string and assigns it to the Include field. +func (o *CopyEnvironmentScopeRoles) SetInclude(v []string) { + o.Include = v +} + +// GetExclude returns the Exclude field value if set, zero value otherwise. +func (o *CopyEnvironmentScopeRoles) GetExclude() []string { + if o == nil || IsNil(o.Exclude) { + var ret []string + return ret + } + return o.Exclude +} + +// GetExcludeOk returns a tuple with the Exclude field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *CopyEnvironmentScopeRoles) GetExcludeOk() ([]string, bool) { + if o == nil || IsNil(o.Exclude) { + return nil, false + } + return o.Exclude, true +} + +// HasExclude returns a boolean if a field has been set. +func (o *CopyEnvironmentScopeRoles) HasExclude() bool { + if o != nil && !IsNil(o.Exclude) { + return true + } + + return false +} + +// SetExclude gets a reference to the given []string and assigns it to the Exclude field. +func (o *CopyEnvironmentScopeRoles) SetExclude(v []string) { + o.Exclude = v +} + +func (o CopyEnvironmentScopeRoles) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o CopyEnvironmentScopeRoles) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Include) { + toSerialize["include"] = o.Include + } + if !IsNil(o.Exclude) { + toSerialize["exclude"] = o.Exclude + } + return toSerialize, nil +} + +type NullableCopyEnvironmentScopeRoles struct { + value *CopyEnvironmentScopeRoles + isSet bool +} + +func (v NullableCopyEnvironmentScopeRoles) Get() *CopyEnvironmentScopeRoles { + return v.value +} + +func (v *NullableCopyEnvironmentScopeRoles) Set(val *CopyEnvironmentScopeRoles) { + v.value = val + v.isSet = true +} + +func (v NullableCopyEnvironmentScopeRoles) IsSet() bool { + return v.isSet +} + +func (v *NullableCopyEnvironmentScopeRoles) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableCopyEnvironmentScopeRoles(val *CopyEnvironmentScopeRoles) *NullableCopyEnvironmentScopeRoles { + return &NullableCopyEnvironmentScopeRoles{value: val, isSet: true} +} + +func (v NullableCopyEnvironmentScopeRoles) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableCopyEnvironmentScopeRoles) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_config.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_config.go new file mode 100644 index 00000000..c36caefa --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_config.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// DataSourceConfig Static list of Data Source Entries returned to client. Answers this question for the client: from where should i get the full picture of data i need? (as opposed to incremental data updates) +type DataSourceConfig struct { + // list of data sources and how to fetch from them + Entries []DataSourceEntry `json:"entries"` +} + +// NewDataSourceConfig instantiates a new DataSourceConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDataSourceConfig(entries []DataSourceEntry) *DataSourceConfig { + this := DataSourceConfig{} + this.Entries = entries + return &this +} + +// NewDataSourceConfigWithDefaults instantiates a new DataSourceConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDataSourceConfigWithDefaults() *DataSourceConfig { + this := DataSourceConfig{} + return &this +} + +// GetEntries returns the Entries field value +func (o *DataSourceConfig) GetEntries() []DataSourceEntry { + if o == nil { + var ret []DataSourceEntry + return ret + } + + return o.Entries +} + +// GetEntriesOk returns a tuple with the Entries field value +// and a boolean to check if the value has been set. +func (o *DataSourceConfig) GetEntriesOk() ([]DataSourceEntry, bool) { + if o == nil { + return nil, false + } + return o.Entries, true +} + +// SetEntries sets field value +func (o *DataSourceConfig) SetEntries(v []DataSourceEntry) { + o.Entries = v +} + +func (o DataSourceConfig) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["entries"] = o.Entries + } + return json.Marshal(toSerialize) +} + +type NullableDataSourceConfig struct { + value *DataSourceConfig + isSet bool +} + +func (v NullableDataSourceConfig) Get() *DataSourceConfig { + return v.value +} + +func (v *NullableDataSourceConfig) Set(val *DataSourceConfig) { + v.value = val + v.isSet = true +} + +func (v NullableDataSourceConfig) IsSet() bool { + return v.isSet +} + +func (v *NullableDataSourceConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDataSourceConfig(val *DataSourceConfig) *NullableDataSourceConfig { + return &NullableDataSourceConfig{value: val, isSet: true} +} + +func (v NullableDataSourceConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDataSourceConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_entry.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_entry.go new file mode 100644 index 00000000..7e64d9ef --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_data_source_entry.go @@ -0,0 +1,263 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// DataSourceEntry Data source configuration - where client's should retrive data from and how they should store it +type DataSourceEntry struct { + // Url source to query for data + Url string `json:"url"` + // Suggested fetcher configuration (e.g. auth or method) to fetch data with + Config map[string]interface{} `json:"config,omitempty"` + // topics the data applies to + Topics []string `json:"topics,omitempty"` + // OPA data api path to store the document at + DstPath *string `json:"dst_path,omitempty"` + // Method used to write into OPA - PUT/PATCH + SaveMethod *string `json:"save_method,omitempty"` +} + +// NewDataSourceEntry instantiates a new DataSourceEntry object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDataSourceEntry(url string) *DataSourceEntry { + this := DataSourceEntry{} + this.Url = url + var dstPath string = "" + this.DstPath = &dstPath + var saveMethod string = "PUT" + this.SaveMethod = &saveMethod + return &this +} + +// NewDataSourceEntryWithDefaults instantiates a new DataSourceEntry object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDataSourceEntryWithDefaults() *DataSourceEntry { + this := DataSourceEntry{} + var dstPath string = "" + this.DstPath = &dstPath + var saveMethod string = "PUT" + this.SaveMethod = &saveMethod + return &this +} + +// GetUrl returns the Url field value +func (o *DataSourceEntry) GetUrl() string { + if o == nil { + var ret string + return ret + } + + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value +// and a boolean to check if the value has been set. +func (o *DataSourceEntry) GetUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Url, true +} + +// SetUrl sets field value +func (o *DataSourceEntry) SetUrl(v string) { + o.Url = v +} + +// GetConfig returns the Config field value if set, zero value otherwise. +func (o *DataSourceEntry) GetConfig() map[string]interface{} { + if o == nil || IsNil(o.Config) { + var ret map[string]interface{} + return ret + } + return o.Config +} + +// GetConfigOk returns a tuple with the Config field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DataSourceEntry) GetConfigOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Config) { + return map[string]interface{}{}, false + } + return o.Config, true +} + +// HasConfig returns a boolean if a field has been set. +func (o *DataSourceEntry) HasConfig() bool { + if o != nil && !IsNil(o.Config) { + return true + } + + return false +} + +// SetConfig gets a reference to the given map[string]interface{} and assigns it to the Config field. +func (o *DataSourceEntry) SetConfig(v map[string]interface{}) { + o.Config = v +} + +// GetTopics returns the Topics field value if set, zero value otherwise. +func (o *DataSourceEntry) GetTopics() []string { + if o == nil || IsNil(o.Topics) { + var ret []string + return ret + } + return o.Topics +} + +// GetTopicsOk returns a tuple with the Topics field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DataSourceEntry) GetTopicsOk() ([]string, bool) { + if o == nil || IsNil(o.Topics) { + return nil, false + } + return o.Topics, true +} + +// HasTopics returns a boolean if a field has been set. +func (o *DataSourceEntry) HasTopics() bool { + if o != nil && !IsNil(o.Topics) { + return true + } + + return false +} + +// SetTopics gets a reference to the given []string and assigns it to the Topics field. +func (o *DataSourceEntry) SetTopics(v []string) { + o.Topics = v +} + +// GetDstPath returns the DstPath field value if set, zero value otherwise. +func (o *DataSourceEntry) GetDstPath() string { + if o == nil || IsNil(o.DstPath) { + var ret string + return ret + } + return *o.DstPath +} + +// GetDstPathOk returns a tuple with the DstPath field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DataSourceEntry) GetDstPathOk() (*string, bool) { + if o == nil || IsNil(o.DstPath) { + return nil, false + } + return o.DstPath, true +} + +// HasDstPath returns a boolean if a field has been set. +func (o *DataSourceEntry) HasDstPath() bool { + if o != nil && !IsNil(o.DstPath) { + return true + } + + return false +} + +// SetDstPath gets a reference to the given string and assigns it to the DstPath field. +func (o *DataSourceEntry) SetDstPath(v string) { + o.DstPath = &v +} + +// GetSaveMethod returns the SaveMethod field value if set, zero value otherwise. +func (o *DataSourceEntry) GetSaveMethod() string { + if o == nil || IsNil(o.SaveMethod) { + var ret string + return ret + } + return *o.SaveMethod +} + +// GetSaveMethodOk returns a tuple with the SaveMethod field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DataSourceEntry) GetSaveMethodOk() (*string, bool) { + if o == nil || IsNil(o.SaveMethod) { + return nil, false + } + return o.SaveMethod, true +} + +// HasSaveMethod returns a boolean if a field has been set. +func (o *DataSourceEntry) HasSaveMethod() bool { + if o != nil && !IsNil(o.SaveMethod) { + return true + } + + return false +} + +// SetSaveMethod gets a reference to the given string and assigns it to the SaveMethod field. +func (o *DataSourceEntry) SetSaveMethod(v string) { + o.SaveMethod = &v +} + +func (o DataSourceEntry) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["url"] = o.Url + } + if !IsNil(o.Config) { + toSerialize["config"] = o.Config + } + if !IsNil(o.Topics) { + toSerialize["topics"] = o.Topics + } + if !IsNil(o.DstPath) { + toSerialize["dst_path"] = o.DstPath + } + if !IsNil(o.SaveMethod) { + toSerialize["save_method"] = o.SaveMethod + } + return json.Marshal(toSerialize) +} + +type NullableDataSourceEntry struct { + value *DataSourceEntry + isSet bool +} + +func (v NullableDataSourceEntry) Get() *DataSourceEntry { + return v.value +} + +func (v *NullableDataSourceEntry) Set(val *DataSourceEntry) { + v.value = val + v.isSet = true +} + +func (v NullableDataSourceEntry) IsSet() bool { + return v.isSet +} + +func (v *NullableDataSourceEntry) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDataSourceEntry(val *DataSourceEntry) *NullableDataSourceEntry { + return &NullableDataSourceEntry{value: val, isSet: true} +} + +func (v NullableDataSourceEntry) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDataSourceEntry) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role.go new file mode 100644 index 00000000..6d40dde5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role.go @@ -0,0 +1,178 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRole type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRole{} + +// DerivedRole struct for DerivedRole +type DerivedRole struct { + Conditions *string `json:"conditions,omitempty"` + Settings PermitBackendSchemasSchemaOpalDataDerivationSettings `json:"settings"` + Rules []DerivedRoleRule `json:"rules"` +} + +// NewDerivedRole instantiates a new DerivedRole object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRole(settings PermitBackendSchemasSchemaOpalDataDerivationSettings, rules []DerivedRoleRule) *DerivedRole { + this := DerivedRole{} + this.Settings = settings + this.Rules = rules + return &this +} + +// NewDerivedRoleWithDefaults instantiates a new DerivedRole object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleWithDefaults() *DerivedRole { + this := DerivedRole{} + return &this +} + +// GetConditions returns the Conditions field value if set, zero value otherwise. +func (o *DerivedRole) GetConditions() string { + if o == nil || IsNil(o.Conditions) { + var ret string + return ret + } + return *o.Conditions +} + +// GetConditionsOk returns a tuple with the Conditions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRole) GetConditionsOk() (*string, bool) { + if o == nil || IsNil(o.Conditions) { + return nil, false + } + return o.Conditions, true +} + +// HasConditions returns a boolean if a field has been set. +func (o *DerivedRole) HasConditions() bool { + if o != nil && !IsNil(o.Conditions) { + return true + } + + return false +} + +// SetConditions gets a reference to the given string and assigns it to the Conditions field. +func (o *DerivedRole) SetConditions(v string) { + o.Conditions = &v +} + +// GetSettings returns the Settings field value +func (o *DerivedRole) GetSettings() PermitBackendSchemasSchemaOpalDataDerivationSettings { + if o == nil { + var ret PermitBackendSchemasSchemaOpalDataDerivationSettings + return ret + } + + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value +// and a boolean to check if the value has been set. +func (o *DerivedRole) GetSettingsOk() (*PermitBackendSchemasSchemaOpalDataDerivationSettings, bool) { + if o == nil { + return nil, false + } + return &o.Settings, true +} + +// SetSettings sets field value +func (o *DerivedRole) SetSettings(v PermitBackendSchemasSchemaOpalDataDerivationSettings) { + o.Settings = v +} + +// GetRules returns the Rules field value +func (o *DerivedRole) GetRules() []DerivedRoleRule { + if o == nil { + var ret []DerivedRoleRule + return ret + } + + return o.Rules +} + +// GetRulesOk returns a tuple with the Rules field value +// and a boolean to check if the value has been set. +func (o *DerivedRole) GetRulesOk() ([]DerivedRoleRule, bool) { + if o == nil { + return nil, false + } + return o.Rules, true +} + +// SetRules sets field value +func (o *DerivedRole) SetRules(v []DerivedRoleRule) { + o.Rules = v +} + +func (o DerivedRole) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRole) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Conditions) { + toSerialize["conditions"] = o.Conditions + } + toSerialize["settings"] = o.Settings + toSerialize["rules"] = o.Rules + return toSerialize, nil +} + +type NullableDerivedRole struct { + value *DerivedRole + isSet bool +} + +func (v NullableDerivedRole) Get() *DerivedRole { + return v.value +} + +func (v *NullableDerivedRole) Set(val *DerivedRole) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRole) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRole) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRole(val *DerivedRole) *NullableDerivedRole { + return &NullableDerivedRole{value: val, isSet: true} +} + +func (v NullableDerivedRole) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRole) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_edit.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_edit.go new file mode 100644 index 00000000..c79dc841 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_edit.go @@ -0,0 +1,163 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRoleBlockEdit type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRoleBlockEdit{} + +// DerivedRoleBlockEdit struct for DerivedRoleBlockEdit +type DerivedRoleBlockEdit struct { + When *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings `json:"when,omitempty"` + // the rules of the derived role + UsersWithRole []DerivedRoleRuleCreate `json:"users_with_role,omitempty"` +} + +// NewDerivedRoleBlockEdit instantiates a new DerivedRoleBlockEdit object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRoleBlockEdit() *DerivedRoleBlockEdit { + this := DerivedRoleBlockEdit{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// NewDerivedRoleBlockEditWithDefaults instantiates a new DerivedRoleBlockEdit object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleBlockEditWithDefaults() *DerivedRoleBlockEdit { + this := DerivedRoleBlockEdit{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// GetWhen returns the When field value if set, zero value otherwise. +func (o *DerivedRoleBlockEdit) GetWhen() PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + if o == nil || IsNil(o.When) { + var ret PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + return ret + } + return *o.When +} + +// GetWhenOk returns a tuple with the When field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleBlockEdit) GetWhenOk() (*PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, bool) { + if o == nil || IsNil(o.When) { + return nil, false + } + return o.When, true +} + +// HasWhen returns a boolean if a field has been set. +func (o *DerivedRoleBlockEdit) HasWhen() bool { + if o != nil && !IsNil(o.When) { + return true + } + + return false +} + +// SetWhen gets a reference to the given PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings and assigns it to the When field. +func (o *DerivedRoleBlockEdit) SetWhen(v PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) { + o.When = &v +} + +// GetUsersWithRole returns the UsersWithRole field value if set, zero value otherwise. +func (o *DerivedRoleBlockEdit) GetUsersWithRole() []DerivedRoleRuleCreate { + if o == nil || IsNil(o.UsersWithRole) { + var ret []DerivedRoleRuleCreate + return ret + } + return o.UsersWithRole +} + +// GetUsersWithRoleOk returns a tuple with the UsersWithRole field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleBlockEdit) GetUsersWithRoleOk() ([]DerivedRoleRuleCreate, bool) { + if o == nil || IsNil(o.UsersWithRole) { + return nil, false + } + return o.UsersWithRole, true +} + +// HasUsersWithRole returns a boolean if a field has been set. +func (o *DerivedRoleBlockEdit) HasUsersWithRole() bool { + if o != nil && !IsNil(o.UsersWithRole) { + return true + } + + return false +} + +// SetUsersWithRole gets a reference to the given []DerivedRoleRuleCreate and assigns it to the UsersWithRole field. +func (o *DerivedRoleBlockEdit) SetUsersWithRole(v []DerivedRoleRuleCreate) { + o.UsersWithRole = v +} + +func (o DerivedRoleBlockEdit) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRoleBlockEdit) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.When) { + toSerialize["when"] = o.When + } + if !IsNil(o.UsersWithRole) { + toSerialize["users_with_role"] = o.UsersWithRole + } + return toSerialize, nil +} + +type NullableDerivedRoleBlockEdit struct { + value *DerivedRoleBlockEdit + isSet bool +} + +func (v NullableDerivedRoleBlockEdit) Get() *DerivedRoleBlockEdit { + return v.value +} + +func (v *NullableDerivedRoleBlockEdit) Set(val *DerivedRoleBlockEdit) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRoleBlockEdit) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRoleBlockEdit) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRoleBlockEdit(val *DerivedRoleBlockEdit) *NullableDerivedRoleBlockEdit { + return &NullableDerivedRoleBlockEdit{value: val, isSet: true} +} + +func (v NullableDerivedRoleBlockEdit) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRoleBlockEdit) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_read.go new file mode 100644 index 00000000..3b2cb219 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_block_read.go @@ -0,0 +1,191 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRoleBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRoleBlockRead{} + +// DerivedRoleBlockRead struct for DerivedRoleBlockRead +type DerivedRoleBlockRead struct { + When *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings `json:"when,omitempty"` + // The unique id of the derived_role + Id string `json:"id"` + // the rules of the derived role + UsersWithRole []DerivedRoleRuleRead `json:"users_with_role,omitempty"` +} + +// NewDerivedRoleBlockRead instantiates a new DerivedRoleBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRoleBlockRead(id string) *DerivedRoleBlockRead { + this := DerivedRoleBlockRead{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + this.Id = id + return &this +} + +// NewDerivedRoleBlockReadWithDefaults instantiates a new DerivedRoleBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleBlockReadWithDefaults() *DerivedRoleBlockRead { + this := DerivedRoleBlockRead{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// GetWhen returns the When field value if set, zero value otherwise. +func (o *DerivedRoleBlockRead) GetWhen() PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + if o == nil || IsNil(o.When) { + var ret PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + return ret + } + return *o.When +} + +// GetWhenOk returns a tuple with the When field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleBlockRead) GetWhenOk() (*PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, bool) { + if o == nil || IsNil(o.When) { + return nil, false + } + return o.When, true +} + +// HasWhen returns a boolean if a field has been set. +func (o *DerivedRoleBlockRead) HasWhen() bool { + if o != nil && !IsNil(o.When) { + return true + } + + return false +} + +// SetWhen gets a reference to the given PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings and assigns it to the When field. +func (o *DerivedRoleBlockRead) SetWhen(v PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) { + o.When = &v +} + +// GetId returns the Id field value +func (o *DerivedRoleBlockRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleBlockRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *DerivedRoleBlockRead) SetId(v string) { + o.Id = v +} + +// GetUsersWithRole returns the UsersWithRole field value if set, zero value otherwise. +func (o *DerivedRoleBlockRead) GetUsersWithRole() []DerivedRoleRuleRead { + if o == nil || IsNil(o.UsersWithRole) { + var ret []DerivedRoleRuleRead + return ret + } + return o.UsersWithRole +} + +// GetUsersWithRoleOk returns a tuple with the UsersWithRole field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleBlockRead) GetUsersWithRoleOk() ([]DerivedRoleRuleRead, bool) { + if o == nil || IsNil(o.UsersWithRole) { + return nil, false + } + return o.UsersWithRole, true +} + +// HasUsersWithRole returns a boolean if a field has been set. +func (o *DerivedRoleBlockRead) HasUsersWithRole() bool { + if o != nil && !IsNil(o.UsersWithRole) { + return true + } + + return false +} + +// SetUsersWithRole gets a reference to the given []DerivedRoleRuleRead and assigns it to the UsersWithRole field. +func (o *DerivedRoleBlockRead) SetUsersWithRole(v []DerivedRoleRuleRead) { + o.UsersWithRole = v +} + +func (o DerivedRoleBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRoleBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.When) { + toSerialize["when"] = o.When + } + toSerialize["id"] = o.Id + if !IsNil(o.UsersWithRole) { + toSerialize["users_with_role"] = o.UsersWithRole + } + return toSerialize, nil +} + +type NullableDerivedRoleBlockRead struct { + value *DerivedRoleBlockRead + isSet bool +} + +func (v NullableDerivedRoleBlockRead) Get() *DerivedRoleBlockRead { + return v.value +} + +func (v *NullableDerivedRoleBlockRead) Set(val *DerivedRoleBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRoleBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRoleBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRoleBlockRead(val *DerivedRoleBlockRead) *NullableDerivedRoleBlockRead { + return &NullableDerivedRoleBlockRead{value: val, isSet: true} +} + +func (v NullableDerivedRoleBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRoleBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule.go new file mode 100644 index 00000000..de258885 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule.go @@ -0,0 +1,196 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRoleRule type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRoleRule{} + +// DerivedRoleRule struct for DerivedRoleRule +type DerivedRoleRule struct { + Relation string `json:"relation"` + RelatedResource string `json:"related_resource"` + RelatedRole string `json:"related_role"` + Settings PermitBackendSchemasSchemaOpalDataDerivationSettings `json:"settings"` +} + +// NewDerivedRoleRule instantiates a new DerivedRoleRule object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRoleRule(relation string, relatedResource string, relatedRole string, settings PermitBackendSchemasSchemaOpalDataDerivationSettings) *DerivedRoleRule { + this := DerivedRoleRule{} + this.Relation = relation + this.RelatedResource = relatedResource + this.RelatedRole = relatedRole + this.Settings = settings + return &this +} + +// NewDerivedRoleRuleWithDefaults instantiates a new DerivedRoleRule object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleRuleWithDefaults() *DerivedRoleRule { + this := DerivedRoleRule{} + return &this +} + +// GetRelation returns the Relation field value +func (o *DerivedRoleRule) GetRelation() string { + if o == nil { + var ret string + return ret + } + + return o.Relation +} + +// GetRelationOk returns a tuple with the Relation field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRule) GetRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Relation, true +} + +// SetRelation sets field value +func (o *DerivedRoleRule) SetRelation(v string) { + o.Relation = v +} + +// GetRelatedResource returns the RelatedResource field value +func (o *DerivedRoleRule) GetRelatedResource() string { + if o == nil { + var ret string + return ret + } + + return o.RelatedResource +} + +// GetRelatedResourceOk returns a tuple with the RelatedResource field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRule) GetRelatedResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RelatedResource, true +} + +// SetRelatedResource sets field value +func (o *DerivedRoleRule) SetRelatedResource(v string) { + o.RelatedResource = v +} + +// GetRelatedRole returns the RelatedRole field value +func (o *DerivedRoleRule) GetRelatedRole() string { + if o == nil { + var ret string + return ret + } + + return o.RelatedRole +} + +// GetRelatedRoleOk returns a tuple with the RelatedRole field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRule) GetRelatedRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RelatedRole, true +} + +// SetRelatedRole sets field value +func (o *DerivedRoleRule) SetRelatedRole(v string) { + o.RelatedRole = v +} + +// GetSettings returns the Settings field value +func (o *DerivedRoleRule) GetSettings() PermitBackendSchemasSchemaOpalDataDerivationSettings { + if o == nil { + var ret PermitBackendSchemasSchemaOpalDataDerivationSettings + return ret + } + + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRule) GetSettingsOk() (*PermitBackendSchemasSchemaOpalDataDerivationSettings, bool) { + if o == nil { + return nil, false + } + return &o.Settings, true +} + +// SetSettings sets field value +func (o *DerivedRoleRule) SetSettings(v PermitBackendSchemasSchemaOpalDataDerivationSettings) { + o.Settings = v +} + +func (o DerivedRoleRule) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRoleRule) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["relation"] = o.Relation + toSerialize["related_resource"] = o.RelatedResource + toSerialize["related_role"] = o.RelatedRole + toSerialize["settings"] = o.Settings + return toSerialize, nil +} + +type NullableDerivedRoleRule struct { + value *DerivedRoleRule + isSet bool +} + +func (v NullableDerivedRoleRule) Get() *DerivedRoleRule { + return v.value +} + +func (v *NullableDerivedRoleRule) Set(val *DerivedRoleRule) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRoleRule) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRoleRule) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRoleRule(val *DerivedRoleRule) *NullableDerivedRoleRule { + return &NullableDerivedRoleRule{value: val, isSet: true} +} + +func (v NullableDerivedRoleRule) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRoleRule) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_create.go new file mode 100644 index 00000000..b821d420 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_create.go @@ -0,0 +1,210 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRoleRuleCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRoleRuleCreate{} + +// DerivedRoleRuleCreate struct for DerivedRoleRuleCreate +type DerivedRoleRuleCreate struct { + // the role key that needs to exist on the related resource (from the relation) + Role string `json:"role"` + // the resource key that needs to exist on the related role (from the relation) + OnResource string `json:"on_resource"` + // the relation key that needs to exist between the resource and the related resource + LinkedByRelation string `json:"linked_by_relation"` + When *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings `json:"when,omitempty"` +} + +// NewDerivedRoleRuleCreate instantiates a new DerivedRoleRuleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRoleRuleCreate(role string, onResource string, linkedByRelation string) *DerivedRoleRuleCreate { + this := DerivedRoleRuleCreate{} + this.Role = role + this.OnResource = onResource + this.LinkedByRelation = linkedByRelation + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// NewDerivedRoleRuleCreateWithDefaults instantiates a new DerivedRoleRuleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleRuleCreateWithDefaults() *DerivedRoleRuleCreate { + this := DerivedRoleRuleCreate{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// GetRole returns the Role field value +func (o *DerivedRoleRuleCreate) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleCreate) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *DerivedRoleRuleCreate) SetRole(v string) { + o.Role = v +} + +// GetOnResource returns the OnResource field value +func (o *DerivedRoleRuleCreate) GetOnResource() string { + if o == nil { + var ret string + return ret + } + + return o.OnResource +} + +// GetOnResourceOk returns a tuple with the OnResource field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleCreate) GetOnResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OnResource, true +} + +// SetOnResource sets field value +func (o *DerivedRoleRuleCreate) SetOnResource(v string) { + o.OnResource = v +} + +// GetLinkedByRelation returns the LinkedByRelation field value +func (o *DerivedRoleRuleCreate) GetLinkedByRelation() string { + if o == nil { + var ret string + return ret + } + + return o.LinkedByRelation +} + +// GetLinkedByRelationOk returns a tuple with the LinkedByRelation field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleCreate) GetLinkedByRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.LinkedByRelation, true +} + +// SetLinkedByRelation sets field value +func (o *DerivedRoleRuleCreate) SetLinkedByRelation(v string) { + o.LinkedByRelation = v +} + +// GetWhen returns the When field value if set, zero value otherwise. +func (o *DerivedRoleRuleCreate) GetWhen() PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + if o == nil || IsNil(o.When) { + var ret PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + return ret + } + return *o.When +} + +// GetWhenOk returns a tuple with the When field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleCreate) GetWhenOk() (*PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, bool) { + if o == nil || IsNil(o.When) { + return nil, false + } + return o.When, true +} + +// HasWhen returns a boolean if a field has been set. +func (o *DerivedRoleRuleCreate) HasWhen() bool { + if o != nil && !IsNil(o.When) { + return true + } + + return false +} + +// SetWhen gets a reference to the given PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings and assigns it to the When field. +func (o *DerivedRoleRuleCreate) SetWhen(v PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) { + o.When = &v +} + +func (o DerivedRoleRuleCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRoleRuleCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["role"] = o.Role + toSerialize["on_resource"] = o.OnResource + toSerialize["linked_by_relation"] = o.LinkedByRelation + if !IsNil(o.When) { + toSerialize["when"] = o.When + } + return toSerialize, nil +} + +type NullableDerivedRoleRuleCreate struct { + value *DerivedRoleRuleCreate + isSet bool +} + +func (v NullableDerivedRoleRuleCreate) Get() *DerivedRoleRuleCreate { + return v.value +} + +func (v *NullableDerivedRoleRuleCreate) Set(val *DerivedRoleRuleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRoleRuleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRoleRuleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRoleRuleCreate(val *DerivedRoleRuleCreate) *NullableDerivedRoleRuleCreate { + return &NullableDerivedRoleRuleCreate{value: val, isSet: true} +} + +func (v NullableDerivedRoleRuleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRoleRuleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_delete.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_delete.go new file mode 100644 index 00000000..58b03462 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_delete.go @@ -0,0 +1,210 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRoleRuleDelete type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRoleRuleDelete{} + +// DerivedRoleRuleDelete struct for DerivedRoleRuleDelete +type DerivedRoleRuleDelete struct { + // the role key that needs to exist on the related resource (from the relation) + Role string `json:"role"` + // the resource key that needs to exist on the related role (from the relation) + OnResource string `json:"on_resource"` + // the relation key that needs to exist between the resource and the related resource + LinkedByRelation string `json:"linked_by_relation"` + When *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings `json:"when,omitempty"` +} + +// NewDerivedRoleRuleDelete instantiates a new DerivedRoleRuleDelete object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRoleRuleDelete(role string, onResource string, linkedByRelation string) *DerivedRoleRuleDelete { + this := DerivedRoleRuleDelete{} + this.Role = role + this.OnResource = onResource + this.LinkedByRelation = linkedByRelation + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// NewDerivedRoleRuleDeleteWithDefaults instantiates a new DerivedRoleRuleDelete object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleRuleDeleteWithDefaults() *DerivedRoleRuleDelete { + this := DerivedRoleRuleDelete{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// GetRole returns the Role field value +func (o *DerivedRoleRuleDelete) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleDelete) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *DerivedRoleRuleDelete) SetRole(v string) { + o.Role = v +} + +// GetOnResource returns the OnResource field value +func (o *DerivedRoleRuleDelete) GetOnResource() string { + if o == nil { + var ret string + return ret + } + + return o.OnResource +} + +// GetOnResourceOk returns a tuple with the OnResource field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleDelete) GetOnResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OnResource, true +} + +// SetOnResource sets field value +func (o *DerivedRoleRuleDelete) SetOnResource(v string) { + o.OnResource = v +} + +// GetLinkedByRelation returns the LinkedByRelation field value +func (o *DerivedRoleRuleDelete) GetLinkedByRelation() string { + if o == nil { + var ret string + return ret + } + + return o.LinkedByRelation +} + +// GetLinkedByRelationOk returns a tuple with the LinkedByRelation field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleDelete) GetLinkedByRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.LinkedByRelation, true +} + +// SetLinkedByRelation sets field value +func (o *DerivedRoleRuleDelete) SetLinkedByRelation(v string) { + o.LinkedByRelation = v +} + +// GetWhen returns the When field value if set, zero value otherwise. +func (o *DerivedRoleRuleDelete) GetWhen() PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + if o == nil || IsNil(o.When) { + var ret PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + return ret + } + return *o.When +} + +// GetWhenOk returns a tuple with the When field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleDelete) GetWhenOk() (*PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, bool) { + if o == nil || IsNil(o.When) { + return nil, false + } + return o.When, true +} + +// HasWhen returns a boolean if a field has been set. +func (o *DerivedRoleRuleDelete) HasWhen() bool { + if o != nil && !IsNil(o.When) { + return true + } + + return false +} + +// SetWhen gets a reference to the given PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings and assigns it to the When field. +func (o *DerivedRoleRuleDelete) SetWhen(v PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) { + o.When = &v +} + +func (o DerivedRoleRuleDelete) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRoleRuleDelete) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["role"] = o.Role + toSerialize["on_resource"] = o.OnResource + toSerialize["linked_by_relation"] = o.LinkedByRelation + if !IsNil(o.When) { + toSerialize["when"] = o.When + } + return toSerialize, nil +} + +type NullableDerivedRoleRuleDelete struct { + value *DerivedRoleRuleDelete + isSet bool +} + +func (v NullableDerivedRoleRuleDelete) Get() *DerivedRoleRuleDelete { + return v.value +} + +func (v *NullableDerivedRoleRuleDelete) Set(val *DerivedRoleRuleDelete) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRoleRuleDelete) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRoleRuleDelete) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRoleRuleDelete(val *DerivedRoleRuleDelete) *NullableDerivedRoleRuleDelete { + return &NullableDerivedRoleRuleDelete{value: val, isSet: true} +} + +func (v NullableDerivedRoleRuleDelete) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRoleRuleDelete) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_read.go new file mode 100644 index 00000000..316f39b7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_derived_role_rule_read.go @@ -0,0 +1,294 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the DerivedRoleRuleRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &DerivedRoleRuleRead{} + +// DerivedRoleRuleRead struct for DerivedRoleRuleRead +type DerivedRoleRuleRead struct { + // the role id that needs to exist on the related resource (from the relation) + RoleId string `json:"role_id"` + // the resource id that needs to exist on the related role (from the relation) + ResourceId string `json:"resource_id"` + // the relation id that needs to exist between the resource and the related resource + RelationId string `json:"relation_id"` + // the role key that needs to exist on the related resource (from the relation) + Role string `json:"role"` + // the resource key that needs to exist on the related role (from the relation) + OnResource string `json:"on_resource"` + // the relation key that needs to exist between the resource and the related resource + LinkedByRelation string `json:"linked_by_relation"` + When *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings `json:"when,omitempty"` +} + +// NewDerivedRoleRuleRead instantiates a new DerivedRoleRuleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDerivedRoleRuleRead(roleId string, resourceId string, relationId string, role string, onResource string, linkedByRelation string) *DerivedRoleRuleRead { + this := DerivedRoleRuleRead{} + this.RoleId = roleId + this.ResourceId = resourceId + this.RelationId = relationId + this.Role = role + this.OnResource = onResource + this.LinkedByRelation = linkedByRelation + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// NewDerivedRoleRuleReadWithDefaults instantiates a new DerivedRoleRuleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDerivedRoleRuleReadWithDefaults() *DerivedRoleRuleRead { + this := DerivedRoleRuleRead{} + this.When = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{NoDirectRolesOnObject: PtrBool(false)} + return &this +} + +// GetRoleId returns the RoleId field value +func (o *DerivedRoleRuleRead) GetRoleId() string { + if o == nil { + var ret string + return ret + } + + return o.RoleId +} + +// GetRoleIdOk returns a tuple with the RoleId field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetRoleIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RoleId, true +} + +// SetRoleId sets field value +func (o *DerivedRoleRuleRead) SetRoleId(v string) { + o.RoleId = v +} + +// GetResourceId returns the ResourceId field value +func (o *DerivedRoleRuleRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *DerivedRoleRuleRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetRelationId returns the RelationId field value +func (o *DerivedRoleRuleRead) GetRelationId() string { + if o == nil { + var ret string + return ret + } + + return o.RelationId +} + +// GetRelationIdOk returns a tuple with the RelationId field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetRelationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RelationId, true +} + +// SetRelationId sets field value +func (o *DerivedRoleRuleRead) SetRelationId(v string) { + o.RelationId = v +} + +// GetRole returns the Role field value +func (o *DerivedRoleRuleRead) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *DerivedRoleRuleRead) SetRole(v string) { + o.Role = v +} + +// GetOnResource returns the OnResource field value +func (o *DerivedRoleRuleRead) GetOnResource() string { + if o == nil { + var ret string + return ret + } + + return o.OnResource +} + +// GetOnResourceOk returns a tuple with the OnResource field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetOnResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OnResource, true +} + +// SetOnResource sets field value +func (o *DerivedRoleRuleRead) SetOnResource(v string) { + o.OnResource = v +} + +// GetLinkedByRelation returns the LinkedByRelation field value +func (o *DerivedRoleRuleRead) GetLinkedByRelation() string { + if o == nil { + var ret string + return ret + } + + return o.LinkedByRelation +} + +// GetLinkedByRelationOk returns a tuple with the LinkedByRelation field value +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetLinkedByRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.LinkedByRelation, true +} + +// SetLinkedByRelation sets field value +func (o *DerivedRoleRuleRead) SetLinkedByRelation(v string) { + o.LinkedByRelation = v +} + +// GetWhen returns the When field value if set, zero value otherwise. +func (o *DerivedRoleRuleRead) GetWhen() PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + if o == nil || IsNil(o.When) { + var ret PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + return ret + } + return *o.When +} + +// GetWhenOk returns a tuple with the When field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DerivedRoleRuleRead) GetWhenOk() (*PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, bool) { + if o == nil || IsNil(o.When) { + return nil, false + } + return o.When, true +} + +// HasWhen returns a boolean if a field has been set. +func (o *DerivedRoleRuleRead) HasWhen() bool { + if o != nil && !IsNil(o.When) { + return true + } + + return false +} + +// SetWhen gets a reference to the given PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings and assigns it to the When field. +func (o *DerivedRoleRuleRead) SetWhen(v PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) { + o.When = &v +} + +func (o DerivedRoleRuleRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o DerivedRoleRuleRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["role_id"] = o.RoleId + toSerialize["resource_id"] = o.ResourceId + toSerialize["relation_id"] = o.RelationId + toSerialize["role"] = o.Role + toSerialize["on_resource"] = o.OnResource + toSerialize["linked_by_relation"] = o.LinkedByRelation + if !IsNil(o.When) { + toSerialize["when"] = o.When + } + return toSerialize, nil +} + +type NullableDerivedRoleRuleRead struct { + value *DerivedRoleRuleRead + isSet bool +} + +func (v NullableDerivedRoleRuleRead) Get() *DerivedRoleRuleRead { + return v.value +} + +func (v *NullableDerivedRoleRuleRead) Set(val *DerivedRoleRuleRead) { + v.value = val + v.isSet = true +} + +func (v NullableDerivedRoleRuleRead) IsSet() bool { + return v.isSet +} + +func (v *NullableDerivedRoleRuleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDerivedRoleRuleRead(val *DerivedRoleRuleRead) *NullableDerivedRoleRuleRead { + return &NullableDerivedRoleRuleRead{value: val, isSet: true} +} + +func (v NullableDerivedRoleRuleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDerivedRoleRuleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_dev_login.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_dev_login.go new file mode 100644 index 00000000..28418dc3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_dev_login.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// DevLogin struct for DevLogin +type DevLogin struct { + // an email address from which to create a DEV MODE session + Username string `json:"username"` +} + +// NewDevLogin instantiates a new DevLogin object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDevLogin(username string) *DevLogin { + this := DevLogin{} + this.Username = username + return &this +} + +// NewDevLoginWithDefaults instantiates a new DevLogin object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDevLoginWithDefaults() *DevLogin { + this := DevLogin{} + return &this +} + +// GetUsername returns the Username field value +func (o *DevLogin) GetUsername() string { + if o == nil { + var ret string + return ret + } + + return o.Username +} + +// GetUsernameOk returns a tuple with the Username field value +// and a boolean to check if the value has been set. +func (o *DevLogin) GetUsernameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Username, true +} + +// SetUsername sets field value +func (o *DevLogin) SetUsername(v string) { + o.Username = v +} + +func (o DevLogin) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["username"] = o.Username + } + return json.Marshal(toSerialize) +} + +type NullableDevLogin struct { + value *DevLogin + isSet bool +} + +func (v NullableDevLogin) Get() *DevLogin { + return v.value +} + +func (v *NullableDevLogin) Set(val *DevLogin) { + v.value = val + v.isSet = true +} + +func (v NullableDevLogin) IsSet() bool { + return v.isSet +} + +func (v *NullableDevLogin) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDevLogin(val *DevLogin) *NullableDevLogin { + return &NullableDevLogin{value: val, isSet: true} +} + +func (v NullableDevLogin) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDevLogin) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_create.go new file mode 100644 index 00000000..230daf23 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_create.go @@ -0,0 +1,263 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsConfigCreate struct for ElementsConfigCreate +type ElementsConfigCreate struct { + // A URL-friendly name of the elements_config (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the elements_config. + Key string `json:"key"` + // The name of the elements_config + Name string `json:"name"` + // The type of the elements interface, e.g: user management + ElementsType ElementsType `json:"elements_type"` + // Obj with the options of the elements interface, e.g: primary color + Settings map[string]Settings `json:"settings"` + // Obj with levels as keys and role ids as values + RolesToLevels map[string][]string `json:"roles_to_levels"` + Webhook *WebhookCreate `json:"webhook,omitempty"` +} + +// NewElementsConfigCreate instantiates a new ElementsConfigCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsConfigCreate(key string, name string, elementsType ElementsType, settings map[string]Settings, rolesToLevels map[string][]string) *ElementsConfigCreate { + this := ElementsConfigCreate{} + this.Key = key + this.Name = name + this.ElementsType = elementsType + this.Settings = settings + this.RolesToLevels = rolesToLevels + return &this +} + +// NewElementsConfigCreateWithDefaults instantiates a new ElementsConfigCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsConfigCreateWithDefaults() *ElementsConfigCreate { + this := ElementsConfigCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ElementsConfigCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ElementsConfigCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *ElementsConfigCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ElementsConfigCreate) SetName(v string) { + o.Name = v +} + +// GetElementsType returns the ElementsType field value +func (o *ElementsConfigCreate) GetElementsType() ElementsType { + if o == nil { + var ret ElementsType + return ret + } + + return o.ElementsType +} + +// GetElementsTypeOk returns a tuple with the ElementsType field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigCreate) GetElementsTypeOk() (*ElementsType, bool) { + if o == nil { + return nil, false + } + return &o.ElementsType, true +} + +// SetElementsType sets field value +func (o *ElementsConfigCreate) SetElementsType(v ElementsType) { + o.ElementsType = v +} + +// GetSettings returns the Settings field value +func (o *ElementsConfigCreate) GetSettings() map[string]Settings { + if o == nil { + var ret map[string]Settings + return ret + } + + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigCreate) GetSettingsOk() (*map[string]Settings, bool) { + if o == nil { + return nil, false + } + return &o.Settings, true +} + +// SetSettings sets field value +func (o *ElementsConfigCreate) SetSettings(v map[string]Settings) { + o.Settings = v +} + +// GetRolesToLevels returns the RolesToLevels field value +func (o *ElementsConfigCreate) GetRolesToLevels() map[string][]string { + if o == nil { + var ret map[string][]string + return ret + } + + return o.RolesToLevels +} + +// GetRolesToLevelsOk returns a tuple with the RolesToLevels field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigCreate) GetRolesToLevelsOk() (*map[string][]string, bool) { + if o == nil { + return nil, false + } + return &o.RolesToLevels, true +} + +// SetRolesToLevels sets field value +func (o *ElementsConfigCreate) SetRolesToLevels(v map[string][]string) { + o.RolesToLevels = v +} + +// GetWebhook returns the Webhook field value if set, zero value otherwise. +func (o *ElementsConfigCreate) GetWebhook() WebhookCreate { + if o == nil || IsNil(o.Webhook) { + var ret WebhookCreate + return ret + } + return *o.Webhook +} + +// GetWebhookOk returns a tuple with the Webhook field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsConfigCreate) GetWebhookOk() (*WebhookCreate, bool) { + if o == nil || IsNil(o.Webhook) { + return nil, false + } + return o.Webhook, true +} + +// HasWebhook returns a boolean if a field has been set. +func (o *ElementsConfigCreate) HasWebhook() bool { + if o != nil && !IsNil(o.Webhook) { + return true + } + + return false +} + +// SetWebhook gets a reference to the given WebhookCreate and assigns it to the Webhook field. +func (o *ElementsConfigCreate) SetWebhook(v WebhookCreate) { + o.Webhook = &v +} + +func (o ElementsConfigCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if true { + toSerialize["elements_type"] = o.ElementsType + } + if true { + toSerialize["settings"] = o.Settings + } + if true { + toSerialize["roles_to_levels"] = o.RolesToLevels + } + if !IsNil(o.Webhook) { + toSerialize["webhook"] = o.Webhook + } + return json.Marshal(toSerialize) +} + +type NullableElementsConfigCreate struct { + value *ElementsConfigCreate + isSet bool +} + +func (v NullableElementsConfigCreate) Get() *ElementsConfigCreate { + return v.value +} + +func (v *NullableElementsConfigCreate) Set(val *ElementsConfigCreate) { + v.value = val + v.isSet = true +} + +func (v NullableElementsConfigCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsConfigCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsConfigCreate(val *ElementsConfigCreate) *NullableElementsConfigCreate { + return &NullableElementsConfigCreate{value: val, isSet: true} +} + +func (v NullableElementsConfigCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsConfigCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_read.go new file mode 100644 index 00000000..2db0536e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_read.go @@ -0,0 +1,473 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ElementsConfigRead struct for ElementsConfigRead +type ElementsConfigRead struct { + // A URL-friendly name of the elements_config (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the elements_config. + Key string `json:"key"` + // Unique id of the elements_config + Id string `json:"id"` + // Unique id of the organization that the elements_config belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the elements_config belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the elements_config belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the elements_config was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the elements_config was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + IsActive bool `json:"is_active"` + // The name of the elements_config + Name string `json:"name"` + // The type of the elements interface, e.g: user management + ElementsType ElementsType `json:"elements_type"` + // Obj with the options of the elements interface, e.g: primary color + Settings map[string]Settings `json:"settings"` + // Obj with levels as keys and role ids as values + RolesToLevels map[string][]PermissionLevelRoleRead `json:"roles_to_levels"` + Webhook *WebhookRead `json:"webhook,omitempty"` +} + +// NewElementsConfigRead instantiates a new ElementsConfigRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsConfigRead(key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, isActive bool, name string, elementsType ElementsType, settings map[string]Settings, rolesToLevels map[string][]PermissionLevelRoleRead) *ElementsConfigRead { + this := ElementsConfigRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.IsActive = isActive + this.Name = name + this.ElementsType = elementsType + this.Settings = settings + this.RolesToLevels = rolesToLevels + return &this +} + +// NewElementsConfigReadWithDefaults instantiates a new ElementsConfigRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsConfigReadWithDefaults() *ElementsConfigRead { + this := ElementsConfigRead{} + return &this +} + +// GetKey returns the Key field value +func (o *ElementsConfigRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ElementsConfigRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ElementsConfigRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ElementsConfigRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ElementsConfigRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ElementsConfigRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ElementsConfigRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ElementsConfigRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ElementsConfigRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ElementsConfigRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ElementsConfigRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ElementsConfigRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ElementsConfigRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ElementsConfigRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetIsActive returns the IsActive field value +func (o *ElementsConfigRead) GetIsActive() bool { + if o == nil { + var ret bool + return ret + } + + return o.IsActive +} + +// GetIsActiveOk returns a tuple with the IsActive field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetIsActiveOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.IsActive, true +} + +// SetIsActive sets field value +func (o *ElementsConfigRead) SetIsActive(v bool) { + o.IsActive = v +} + +// GetName returns the Name field value +func (o *ElementsConfigRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ElementsConfigRead) SetName(v string) { + o.Name = v +} + +// GetElementsType returns the ElementsType field value +func (o *ElementsConfigRead) GetElementsType() ElementsType { + if o == nil { + var ret ElementsType + return ret + } + + return o.ElementsType +} + +// GetElementsTypeOk returns a tuple with the ElementsType field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetElementsTypeOk() (*ElementsType, bool) { + if o == nil { + return nil, false + } + return &o.ElementsType, true +} + +// SetElementsType sets field value +func (o *ElementsConfigRead) SetElementsType(v ElementsType) { + o.ElementsType = v +} + +// GetSettings returns the Settings field value +func (o *ElementsConfigRead) GetSettings() map[string]Settings { + if o == nil { + var ret map[string]Settings + return ret + } + + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetSettingsOk() (*map[string]Settings, bool) { + if o == nil { + return nil, false + } + return &o.Settings, true +} + +// SetSettings sets field value +func (o *ElementsConfigRead) SetSettings(v map[string]Settings) { + o.Settings = v +} + +// GetRolesToLevels returns the RolesToLevels field value +func (o *ElementsConfigRead) GetRolesToLevels() map[string][]PermissionLevelRoleRead { + if o == nil { + var ret map[string][]PermissionLevelRoleRead + return ret + } + + return o.RolesToLevels +} + +// GetRolesToLevelsOk returns a tuple with the RolesToLevels field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetRolesToLevelsOk() (*map[string][]PermissionLevelRoleRead, bool) { + if o == nil { + return nil, false + } + return &o.RolesToLevels, true +} + +// SetRolesToLevels sets field value +func (o *ElementsConfigRead) SetRolesToLevels(v map[string][]PermissionLevelRoleRead) { + o.RolesToLevels = v +} + +// GetWebhook returns the Webhook field value if set, zero value otherwise. +func (o *ElementsConfigRead) GetWebhook() WebhookRead { + if o == nil || IsNil(o.Webhook) { + var ret WebhookRead + return ret + } + return *o.Webhook +} + +// GetWebhookOk returns a tuple with the Webhook field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsConfigRead) GetWebhookOk() (*WebhookRead, bool) { + if o == nil || IsNil(o.Webhook) { + return nil, false + } + return o.Webhook, true +} + +// HasWebhook returns a boolean if a field has been set. +func (o *ElementsConfigRead) HasWebhook() bool { + if o != nil && !IsNil(o.Webhook) { + return true + } + + return false +} + +// SetWebhook gets a reference to the given WebhookRead and assigns it to the Webhook field. +func (o *ElementsConfigRead) SetWebhook(v WebhookRead) { + o.Webhook = &v +} + +func (o ElementsConfigRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["is_active"] = o.IsActive + } + if true { + toSerialize["name"] = o.Name + } + if true { + toSerialize["elements_type"] = o.ElementsType + } + if true { + toSerialize["settings"] = o.Settings + } + if true { + toSerialize["roles_to_levels"] = o.RolesToLevels + } + if !IsNil(o.Webhook) { + toSerialize["webhook"] = o.Webhook + } + return json.Marshal(toSerialize) +} + +type NullableElementsConfigRead struct { + value *ElementsConfigRead + isSet bool +} + +func (v NullableElementsConfigRead) Get() *ElementsConfigRead { + return v.value +} + +func (v *NullableElementsConfigRead) Set(val *ElementsConfigRead) { + v.value = val + v.isSet = true +} + +func (v NullableElementsConfigRead) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsConfigRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsConfigRead(val *ElementsConfigRead) *NullableElementsConfigRead { + return &NullableElementsConfigRead{value: val, isSet: true} +} + +func (v NullableElementsConfigRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsConfigRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_update.go new file mode 100644 index 00000000..87daee6f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_config_update.go @@ -0,0 +1,254 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsConfigUpdate struct for ElementsConfigUpdate +type ElementsConfigUpdate struct { + // The name of the elements_config + Name *string `json:"name,omitempty"` + // The type of the elements interface, e.g: user management + ElementsType *ElementsType `json:"elements_type,omitempty"` + // Obj with the options of the elements interface, e.g: primary color + Settings *map[string]Settings `json:"settings,omitempty"` + // Obj with levels as keys and role ids as values + RolesToLevels map[string][]string `json:"roles_to_levels"` + Webhook *WebhookUpdate `json:"webhook,omitempty"` +} + +// NewElementsConfigUpdate instantiates a new ElementsConfigUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsConfigUpdate(rolesToLevels map[string][]string) *ElementsConfigUpdate { + this := ElementsConfigUpdate{} + this.RolesToLevels = rolesToLevels + return &this +} + +// NewElementsConfigUpdateWithDefaults instantiates a new ElementsConfigUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsConfigUpdateWithDefaults() *ElementsConfigUpdate { + this := ElementsConfigUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ElementsConfigUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsConfigUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ElementsConfigUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ElementsConfigUpdate) SetName(v string) { + o.Name = &v +} + +// GetElementsType returns the ElementsType field value if set, zero value otherwise. +func (o *ElementsConfigUpdate) GetElementsType() ElementsType { + if o == nil || IsNil(o.ElementsType) { + var ret ElementsType + return ret + } + return *o.ElementsType +} + +// GetElementsTypeOk returns a tuple with the ElementsType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsConfigUpdate) GetElementsTypeOk() (*ElementsType, bool) { + if o == nil || IsNil(o.ElementsType) { + return nil, false + } + return o.ElementsType, true +} + +// HasElementsType returns a boolean if a field has been set. +func (o *ElementsConfigUpdate) HasElementsType() bool { + if o != nil && !IsNil(o.ElementsType) { + return true + } + + return false +} + +// SetElementsType gets a reference to the given ElementsType and assigns it to the ElementsType field. +func (o *ElementsConfigUpdate) SetElementsType(v ElementsType) { + o.ElementsType = &v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *ElementsConfigUpdate) GetSettings() map[string]Settings { + if o == nil || IsNil(o.Settings) { + var ret map[string]Settings + return ret + } + return *o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsConfigUpdate) GetSettingsOk() (*map[string]Settings, bool) { + if o == nil || IsNil(o.Settings) { + return nil, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *ElementsConfigUpdate) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]Settings and assigns it to the Settings field. +func (o *ElementsConfigUpdate) SetSettings(v map[string]Settings) { + o.Settings = &v +} + +// GetRolesToLevels returns the RolesToLevels field value +func (o *ElementsConfigUpdate) GetRolesToLevels() map[string][]string { + if o == nil { + var ret map[string][]string + return ret + } + + return o.RolesToLevels +} + +// GetRolesToLevelsOk returns a tuple with the RolesToLevels field value +// and a boolean to check if the value has been set. +func (o *ElementsConfigUpdate) GetRolesToLevelsOk() (*map[string][]string, bool) { + if o == nil { + return nil, false + } + return &o.RolesToLevels, true +} + +// SetRolesToLevels sets field value +func (o *ElementsConfigUpdate) SetRolesToLevels(v map[string][]string) { + o.RolesToLevels = v +} + +// GetWebhook returns the Webhook field value if set, zero value otherwise. +func (o *ElementsConfigUpdate) GetWebhook() WebhookUpdate { + if o == nil || IsNil(o.Webhook) { + var ret WebhookUpdate + return ret + } + return *o.Webhook +} + +// GetWebhookOk returns a tuple with the Webhook field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsConfigUpdate) GetWebhookOk() (*WebhookUpdate, bool) { + if o == nil || IsNil(o.Webhook) { + return nil, false + } + return o.Webhook, true +} + +// HasWebhook returns a boolean if a field has been set. +func (o *ElementsConfigUpdate) HasWebhook() bool { + if o != nil && !IsNil(o.Webhook) { + return true + } + + return false +} + +// SetWebhook gets a reference to the given WebhookUpdate and assigns it to the Webhook field. +func (o *ElementsConfigUpdate) SetWebhook(v WebhookUpdate) { + o.Webhook = &v +} + +func (o ElementsConfigUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.ElementsType) { + toSerialize["elements_type"] = o.ElementsType + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + if true { + toSerialize["roles_to_levels"] = o.RolesToLevels + } + if !IsNil(o.Webhook) { + toSerialize["webhook"] = o.Webhook + } + return json.Marshal(toSerialize) +} + +type NullableElementsConfigUpdate struct { + value *ElementsConfigUpdate + isSet bool +} + +func (v NullableElementsConfigUpdate) Get() *ElementsConfigUpdate { + return v.value +} + +func (v *NullableElementsConfigUpdate) Set(val *ElementsConfigUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableElementsConfigUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsConfigUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsConfigUpdate(val *ElementsConfigUpdate) *NullableElementsConfigUpdate { + return &NullableElementsConfigUpdate{value: val, isSet: true} +} + +func (v NullableElementsConfigUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsConfigUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_read.go new file mode 100644 index 00000000..84098ed1 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_read.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsEnvRead struct for ElementsEnvRead +type ElementsEnvRead struct { + // Obj with levels as keys and role ids as values + RolesToLevels map[string][]PermissionLevelRoleRead `json:"roles_to_levels"` +} + +// NewElementsEnvRead instantiates a new ElementsEnvRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsEnvRead(rolesToLevels map[string][]PermissionLevelRoleRead) *ElementsEnvRead { + this := ElementsEnvRead{} + this.RolesToLevels = rolesToLevels + return &this +} + +// NewElementsEnvReadWithDefaults instantiates a new ElementsEnvRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsEnvReadWithDefaults() *ElementsEnvRead { + this := ElementsEnvRead{} + return &this +} + +// GetRolesToLevels returns the RolesToLevels field value +func (o *ElementsEnvRead) GetRolesToLevels() map[string][]PermissionLevelRoleRead { + if o == nil { + var ret map[string][]PermissionLevelRoleRead + return ret + } + + return o.RolesToLevels +} + +// GetRolesToLevelsOk returns a tuple with the RolesToLevels field value +// and a boolean to check if the value has been set. +func (o *ElementsEnvRead) GetRolesToLevelsOk() (*map[string][]PermissionLevelRoleRead, bool) { + if o == nil { + return nil, false + } + return &o.RolesToLevels, true +} + +// SetRolesToLevels sets field value +func (o *ElementsEnvRead) SetRolesToLevels(v map[string][]PermissionLevelRoleRead) { + o.RolesToLevels = v +} + +func (o ElementsEnvRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["roles_to_levels"] = o.RolesToLevels + } + return json.Marshal(toSerialize) +} + +type NullableElementsEnvRead struct { + value *ElementsEnvRead + isSet bool +} + +func (v NullableElementsEnvRead) Get() *ElementsEnvRead { + return v.value +} + +func (v *NullableElementsEnvRead) Set(val *ElementsEnvRead) { + v.value = val + v.isSet = true +} + +func (v NullableElementsEnvRead) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsEnvRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsEnvRead(val *ElementsEnvRead) *NullableElementsEnvRead { + return &NullableElementsEnvRead{value: val, isSet: true} +} + +func (v NullableElementsEnvRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsEnvRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_update.go new file mode 100644 index 00000000..d1743f35 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_env_update.go @@ -0,0 +1,114 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsEnvUpdate struct for ElementsEnvUpdate +type ElementsEnvUpdate struct { + // Obj with levels as keys and role ids as values + RolesToLevels *map[string][]string `json:"roles_to_levels,omitempty"` +} + +// NewElementsEnvUpdate instantiates a new ElementsEnvUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsEnvUpdate() *ElementsEnvUpdate { + this := ElementsEnvUpdate{} + return &this +} + +// NewElementsEnvUpdateWithDefaults instantiates a new ElementsEnvUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsEnvUpdateWithDefaults() *ElementsEnvUpdate { + this := ElementsEnvUpdate{} + return &this +} + +// GetRolesToLevels returns the RolesToLevels field value if set, zero value otherwise. +func (o *ElementsEnvUpdate) GetRolesToLevels() map[string][]string { + if o == nil || IsNil(o.RolesToLevels) { + var ret map[string][]string + return ret + } + return *o.RolesToLevels +} + +// GetRolesToLevelsOk returns a tuple with the RolesToLevels field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsEnvUpdate) GetRolesToLevelsOk() (*map[string][]string, bool) { + if o == nil || IsNil(o.RolesToLevels) { + return nil, false + } + return o.RolesToLevels, true +} + +// HasRolesToLevels returns a boolean if a field has been set. +func (o *ElementsEnvUpdate) HasRolesToLevels() bool { + if o != nil && !IsNil(o.RolesToLevels) { + return true + } + + return false +} + +// SetRolesToLevels gets a reference to the given map[string][]string and assigns it to the RolesToLevels field. +func (o *ElementsEnvUpdate) SetRolesToLevels(v map[string][]string) { + o.RolesToLevels = &v +} + +func (o ElementsEnvUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.RolesToLevels) { + toSerialize["roles_to_levels"] = o.RolesToLevels + } + return json.Marshal(toSerialize) +} + +type NullableElementsEnvUpdate struct { + value *ElementsEnvUpdate + isSet bool +} + +func (v NullableElementsEnvUpdate) Get() *ElementsEnvUpdate { + return v.value +} + +func (v *NullableElementsEnvUpdate) Set(val *ElementsEnvUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableElementsEnvUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsEnvUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsEnvUpdate(val *ElementsEnvUpdate) *NullableElementsEnvUpdate { + return &NullableElementsEnvUpdate{value: val, isSet: true} +} + +func (v NullableElementsEnvUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsEnvUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_permission_level.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_permission_level.go new file mode 100644 index 00000000..b8480249 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_permission_level.go @@ -0,0 +1,118 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ElementsPermissionLevel An enumeration. +type ElementsPermissionLevel string + +// List of ElementsPermissionLevel +const ( + LEVEL_1 ElementsPermissionLevel = "LEVEL_1" + LEVEL_2 ElementsPermissionLevel = "LEVEL_2" + LEVEL_3 ElementsPermissionLevel = "LEVEL_3" + LEVEL_4 ElementsPermissionLevel = "LEVEL_4" + HIDDEN ElementsPermissionLevel = "HIDDEN" + UNCONFIGURED ElementsPermissionLevel = "UNCONFIGURED" +) + +// All allowed values of ElementsPermissionLevel enum +var AllowedElementsPermissionLevelEnumValues = []ElementsPermissionLevel{ + "LEVEL_1", + "LEVEL_2", + "LEVEL_3", + "LEVEL_4", + "HIDDEN", + "UNCONFIGURED", +} + +func (v *ElementsPermissionLevel) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ElementsPermissionLevel(value) + for _, existing := range AllowedElementsPermissionLevelEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ElementsPermissionLevel", value) +} + +// NewElementsPermissionLevelFromValue returns a pointer to a valid ElementsPermissionLevel +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewElementsPermissionLevelFromValue(v string) (*ElementsPermissionLevel, error) { + ev := ElementsPermissionLevel(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ElementsPermissionLevel: valid values are %v", v, AllowedElementsPermissionLevelEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ElementsPermissionLevel) IsValid() bool { + for _, existing := range AllowedElementsPermissionLevelEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ElementsPermissionLevel value +func (v ElementsPermissionLevel) Ptr() *ElementsPermissionLevel { + return &v +} + +type NullableElementsPermissionLevel struct { + value *ElementsPermissionLevel + isSet bool +} + +func (v NullableElementsPermissionLevel) Get() *ElementsPermissionLevel { + return v.value +} + +func (v *NullableElementsPermissionLevel) Set(val *ElementsPermissionLevel) { + v.value = val + v.isSet = true +} + +func (v NullableElementsPermissionLevel) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsPermissionLevel) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsPermissionLevel(val *ElementsPermissionLevel) *NullableElementsPermissionLevel { + return &NullableElementsPermissionLevel{value: val, isSet: true} +} + +func (v NullableElementsPermissionLevel) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsPermissionLevel) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_role_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_role_read.go new file mode 100644 index 00000000..3efb9ba0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_role_read.go @@ -0,0 +1,458 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ElementsRoleRead struct for ElementsRoleRead +type ElementsRoleRead struct { + // The name of the role + Name string `json:"name"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` + // A URL-friendly name of the role (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the role. + Key string `json:"key"` + // Unique id of the role + Id string `json:"id"` + // Unique id of the organization that the role belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the role belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the role belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the role was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the role was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + PermissionLevel ElementsPermissionLevel `json:"permission_level"` +} + +// NewElementsRoleRead instantiates a new ElementsRoleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsRoleRead(name string, key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, permissionLevel ElementsPermissionLevel) *ElementsRoleRead { + this := ElementsRoleRead{} + this.Name = name + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.PermissionLevel = permissionLevel + return &this +} + +// NewElementsRoleReadWithDefaults instantiates a new ElementsRoleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsRoleReadWithDefaults() *ElementsRoleRead { + this := ElementsRoleRead{} + return &this +} + +// GetName returns the Name field value +func (o *ElementsRoleRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ElementsRoleRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ElementsRoleRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ElementsRoleRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ElementsRoleRead) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *ElementsRoleRead) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *ElementsRoleRead) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *ElementsRoleRead) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *ElementsRoleRead) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *ElementsRoleRead) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *ElementsRoleRead) SetExtends(v []string) { + o.Extends = v +} + +// GetKey returns the Key field value +func (o *ElementsRoleRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ElementsRoleRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ElementsRoleRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ElementsRoleRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ElementsRoleRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ElementsRoleRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ElementsRoleRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ElementsRoleRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ElementsRoleRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ElementsRoleRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ElementsRoleRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ElementsRoleRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ElementsRoleRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ElementsRoleRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetPermissionLevel returns the PermissionLevel field value +func (o *ElementsRoleRead) GetPermissionLevel() ElementsPermissionLevel { + if o == nil { + var ret ElementsPermissionLevel + return ret + } + + return o.PermissionLevel +} + +// GetPermissionLevelOk returns a tuple with the PermissionLevel field value +// and a boolean to check if the value has been set. +func (o *ElementsRoleRead) GetPermissionLevelOk() (*ElementsPermissionLevel, bool) { + if o == nil { + return nil, false + } + return &o.PermissionLevel, true +} + +// SetPermissionLevel sets field value +func (o *ElementsRoleRead) SetPermissionLevel(v ElementsPermissionLevel) { + o.PermissionLevel = v +} + +func (o ElementsRoleRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["permission_level"] = o.PermissionLevel + } + return json.Marshal(toSerialize) +} + +type NullableElementsRoleRead struct { + value *ElementsRoleRead + isSet bool +} + +func (v NullableElementsRoleRead) Get() *ElementsRoleRead { + return v.value +} + +func (v *NullableElementsRoleRead) Set(val *ElementsRoleRead) { + v.value = val + v.isSet = true +} + +func (v NullableElementsRoleRead) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsRoleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsRoleRead(val *ElementsRoleRead) *NullableElementsRoleRead { + return &NullableElementsRoleRead{value: val, isSet: true} +} + +func (v NullableElementsRoleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsRoleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_type.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_type.go new file mode 100644 index 00000000..195404df --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_type.go @@ -0,0 +1,112 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ElementsType An enumeration. +type ElementsType string + +// List of ElementsType +const ( + USER_MANAGEMENT ElementsType = "user_management" + AUDIT_LOG ElementsType = "audit_log" + APPROVAL_FLOW ElementsType = "approval_flow" +) + +// All allowed values of ElementsType enum +var AllowedElementsTypeEnumValues = []ElementsType{ + "user_management", + "audit_log", + "approval_flow", +} + +func (v *ElementsType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ElementsType(value) + for _, existing := range AllowedElementsTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ElementsType", value) +} + +// NewElementsTypeFromValue returns a pointer to a valid ElementsType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewElementsTypeFromValue(v string) (*ElementsType, error) { + ev := ElementsType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ElementsType: valid values are %v", v, AllowedElementsTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ElementsType) IsValid() bool { + for _, existing := range AllowedElementsTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ElementsType value +func (v ElementsType) Ptr() *ElementsType { + return &v +} + +type NullableElementsType struct { + value *ElementsType + isSet bool +} + +func (v NullableElementsType) Get() *ElementsType { + return v.value +} + +func (v *NullableElementsType) Set(val *ElementsType) { + v.value = val + v.isSet = true +} + +func (v NullableElementsType) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsType(val *ElementsType) *NullableElementsType { + return &NullableElementsType{value: val, isSet: true} +} + +func (v NullableElementsType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_create.go new file mode 100644 index 00000000..0e95881a --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_create.go @@ -0,0 +1,291 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsUserCreate struct for ElementsUserCreate +type ElementsUserCreate struct { + // A unique id by which Permit will identify the user for permission checks. + Key string `json:"key"` + // The email of the user. If synced, will be unique inside the environment. + Email *string `json:"email,omitempty"` + // First name of the user. + FirstName *string `json:"first_name,omitempty"` + // Last name of the user. + LastName *string `json:"last_name,omitempty"` + // Arbitraty user attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` + Role *string `json:"role,omitempty"` +} + +// NewElementsUserCreate instantiates a new ElementsUserCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsUserCreate(key string) *ElementsUserCreate { + this := ElementsUserCreate{} + this.Key = key + return &this +} + +// NewElementsUserCreateWithDefaults instantiates a new ElementsUserCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsUserCreateWithDefaults() *ElementsUserCreate { + this := ElementsUserCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ElementsUserCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ElementsUserCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ElementsUserCreate) SetKey(v string) { + o.Key = v +} + +// GetEmail returns the Email field value if set, zero value otherwise. +func (o *ElementsUserCreate) GetEmail() string { + if o == nil || IsNil(o.Email) { + var ret string + return ret + } + return *o.Email +} + +// GetEmailOk returns a tuple with the Email field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsUserCreate) GetEmailOk() (*string, bool) { + if o == nil || IsNil(o.Email) { + return nil, false + } + return o.Email, true +} + +// HasEmail returns a boolean if a field has been set. +func (o *ElementsUserCreate) HasEmail() bool { + if o != nil && !IsNil(o.Email) { + return true + } + + return false +} + +// SetEmail gets a reference to the given string and assigns it to the Email field. +func (o *ElementsUserCreate) SetEmail(v string) { + o.Email = &v +} + +// GetFirstName returns the FirstName field value if set, zero value otherwise. +func (o *ElementsUserCreate) GetFirstName() string { + if o == nil || IsNil(o.FirstName) { + var ret string + return ret + } + return *o.FirstName +} + +// GetFirstNameOk returns a tuple with the FirstName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsUserCreate) GetFirstNameOk() (*string, bool) { + if o == nil || IsNil(o.FirstName) { + return nil, false + } + return o.FirstName, true +} + +// HasFirstName returns a boolean if a field has been set. +func (o *ElementsUserCreate) HasFirstName() bool { + if o != nil && !IsNil(o.FirstName) { + return true + } + + return false +} + +// SetFirstName gets a reference to the given string and assigns it to the FirstName field. +func (o *ElementsUserCreate) SetFirstName(v string) { + o.FirstName = &v +} + +// GetLastName returns the LastName field value if set, zero value otherwise. +func (o *ElementsUserCreate) GetLastName() string { + if o == nil || IsNil(o.LastName) { + var ret string + return ret + } + return *o.LastName +} + +// GetLastNameOk returns a tuple with the LastName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsUserCreate) GetLastNameOk() (*string, bool) { + if o == nil || IsNil(o.LastName) { + return nil, false + } + return o.LastName, true +} + +// HasLastName returns a boolean if a field has been set. +func (o *ElementsUserCreate) HasLastName() bool { + if o != nil && !IsNil(o.LastName) { + return true + } + + return false +} + +// SetLastName gets a reference to the given string and assigns it to the LastName field. +func (o *ElementsUserCreate) SetLastName(v string) { + o.LastName = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ElementsUserCreate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsUserCreate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ElementsUserCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ElementsUserCreate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +// GetRole returns the Role field value if set, zero value otherwise. +func (o *ElementsUserCreate) GetRole() string { + if o == nil || IsNil(o.Role) { + var ret string + return ret + } + return *o.Role +} + +// GetRoleOk returns a tuple with the Role field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ElementsUserCreate) GetRoleOk() (*string, bool) { + if o == nil || IsNil(o.Role) { + return nil, false + } + return o.Role, true +} + +// HasRole returns a boolean if a field has been set. +func (o *ElementsUserCreate) HasRole() bool { + if o != nil && !IsNil(o.Role) { + return true + } + + return false +} + +// SetRole gets a reference to the given string and assigns it to the Role field. +func (o *ElementsUserCreate) SetRole(v string) { + o.Role = &v +} + +func (o ElementsUserCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if !IsNil(o.Email) { + toSerialize["email"] = o.Email + } + if !IsNil(o.FirstName) { + toSerialize["first_name"] = o.FirstName + } + if !IsNil(o.LastName) { + toSerialize["last_name"] = o.LastName + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + if !IsNil(o.Role) { + toSerialize["role"] = o.Role + } + return json.Marshal(toSerialize) +} + +type NullableElementsUserCreate struct { + value *ElementsUserCreate + isSet bool +} + +func (v NullableElementsUserCreate) Get() *ElementsUserCreate { + return v.value +} + +func (v *NullableElementsUserCreate) Set(val *ElementsUserCreate) { + v.value = val + v.isSet = true +} + +func (v NullableElementsUserCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsUserCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsUserCreate(val *ElementsUserCreate) *NullableElementsUserCreate { + return &NullableElementsUserCreate{value: val, isSet: true} +} + +func (v NullableElementsUserCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsUserCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_create.go new file mode 100644 index 00000000..198f1f2c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_create.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsUserRoleCreate struct for ElementsUserRoleCreate +type ElementsUserRoleCreate struct { + // the role that will be assigned (accepts either the role id or the role key) + Role string `json:"role"` +} + +// NewElementsUserRoleCreate instantiates a new ElementsUserRoleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsUserRoleCreate(role string) *ElementsUserRoleCreate { + this := ElementsUserRoleCreate{} + this.Role = role + return &this +} + +// NewElementsUserRoleCreateWithDefaults instantiates a new ElementsUserRoleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsUserRoleCreateWithDefaults() *ElementsUserRoleCreate { + this := ElementsUserRoleCreate{} + return &this +} + +// GetRole returns the Role field value +func (o *ElementsUserRoleCreate) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *ElementsUserRoleCreate) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *ElementsUserRoleCreate) SetRole(v string) { + o.Role = v +} + +func (o ElementsUserRoleCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["role"] = o.Role + } + return json.Marshal(toSerialize) +} + +type NullableElementsUserRoleCreate struct { + value *ElementsUserRoleCreate + isSet bool +} + +func (v NullableElementsUserRoleCreate) Get() *ElementsUserRoleCreate { + return v.value +} + +func (v *NullableElementsUserRoleCreate) Set(val *ElementsUserRoleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableElementsUserRoleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsUserRoleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsUserRoleCreate(val *ElementsUserRoleCreate) *NullableElementsUserRoleCreate { + return &NullableElementsUserRoleCreate{value: val, isSet: true} +} + +func (v NullableElementsUserRoleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsUserRoleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_remove.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_remove.go new file mode 100644 index 00000000..d32c1f62 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_elements_user_role_remove.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ElementsUserRoleRemove struct for ElementsUserRoleRemove +type ElementsUserRoleRemove struct { + // the role that will be unassigned (accepts either the role id or the role key) + Role string `json:"role"` +} + +// NewElementsUserRoleRemove instantiates a new ElementsUserRoleRemove object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewElementsUserRoleRemove(role string) *ElementsUserRoleRemove { + this := ElementsUserRoleRemove{} + this.Role = role + return &this +} + +// NewElementsUserRoleRemoveWithDefaults instantiates a new ElementsUserRoleRemove object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewElementsUserRoleRemoveWithDefaults() *ElementsUserRoleRemove { + this := ElementsUserRoleRemove{} + return &this +} + +// GetRole returns the Role field value +func (o *ElementsUserRoleRemove) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *ElementsUserRoleRemove) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *ElementsUserRoleRemove) SetRole(v string) { + o.Role = v +} + +func (o ElementsUserRoleRemove) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["role"] = o.Role + } + return json.Marshal(toSerialize) +} + +type NullableElementsUserRoleRemove struct { + value *ElementsUserRoleRemove + isSet bool +} + +func (v NullableElementsUserRoleRemove) Get() *ElementsUserRoleRemove { + return v.value +} + +func (v *NullableElementsUserRoleRemove) Set(val *ElementsUserRoleRemove) { + v.value = val + v.isSet = true +} + +func (v NullableElementsUserRoleRemove) IsSet() bool { + return v.isSet +} + +func (v *NullableElementsUserRoleRemove) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableElementsUserRoleRemove(val *ElementsUserRoleRemove) *NullableElementsUserRoleRemove { + return &NullableElementsUserRoleRemove{value: val, isSet: true} +} + +func (v NullableElementsUserRoleRemove) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableElementsUserRoleRemove) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_embedded_login_request_output.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_embedded_login_request_output.go new file mode 100644 index 00000000..50d109b0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_embedded_login_request_output.go @@ -0,0 +1,255 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// EmbeddedLoginRequestOutput struct for EmbeddedLoginRequestOutput +type EmbeddedLoginRequestOutput struct { + // If the login request failed, this field will contain the error message + Error *string `json:"error,omitempty"` + // If the login request failed, this field will contain the error code + ErrorCode *int32 `json:"error_code,omitempty"` + // The auth token that lets your users login into permit elements + Token *string `json:"token,omitempty"` + // Extra data that you can pass to the login request + Extra *string `json:"extra,omitempty"` + // The full URL to which the user should be redirected in order to complete the login process + RedirectUrl string `json:"redirect_url"` +} + +// NewEmbeddedLoginRequestOutput instantiates a new EmbeddedLoginRequestOutput object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEmbeddedLoginRequestOutput(redirectUrl string) *EmbeddedLoginRequestOutput { + this := EmbeddedLoginRequestOutput{} + this.RedirectUrl = redirectUrl + return &this +} + +// NewEmbeddedLoginRequestOutputWithDefaults instantiates a new EmbeddedLoginRequestOutput object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEmbeddedLoginRequestOutputWithDefaults() *EmbeddedLoginRequestOutput { + this := EmbeddedLoginRequestOutput{} + return &this +} + +// GetError returns the Error field value if set, zero value otherwise. +func (o *EmbeddedLoginRequestOutput) GetError() string { + if o == nil || IsNil(o.Error) { + var ret string + return ret + } + return *o.Error +} + +// GetErrorOk returns a tuple with the Error field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EmbeddedLoginRequestOutput) GetErrorOk() (*string, bool) { + if o == nil || IsNil(o.Error) { + return nil, false + } + return o.Error, true +} + +// HasError returns a boolean if a field has been set. +func (o *EmbeddedLoginRequestOutput) HasError() bool { + if o != nil && !IsNil(o.Error) { + return true + } + + return false +} + +// SetError gets a reference to the given string and assigns it to the Error field. +func (o *EmbeddedLoginRequestOutput) SetError(v string) { + o.Error = &v +} + +// GetErrorCode returns the ErrorCode field value if set, zero value otherwise. +func (o *EmbeddedLoginRequestOutput) GetErrorCode() int32 { + if o == nil || IsNil(o.ErrorCode) { + var ret int32 + return ret + } + return *o.ErrorCode +} + +// GetErrorCodeOk returns a tuple with the ErrorCode field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EmbeddedLoginRequestOutput) GetErrorCodeOk() (*int32, bool) { + if o == nil || IsNil(o.ErrorCode) { + return nil, false + } + return o.ErrorCode, true +} + +// HasErrorCode returns a boolean if a field has been set. +func (o *EmbeddedLoginRequestOutput) HasErrorCode() bool { + if o != nil && !IsNil(o.ErrorCode) { + return true + } + + return false +} + +// SetErrorCode gets a reference to the given int32 and assigns it to the ErrorCode field. +func (o *EmbeddedLoginRequestOutput) SetErrorCode(v int32) { + o.ErrorCode = &v +} + +// GetToken returns the Token field value if set, zero value otherwise. +func (o *EmbeddedLoginRequestOutput) GetToken() string { + if o == nil || IsNil(o.Token) { + var ret string + return ret + } + return *o.Token +} + +// GetTokenOk returns a tuple with the Token field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EmbeddedLoginRequestOutput) GetTokenOk() (*string, bool) { + if o == nil || IsNil(o.Token) { + return nil, false + } + return o.Token, true +} + +// HasToken returns a boolean if a field has been set. +func (o *EmbeddedLoginRequestOutput) HasToken() bool { + if o != nil && !IsNil(o.Token) { + return true + } + + return false +} + +// SetToken gets a reference to the given string and assigns it to the Token field. +func (o *EmbeddedLoginRequestOutput) SetToken(v string) { + o.Token = &v +} + +// GetExtra returns the Extra field value if set, zero value otherwise. +func (o *EmbeddedLoginRequestOutput) GetExtra() string { + if o == nil || IsNil(o.Extra) { + var ret string + return ret + } + return *o.Extra +} + +// GetExtraOk returns a tuple with the Extra field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EmbeddedLoginRequestOutput) GetExtraOk() (*string, bool) { + if o == nil || IsNil(o.Extra) { + return nil, false + } + return o.Extra, true +} + +// HasExtra returns a boolean if a field has been set. +func (o *EmbeddedLoginRequestOutput) HasExtra() bool { + if o != nil && !IsNil(o.Extra) { + return true + } + + return false +} + +// SetExtra gets a reference to the given string and assigns it to the Extra field. +func (o *EmbeddedLoginRequestOutput) SetExtra(v string) { + o.Extra = &v +} + +// GetRedirectUrl returns the RedirectUrl field value +func (o *EmbeddedLoginRequestOutput) GetRedirectUrl() string { + if o == nil { + var ret string + return ret + } + + return o.RedirectUrl +} + +// GetRedirectUrlOk returns a tuple with the RedirectUrl field value +// and a boolean to check if the value has been set. +func (o *EmbeddedLoginRequestOutput) GetRedirectUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RedirectUrl, true +} + +// SetRedirectUrl sets field value +func (o *EmbeddedLoginRequestOutput) SetRedirectUrl(v string) { + o.RedirectUrl = v +} + +func (o EmbeddedLoginRequestOutput) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Error) { + toSerialize["error"] = o.Error + } + if !IsNil(o.ErrorCode) { + toSerialize["error_code"] = o.ErrorCode + } + if !IsNil(o.Token) { + toSerialize["token"] = o.Token + } + if !IsNil(o.Extra) { + toSerialize["extra"] = o.Extra + } + if true { + toSerialize["redirect_url"] = o.RedirectUrl + } + return json.Marshal(toSerialize) +} + +type NullableEmbeddedLoginRequestOutput struct { + value *EmbeddedLoginRequestOutput + isSet bool +} + +func (v NullableEmbeddedLoginRequestOutput) Get() *EmbeddedLoginRequestOutput { + return v.value +} + +func (v *NullableEmbeddedLoginRequestOutput) Set(val *EmbeddedLoginRequestOutput) { + v.value = val + v.isSet = true +} + +func (v NullableEmbeddedLoginRequestOutput) IsSet() bool { + return v.isSet +} + +func (v *NullableEmbeddedLoginRequestOutput) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEmbeddedLoginRequestOutput(val *EmbeddedLoginRequestOutput) *NullableEmbeddedLoginRequestOutput { + return &NullableEmbeddedLoginRequestOutput{value: val, isSet: true} +} + +func (v NullableEmbeddedLoginRequestOutput) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEmbeddedLoginRequestOutput) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy.go new file mode 100644 index 00000000..0ae50319 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy.go @@ -0,0 +1,192 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the EnvironmentCopy type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &EnvironmentCopy{} + +// EnvironmentCopy struct for EnvironmentCopy +type EnvironmentCopy struct { + TargetEnv TargetEnv `json:"target_env"` + // Action to take when detecting a conflict when copying. Only applies to copying into an existing environment + ConflictStrategy *string `json:"conflict_strategy,omitempty"` + Scope *Scope `json:"scope,omitempty"` +} + +// NewEnvironmentCopy instantiates a new EnvironmentCopy object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentCopy(targetEnv TargetEnv) *EnvironmentCopy { + this := EnvironmentCopy{} + this.TargetEnv = targetEnv + var conflictStrategy string = "fail" + this.ConflictStrategy = &conflictStrategy + return &this +} + +// NewEnvironmentCopyWithDefaults instantiates a new EnvironmentCopy object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentCopyWithDefaults() *EnvironmentCopy { + this := EnvironmentCopy{} + var conflictStrategy string = "fail" + this.ConflictStrategy = &conflictStrategy + return &this +} + +// GetTargetEnv returns the TargetEnv field value +func (o *EnvironmentCopy) GetTargetEnv() TargetEnv { + if o == nil { + var ret TargetEnv + return ret + } + + return o.TargetEnv +} + +// GetTargetEnvOk returns a tuple with the TargetEnv field value +// and a boolean to check if the value has been set. +func (o *EnvironmentCopy) GetTargetEnvOk() (*TargetEnv, bool) { + if o == nil { + return nil, false + } + return &o.TargetEnv, true +} + +// SetTargetEnv sets field value +func (o *EnvironmentCopy) SetTargetEnv(v TargetEnv) { + o.TargetEnv = v +} + +// GetConflictStrategy returns the ConflictStrategy field value if set, zero value otherwise. +func (o *EnvironmentCopy) GetConflictStrategy() string { + if o == nil || IsNil(o.ConflictStrategy) { + var ret string + return ret + } + return *o.ConflictStrategy +} + +// GetConflictStrategyOk returns a tuple with the ConflictStrategy field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopy) GetConflictStrategyOk() (*string, bool) { + if o == nil || IsNil(o.ConflictStrategy) { + return nil, false + } + return o.ConflictStrategy, true +} + +// HasConflictStrategy returns a boolean if a field has been set. +func (o *EnvironmentCopy) HasConflictStrategy() bool { + if o != nil && !IsNil(o.ConflictStrategy) { + return true + } + + return false +} + +// SetConflictStrategy gets a reference to the given string and assigns it to the ConflictStrategy field. +func (o *EnvironmentCopy) SetConflictStrategy(v string) { + o.ConflictStrategy = &v +} + +// GetScope returns the Scope field value if set, zero value otherwise. +func (o *EnvironmentCopy) GetScope() Scope { + if o == nil || IsNil(o.Scope) { + var ret Scope + return ret + } + return *o.Scope +} + +// GetScopeOk returns a tuple with the Scope field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopy) GetScopeOk() (*Scope, bool) { + if o == nil || IsNil(o.Scope) { + return nil, false + } + return o.Scope, true +} + +// HasScope returns a boolean if a field has been set. +func (o *EnvironmentCopy) HasScope() bool { + if o != nil && !IsNil(o.Scope) { + return true + } + + return false +} + +// SetScope gets a reference to the given Scope and assigns it to the Scope field. +func (o *EnvironmentCopy) SetScope(v Scope) { + o.Scope = &v +} + +func (o EnvironmentCopy) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o EnvironmentCopy) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["target_env"] = o.TargetEnv + if !IsNil(o.ConflictStrategy) { + toSerialize["conflict_strategy"] = o.ConflictStrategy + } + if !IsNil(o.Scope) { + toSerialize["scope"] = o.Scope + } + return toSerialize, nil +} + +type NullableEnvironmentCopy struct { + value *EnvironmentCopy + isSet bool +} + +func (v NullableEnvironmentCopy) Get() *EnvironmentCopy { + return v.value +} + +func (v *NullableEnvironmentCopy) Set(val *EnvironmentCopy) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentCopy) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentCopy) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentCopy(val *EnvironmentCopy) *NullableEnvironmentCopy { + return &NullableEnvironmentCopy{value: val, isSet: true} +} + +func (v NullableEnvironmentCopy) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentCopy) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope.go new file mode 100644 index 00000000..355197e6 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope.go @@ -0,0 +1,232 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the EnvironmentCopyScope type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &EnvironmentCopyScope{} + +// EnvironmentCopyScope struct for EnvironmentCopyScope +type EnvironmentCopyScope struct { + Resources *Resources `json:"resources,omitempty"` + Roles *CopyEnvironmentScopeRoles `json:"roles,omitempty"` + UserSets *UserSets `json:"user_sets,omitempty"` + ResourceSets *ResourceSets `json:"resource_sets,omitempty"` +} + +// NewEnvironmentCopyScope instantiates a new EnvironmentCopyScope object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentCopyScope() *EnvironmentCopyScope { + this := EnvironmentCopyScope{} + return &this +} + +// NewEnvironmentCopyScopeWithDefaults instantiates a new EnvironmentCopyScope object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentCopyScopeWithDefaults() *EnvironmentCopyScope { + this := EnvironmentCopyScope{} + return &this +} + +// GetResources returns the Resources field value if set, zero value otherwise. +func (o *EnvironmentCopyScope) GetResources() Resources { + if o == nil || IsNil(o.Resources) { + var ret Resources + return ret + } + return *o.Resources +} + +// GetResourcesOk returns a tuple with the Resources field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyScope) GetResourcesOk() (*Resources, bool) { + if o == nil || IsNil(o.Resources) { + return nil, false + } + return o.Resources, true +} + +// HasResources returns a boolean if a field has been set. +func (o *EnvironmentCopyScope) HasResources() bool { + if o != nil && !IsNil(o.Resources) { + return true + } + + return false +} + +// SetResources gets a reference to the given Resources and assigns it to the Resources field. +func (o *EnvironmentCopyScope) SetResources(v Resources) { + o.Resources = &v +} + +// GetRoles returns the Roles field value if set, zero value otherwise. +func (o *EnvironmentCopyScope) GetRoles() CopyEnvironmentScopeRoles { + if o == nil || IsNil(o.Roles) { + var ret CopyEnvironmentScopeRoles + return ret + } + return *o.Roles +} + +// GetRolesOk returns a tuple with the Roles field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyScope) GetRolesOk() (*CopyEnvironmentScopeRoles, bool) { + if o == nil || IsNil(o.Roles) { + return nil, false + } + return o.Roles, true +} + +// HasRoles returns a boolean if a field has been set. +func (o *EnvironmentCopyScope) HasRoles() bool { + if o != nil && !IsNil(o.Roles) { + return true + } + + return false +} + +// SetRoles gets a reference to the given Roles and assigns it to the Roles field. +func (o *EnvironmentCopyScope) SetRoles(v CopyEnvironmentScopeRoles) { + o.Roles = &v +} + +// GetUserSets returns the UserSets field value if set, zero value otherwise. +func (o *EnvironmentCopyScope) GetUserSets() UserSets { + if o == nil || IsNil(o.UserSets) { + var ret UserSets + return ret + } + return *o.UserSets +} + +// GetUserSetsOk returns a tuple with the UserSets field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyScope) GetUserSetsOk() (*UserSets, bool) { + if o == nil || IsNil(o.UserSets) { + return nil, false + } + return o.UserSets, true +} + +// HasUserSets returns a boolean if a field has been set. +func (o *EnvironmentCopyScope) HasUserSets() bool { + if o != nil && !IsNil(o.UserSets) { + return true + } + + return false +} + +// SetUserSets gets a reference to the given UserSets and assigns it to the UserSets field. +func (o *EnvironmentCopyScope) SetUserSets(v UserSets) { + o.UserSets = &v +} + +// GetResourceSets returns the ResourceSets field value if set, zero value otherwise. +func (o *EnvironmentCopyScope) GetResourceSets() ResourceSets { + if o == nil || IsNil(o.ResourceSets) { + var ret ResourceSets + return ret + } + return *o.ResourceSets +} + +// GetResourceSetsOk returns a tuple with the ResourceSets field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyScope) GetResourceSetsOk() (*ResourceSets, bool) { + if o == nil || IsNil(o.ResourceSets) { + return nil, false + } + return o.ResourceSets, true +} + +// HasResourceSets returns a boolean if a field has been set. +func (o *EnvironmentCopyScope) HasResourceSets() bool { + if o != nil && !IsNil(o.ResourceSets) { + return true + } + + return false +} + +// SetResourceSets gets a reference to the given ResourceSets and assigns it to the ResourceSets field. +func (o *EnvironmentCopyScope) SetResourceSets(v ResourceSets) { + o.ResourceSets = &v +} + +func (o EnvironmentCopyScope) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o EnvironmentCopyScope) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Resources) { + toSerialize["resources"] = o.Resources + } + if !IsNil(o.Roles) { + toSerialize["roles"] = o.Roles + } + if !IsNil(o.UserSets) { + toSerialize["user_sets"] = o.UserSets + } + if !IsNil(o.ResourceSets) { + toSerialize["resource_sets"] = o.ResourceSets + } + return toSerialize, nil +} + +type NullableEnvironmentCopyScope struct { + value *EnvironmentCopyScope + isSet bool +} + +func (v NullableEnvironmentCopyScope) Get() *EnvironmentCopyScope { + return v.value +} + +func (v *NullableEnvironmentCopyScope) Set(val *EnvironmentCopyScope) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentCopyScope) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentCopyScope) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentCopyScope(val *EnvironmentCopyScope) *NullableEnvironmentCopyScope { + return &NullableEnvironmentCopyScope{value: val, isSet: true} +} + +func (v NullableEnvironmentCopyScope) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentCopyScope) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope_filters.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope_filters.go new file mode 100644 index 00000000..c033e65f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_scope_filters.go @@ -0,0 +1,162 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the EnvironmentCopyScopeFilters type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &EnvironmentCopyScopeFilters{} + +// EnvironmentCopyScopeFilters struct for EnvironmentCopyScopeFilters +type EnvironmentCopyScopeFilters struct { + // Objects to include (use * as wildcard) + Include []string `json:"include,omitempty"` + // Object to exclude (use * as wildcard) + Exclude []string `json:"exclude,omitempty"` +} + +// NewEnvironmentCopyScopeFilters instantiates a new EnvironmentCopyScopeFilters object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentCopyScopeFilters() *EnvironmentCopyScopeFilters { + this := EnvironmentCopyScopeFilters{} + return &this +} + +// NewEnvironmentCopyScopeFiltersWithDefaults instantiates a new EnvironmentCopyScopeFilters object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentCopyScopeFiltersWithDefaults() *EnvironmentCopyScopeFilters { + this := EnvironmentCopyScopeFilters{} + return &this +} + +// GetInclude returns the Include field value if set, zero value otherwise. +func (o *EnvironmentCopyScopeFilters) GetInclude() []string { + if o == nil || IsNil(o.Include) { + var ret []string + return ret + } + return o.Include +} + +// GetIncludeOk returns a tuple with the Include field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyScopeFilters) GetIncludeOk() ([]string, bool) { + if o == nil || IsNil(o.Include) { + return nil, false + } + return o.Include, true +} + +// HasInclude returns a boolean if a field has been set. +func (o *EnvironmentCopyScopeFilters) HasInclude() bool { + if o != nil && !IsNil(o.Include) { + return true + } + + return false +} + +// SetInclude gets a reference to the given []string and assigns it to the Include field. +func (o *EnvironmentCopyScopeFilters) SetInclude(v []string) { + o.Include = v +} + +// GetExclude returns the Exclude field value if set, zero value otherwise. +func (o *EnvironmentCopyScopeFilters) GetExclude() []string { + if o == nil || IsNil(o.Exclude) { + var ret []string + return ret + } + return o.Exclude +} + +// GetExcludeOk returns a tuple with the Exclude field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyScopeFilters) GetExcludeOk() ([]string, bool) { + if o == nil || IsNil(o.Exclude) { + return nil, false + } + return o.Exclude, true +} + +// HasExclude returns a boolean if a field has been set. +func (o *EnvironmentCopyScopeFilters) HasExclude() bool { + if o != nil && !IsNil(o.Exclude) { + return true + } + + return false +} + +// SetExclude gets a reference to the given []string and assigns it to the Exclude field. +func (o *EnvironmentCopyScopeFilters) SetExclude(v []string) { + o.Exclude = v +} + +func (o EnvironmentCopyScopeFilters) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o EnvironmentCopyScopeFilters) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Include) { + toSerialize["include"] = o.Include + } + if !IsNil(o.Exclude) { + toSerialize["exclude"] = o.Exclude + } + return toSerialize, nil +} + +type NullableEnvironmentCopyScopeFilters struct { + value *EnvironmentCopyScopeFilters + isSet bool +} + +func (v NullableEnvironmentCopyScopeFilters) Get() *EnvironmentCopyScopeFilters { + return v.value +} + +func (v *NullableEnvironmentCopyScopeFilters) Set(val *EnvironmentCopyScopeFilters) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentCopyScopeFilters) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentCopyScopeFilters) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentCopyScopeFilters(val *EnvironmentCopyScopeFilters) *NullableEnvironmentCopyScopeFilters { + return &NullableEnvironmentCopyScopeFilters{value: val, isSet: true} +} + +func (v NullableEnvironmentCopyScopeFilters) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentCopyScopeFilters) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_target.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_target.go new file mode 100644 index 00000000..2d4d2b5f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_copy_target.go @@ -0,0 +1,161 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the EnvironmentCopyTarget type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &EnvironmentCopyTarget{} + +// EnvironmentCopyTarget struct for EnvironmentCopyTarget +type EnvironmentCopyTarget struct { + // Identifier of an existing environment to copy into + Existing *string `json:"existing,omitempty"` + New *New `json:"new,omitempty"` +} + +// NewEnvironmentCopyTarget instantiates a new EnvironmentCopyTarget object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentCopyTarget() *EnvironmentCopyTarget { + this := EnvironmentCopyTarget{} + return &this +} + +// NewEnvironmentCopyTargetWithDefaults instantiates a new EnvironmentCopyTarget object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentCopyTargetWithDefaults() *EnvironmentCopyTarget { + this := EnvironmentCopyTarget{} + return &this +} + +// GetExisting returns the Existing field value if set, zero value otherwise. +func (o *EnvironmentCopyTarget) GetExisting() string { + if o == nil || IsNil(o.Existing) { + var ret string + return ret + } + return *o.Existing +} + +// GetExistingOk returns a tuple with the Existing field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyTarget) GetExistingOk() (*string, bool) { + if o == nil || IsNil(o.Existing) { + return nil, false + } + return o.Existing, true +} + +// HasExisting returns a boolean if a field has been set. +func (o *EnvironmentCopyTarget) HasExisting() bool { + if o != nil && !IsNil(o.Existing) { + return true + } + + return false +} + +// SetExisting gets a reference to the given string and assigns it to the Existing field. +func (o *EnvironmentCopyTarget) SetExisting(v string) { + o.Existing = &v +} + +// GetNew returns the New field value if set, zero value otherwise. +func (o *EnvironmentCopyTarget) GetNew() New { + if o == nil || IsNil(o.New) { + var ret New + return ret + } + return *o.New +} + +// GetNewOk returns a tuple with the New field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCopyTarget) GetNewOk() (*New, bool) { + if o == nil || IsNil(o.New) { + return nil, false + } + return o.New, true +} + +// HasNew returns a boolean if a field has been set. +func (o *EnvironmentCopyTarget) HasNew() bool { + if o != nil && !IsNil(o.New) { + return true + } + + return false +} + +// SetNew gets a reference to the given New and assigns it to the New field. +func (o *EnvironmentCopyTarget) SetNew(v New) { + o.New = &v +} + +func (o EnvironmentCopyTarget) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o EnvironmentCopyTarget) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Existing) { + toSerialize["existing"] = o.Existing + } + if !IsNil(o.New) { + toSerialize["new"] = o.New + } + return toSerialize, nil +} + +type NullableEnvironmentCopyTarget struct { + value *EnvironmentCopyTarget + isSet bool +} + +func (v NullableEnvironmentCopyTarget) Get() *EnvironmentCopyTarget { + return v.value +} + +func (v *NullableEnvironmentCopyTarget) Set(val *EnvironmentCopyTarget) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentCopyTarget) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentCopyTarget) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentCopyTarget(val *EnvironmentCopyTarget) *NullableEnvironmentCopyTarget { + return &NullableEnvironmentCopyTarget{value: val, isSet: true} +} + +func (v NullableEnvironmentCopyTarget) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentCopyTarget) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_create.go new file mode 100644 index 00000000..3e8b3d5e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_create.go @@ -0,0 +1,211 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// EnvironmentCreate struct for EnvironmentCreate +type EnvironmentCreate struct { + // A URL-friendly name of the environment (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the environment. + Key string `json:"key"` + // The name of the environment + Name string `json:"name"` + // an optional longer description of the environment + Description *string `json:"description,omitempty"` + // when using gitops feature, an optional branch name for the environment + CustomBranchName *string `json:"custom_branch_name,omitempty"` +} + +// NewEnvironmentCreate instantiates a new EnvironmentCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentCreate(key string, name string) *EnvironmentCreate { + this := EnvironmentCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewEnvironmentCreateWithDefaults instantiates a new EnvironmentCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentCreateWithDefaults() *EnvironmentCreate { + this := EnvironmentCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *EnvironmentCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *EnvironmentCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *EnvironmentCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *EnvironmentCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *EnvironmentCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *EnvironmentCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *EnvironmentCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *EnvironmentCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *EnvironmentCreate) SetDescription(v string) { + o.Description = &v +} + +// GetCustomBranchName returns the CustomBranchName field value if set, zero value otherwise. +func (o *EnvironmentCreate) GetCustomBranchName() string { + if o == nil || IsNil(o.CustomBranchName) { + var ret string + return ret + } + return *o.CustomBranchName +} + +// GetCustomBranchNameOk returns a tuple with the CustomBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentCreate) GetCustomBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.CustomBranchName) { + return nil, false + } + return o.CustomBranchName, true +} + +// HasCustomBranchName returns a boolean if a field has been set. +func (o *EnvironmentCreate) HasCustomBranchName() bool { + if o != nil && !IsNil(o.CustomBranchName) { + return true + } + + return false +} + +// SetCustomBranchName gets a reference to the given string and assigns it to the CustomBranchName field. +func (o *EnvironmentCreate) SetCustomBranchName(v string) { + o.CustomBranchName = &v +} + +func (o EnvironmentCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.CustomBranchName) { + toSerialize["custom_branch_name"] = o.CustomBranchName + } + return json.Marshal(toSerialize) +} + +type NullableEnvironmentCreate struct { + value *EnvironmentCreate + isSet bool +} + +func (v NullableEnvironmentCreate) Get() *EnvironmentCreate { + return v.value +} + +func (v *NullableEnvironmentCreate) Set(val *EnvironmentCreate) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentCreate(val *EnvironmentCreate) *NullableEnvironmentCreate { + return &NullableEnvironmentCreate{value: val, isSet: true} +} + +func (v NullableEnvironmentCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_read.go new file mode 100644 index 00000000..7695e760 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_read.go @@ -0,0 +1,362 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// EnvironmentRead struct for EnvironmentRead +type EnvironmentRead struct { + // A URL-friendly name of the environment (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the environment. + Key string `json:"key"` + // Unique id of the environment + Id string `json:"id"` + // Unique id of the organization that the environment belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the environment belongs to. + ProjectId string `json:"project_id"` + // Date and time when the environment was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the environment was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The name of the environment + Name string `json:"name"` + // an optional longer description of the environment + Description *string `json:"description,omitempty"` + // when using gitops feature, an optional branch name for the environment + CustomBranchName *string `json:"custom_branch_name,omitempty"` +} + +// NewEnvironmentRead instantiates a new EnvironmentRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentRead(key string, id string, organizationId string, projectId string, createdAt time.Time, updatedAt time.Time, name string) *EnvironmentRead { + this := EnvironmentRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + return &this +} + +// NewEnvironmentReadWithDefaults instantiates a new EnvironmentRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentReadWithDefaults() *EnvironmentRead { + this := EnvironmentRead{} + return &this +} + +// GetKey returns the Key field value +func (o *EnvironmentRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *EnvironmentRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *EnvironmentRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *EnvironmentRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *EnvironmentRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *EnvironmentRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *EnvironmentRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *EnvironmentRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *EnvironmentRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *EnvironmentRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *EnvironmentRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *EnvironmentRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetName returns the Name field value +func (o *EnvironmentRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *EnvironmentRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *EnvironmentRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *EnvironmentRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *EnvironmentRead) SetDescription(v string) { + o.Description = &v +} + +// GetCustomBranchName returns the CustomBranchName field value if set, zero value otherwise. +func (o *EnvironmentRead) GetCustomBranchName() string { + if o == nil || IsNil(o.CustomBranchName) { + var ret string + return ret + } + return *o.CustomBranchName +} + +// GetCustomBranchNameOk returns a tuple with the CustomBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentRead) GetCustomBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.CustomBranchName) { + return nil, false + } + return o.CustomBranchName, true +} + +// HasCustomBranchName returns a boolean if a field has been set. +func (o *EnvironmentRead) HasCustomBranchName() bool { + if o != nil && !IsNil(o.CustomBranchName) { + return true + } + + return false +} + +// SetCustomBranchName gets a reference to the given string and assigns it to the CustomBranchName field. +func (o *EnvironmentRead) SetCustomBranchName(v string) { + o.CustomBranchName = &v +} + +func (o EnvironmentRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.CustomBranchName) { + toSerialize["custom_branch_name"] = o.CustomBranchName + } + return json.Marshal(toSerialize) +} + +type NullableEnvironmentRead struct { + value *EnvironmentRead + isSet bool +} + +func (v NullableEnvironmentRead) Get() *EnvironmentRead { + return v.value +} + +func (v *NullableEnvironmentRead) Set(val *EnvironmentRead) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentRead) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentRead(val *EnvironmentRead) *NullableEnvironmentRead { + return &NullableEnvironmentRead{value: val, isSet: true} +} + +func (v NullableEnvironmentRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_stats.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_stats.go new file mode 100644 index 00000000..74df2edd --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_stats.go @@ -0,0 +1,420 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// EnvironmentStats struct for EnvironmentStats +type EnvironmentStats struct { + // A URL-friendly name of the environment (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the environment. + Key string `json:"key"` + // Unique id of the environment + Id string `json:"id"` + // Unique id of the organization that the environment belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the environment belongs to. + ProjectId string `json:"project_id"` + // Date and time when the environment was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the environment was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The name of the environment + Name string `json:"name"` + // an optional longer description of the environment + Description *string `json:"description,omitempty"` + // when using gitops feature, an optional branch name for the environment + CustomBranchName *string `json:"custom_branch_name,omitempty"` + PdpConfigs []PDPConfigRead `json:"pdp_configs"` + Stats Statistics `json:"stats"` +} + +// NewEnvironmentStats instantiates a new EnvironmentStats object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentStats(key string, id string, organizationId string, projectId string, createdAt time.Time, updatedAt time.Time, name string, pdpConfigs []PDPConfigRead, stats Statistics) *EnvironmentStats { + this := EnvironmentStats{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + this.PdpConfigs = pdpConfigs + this.Stats = stats + return &this +} + +// NewEnvironmentStatsWithDefaults instantiates a new EnvironmentStats object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentStatsWithDefaults() *EnvironmentStats { + this := EnvironmentStats{} + return &this +} + +// GetKey returns the Key field value +func (o *EnvironmentStats) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *EnvironmentStats) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *EnvironmentStats) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *EnvironmentStats) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *EnvironmentStats) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *EnvironmentStats) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *EnvironmentStats) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *EnvironmentStats) SetProjectId(v string) { + o.ProjectId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *EnvironmentStats) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *EnvironmentStats) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *EnvironmentStats) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *EnvironmentStats) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetName returns the Name field value +func (o *EnvironmentStats) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *EnvironmentStats) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *EnvironmentStats) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *EnvironmentStats) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *EnvironmentStats) SetDescription(v string) { + o.Description = &v +} + +// GetCustomBranchName returns the CustomBranchName field value if set, zero value otherwise. +func (o *EnvironmentStats) GetCustomBranchName() string { + if o == nil || IsNil(o.CustomBranchName) { + var ret string + return ret + } + return *o.CustomBranchName +} + +// GetCustomBranchNameOk returns a tuple with the CustomBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetCustomBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.CustomBranchName) { + return nil, false + } + return o.CustomBranchName, true +} + +// HasCustomBranchName returns a boolean if a field has been set. +func (o *EnvironmentStats) HasCustomBranchName() bool { + if o != nil && !IsNil(o.CustomBranchName) { + return true + } + + return false +} + +// SetCustomBranchName gets a reference to the given string and assigns it to the CustomBranchName field. +func (o *EnvironmentStats) SetCustomBranchName(v string) { + o.CustomBranchName = &v +} + +// GetPdpConfigs returns the PdpConfigs field value +func (o *EnvironmentStats) GetPdpConfigs() []PDPConfigRead { + if o == nil { + var ret []PDPConfigRead + return ret + } + + return o.PdpConfigs +} + +// GetPdpConfigsOk returns a tuple with the PdpConfigs field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetPdpConfigsOk() ([]PDPConfigRead, bool) { + if o == nil { + return nil, false + } + return o.PdpConfigs, true +} + +// SetPdpConfigs sets field value +func (o *EnvironmentStats) SetPdpConfigs(v []PDPConfigRead) { + o.PdpConfigs = v +} + +// GetStats returns the Stats field value +func (o *EnvironmentStats) GetStats() Statistics { + if o == nil { + var ret Statistics + return ret + } + + return o.Stats +} + +// GetStatsOk returns a tuple with the Stats field value +// and a boolean to check if the value has been set. +func (o *EnvironmentStats) GetStatsOk() (*Statistics, bool) { + if o == nil { + return nil, false + } + return &o.Stats, true +} + +// SetStats sets field value +func (o *EnvironmentStats) SetStats(v Statistics) { + o.Stats = v +} + +func (o EnvironmentStats) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.CustomBranchName) { + toSerialize["custom_branch_name"] = o.CustomBranchName + } + if true { + toSerialize["pdp_configs"] = o.PdpConfigs + } + if true { + toSerialize["stats"] = o.Stats + } + return json.Marshal(toSerialize) +} + +type NullableEnvironmentStats struct { + value *EnvironmentStats + isSet bool +} + +func (v NullableEnvironmentStats) Get() *EnvironmentStats { + return v.value +} + +func (v *NullableEnvironmentStats) Set(val *EnvironmentStats) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentStats) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentStats) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentStats(val *EnvironmentStats) *NullableEnvironmentStats { + return &NullableEnvironmentStats{value: val, isSet: true} +} + +func (v NullableEnvironmentStats) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentStats) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_update.go new file mode 100644 index 00000000..1b3f78ba --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_environment_update.go @@ -0,0 +1,188 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// EnvironmentUpdate struct for EnvironmentUpdate +type EnvironmentUpdate struct { + // The name of the environment + Name *string `json:"name,omitempty"` + // an optional longer description of the environment + Description *string `json:"description,omitempty"` + // when using gitops feature, an optional branch name for the environment + CustomBranchName *string `json:"custom_branch_name,omitempty"` +} + +// NewEnvironmentUpdate instantiates a new EnvironmentUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironmentUpdate() *EnvironmentUpdate { + this := EnvironmentUpdate{} + return &this +} + +// NewEnvironmentUpdateWithDefaults instantiates a new EnvironmentUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentUpdateWithDefaults() *EnvironmentUpdate { + this := EnvironmentUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *EnvironmentUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *EnvironmentUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *EnvironmentUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *EnvironmentUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *EnvironmentUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *EnvironmentUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetCustomBranchName returns the CustomBranchName field value if set, zero value otherwise. +func (o *EnvironmentUpdate) GetCustomBranchName() string { + if o == nil || IsNil(o.CustomBranchName) { + var ret string + return ret + } + return *o.CustomBranchName +} + +// GetCustomBranchNameOk returns a tuple with the CustomBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvironmentUpdate) GetCustomBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.CustomBranchName) { + return nil, false + } + return o.CustomBranchName, true +} + +// HasCustomBranchName returns a boolean if a field has been set. +func (o *EnvironmentUpdate) HasCustomBranchName() bool { + if o != nil && !IsNil(o.CustomBranchName) { + return true + } + + return false +} + +// SetCustomBranchName gets a reference to the given string and assigns it to the CustomBranchName field. +func (o *EnvironmentUpdate) SetCustomBranchName(v string) { + o.CustomBranchName = &v +} + +func (o EnvironmentUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.CustomBranchName) { + toSerialize["custom_branch_name"] = o.CustomBranchName + } + return json.Marshal(toSerialize) +} + +type NullableEnvironmentUpdate struct { + value *EnvironmentUpdate + isSet bool +} + +func (v NullableEnvironmentUpdate) Get() *EnvironmentUpdate { + return v.value +} + +func (v *NullableEnvironmentUpdate) Set(val *EnvironmentUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironmentUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironmentUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironmentUpdate(val *EnvironmentUpdate) *NullableEnvironmentUpdate { + return &NullableEnvironmentUpdate{value: val, isSet: true} +} + +func (v NullableEnvironmentUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironmentUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_failed_invite.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_failed_invite.go new file mode 100644 index 00000000..21b942be --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_failed_invite.go @@ -0,0 +1,135 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// FailedInvite struct for FailedInvite +type FailedInvite struct { + Email string `json:"email"` + Reason string `json:"reason"` +} + +// NewFailedInvite instantiates a new FailedInvite object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewFailedInvite(email string, reason string) *FailedInvite { + this := FailedInvite{} + this.Email = email + this.Reason = reason + return &this +} + +// NewFailedInviteWithDefaults instantiates a new FailedInvite object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewFailedInviteWithDefaults() *FailedInvite { + this := FailedInvite{} + return &this +} + +// GetEmail returns the Email field value +func (o *FailedInvite) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *FailedInvite) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *FailedInvite) SetEmail(v string) { + o.Email = v +} + +// GetReason returns the Reason field value +func (o *FailedInvite) GetReason() string { + if o == nil { + var ret string + return ret + } + + return o.Reason +} + +// GetReasonOk returns a tuple with the Reason field value +// and a boolean to check if the value has been set. +func (o *FailedInvite) GetReasonOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Reason, true +} + +// SetReason sets field value +func (o *FailedInvite) SetReason(v string) { + o.Reason = v +} + +func (o FailedInvite) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["email"] = o.Email + } + if true { + toSerialize["reason"] = o.Reason + } + return json.Marshal(toSerialize) +} + +type NullableFailedInvite struct { + value *FailedInvite + isSet bool +} + +func (v NullableFailedInvite) Get() *FailedInvite { + return v.value +} + +func (v *NullableFailedInvite) Set(val *FailedInvite) { + v.value = val + v.isSet = true +} + +func (v NullableFailedInvite) IsSet() bool { + return v.isSet +} + +func (v *NullableFailedInvite) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFailedInvite(val *FailedInvite) *NullableFailedInvite { + return &NullableFailedInvite{value: val, isSet: true} +} + +func (v NullableFailedInvite) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFailedInvite) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_full_data.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_full_data.go new file mode 100644 index 00000000..3853fd02 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_full_data.go @@ -0,0 +1,164 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// FullData struct for FullData +type FullData struct { + Users map[string]UserData `json:"users"` + Roles map[string]RoleData `json:"roles"` + ConditionSetRules map[string]map[string]map[string][]string `json:"condition_set_rules"` +} + +// NewFullData instantiates a new FullData object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewFullData(users map[string]UserData, roles map[string]RoleData, conditionSetRules map[string]map[string]map[string][]string) *FullData { + this := FullData{} + this.Users = users + this.Roles = roles + this.ConditionSetRules = conditionSetRules + return &this +} + +// NewFullDataWithDefaults instantiates a new FullData object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewFullDataWithDefaults() *FullData { + this := FullData{} + return &this +} + +// GetUsers returns the Users field value +func (o *FullData) GetUsers() map[string]UserData { + if o == nil { + var ret map[string]UserData + return ret + } + + return o.Users +} + +// GetUsersOk returns a tuple with the Users field value +// and a boolean to check if the value has been set. +func (o *FullData) GetUsersOk() (*map[string]UserData, bool) { + if o == nil { + return nil, false + } + return &o.Users, true +} + +// SetUsers sets field value +func (o *FullData) SetUsers(v map[string]UserData) { + o.Users = v +} + +// GetRoles returns the Roles field value +func (o *FullData) GetRoles() map[string]RoleData { + if o == nil { + var ret map[string]RoleData + return ret + } + + return o.Roles +} + +// GetRolesOk returns a tuple with the Roles field value +// and a boolean to check if the value has been set. +func (o *FullData) GetRolesOk() (*map[string]RoleData, bool) { + if o == nil { + return nil, false + } + return &o.Roles, true +} + +// SetRoles sets field value +func (o *FullData) SetRoles(v map[string]RoleData) { + o.Roles = v +} + +// GetConditionSetRules returns the ConditionSetRules field value +func (o *FullData) GetConditionSetRules() map[string]map[string]map[string][]string { + if o == nil { + var ret map[string]map[string]map[string][]string + return ret + } + + return o.ConditionSetRules +} + +// GetConditionSetRulesOk returns a tuple with the ConditionSetRules field value +// and a boolean to check if the value has been set. +func (o *FullData) GetConditionSetRulesOk() (*map[string]map[string]map[string][]string, bool) { + if o == nil { + return nil, false + } + return &o.ConditionSetRules, true +} + +// SetConditionSetRules sets field value +func (o *FullData) SetConditionSetRules(v map[string]map[string]map[string][]string) { + o.ConditionSetRules = v +} + +func (o FullData) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["users"] = o.Users + } + if true { + toSerialize["roles"] = o.Roles + } + if true { + toSerialize["condition_set_rules"] = o.ConditionSetRules + } + return json.Marshal(toSerialize) +} + +type NullableFullData struct { + value *FullData + isSet bool +} + +func (v NullableFullData) Get() *FullData { + return v.value +} + +func (v *NullableFullData) Set(val *FullData) { + v.value = val + v.isSet = true +} + +func (v NullableFullData) IsSet() bool { + return v.isSet +} + +func (v *NullableFullData) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFullData(val *FullData) *NullableFullData { + return &NullableFullData{value: val, isSet: true} +} + +func (v NullableFullData) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFullData) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_http_validation_error.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_http_validation_error.go new file mode 100644 index 00000000..e18920c7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_http_validation_error.go @@ -0,0 +1,113 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// HTTPValidationError struct for HTTPValidationError +type HTTPValidationError struct { + Detail []ValidationError `json:"detail,omitempty"` +} + +// NewHTTPValidationError instantiates a new HTTPValidationError object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewHTTPValidationError() *HTTPValidationError { + this := HTTPValidationError{} + return &this +} + +// NewHTTPValidationErrorWithDefaults instantiates a new HTTPValidationError object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewHTTPValidationErrorWithDefaults() *HTTPValidationError { + this := HTTPValidationError{} + return &this +} + +// GetDetail returns the Detail field value if set, zero value otherwise. +func (o *HTTPValidationError) GetDetail() []ValidationError { + if o == nil || IsNil(o.Detail) { + var ret []ValidationError + return ret + } + return o.Detail +} + +// GetDetailOk returns a tuple with the Detail field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *HTTPValidationError) GetDetailOk() ([]ValidationError, bool) { + if o == nil || IsNil(o.Detail) { + return nil, false + } + return o.Detail, true +} + +// HasDetail returns a boolean if a field has been set. +func (o *HTTPValidationError) HasDetail() bool { + if o != nil && !IsNil(o.Detail) { + return true + } + + return false +} + +// SetDetail gets a reference to the given []ValidationError and assigns it to the Detail field. +func (o *HTTPValidationError) SetDetail(v []ValidationError) { + o.Detail = v +} + +func (o HTTPValidationError) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Detail) { + toSerialize["detail"] = o.Detail + } + return json.Marshal(toSerialize) +} + +type NullableHTTPValidationError struct { + value *HTTPValidationError + isSet bool +} + +func (v NullableHTTPValidationError) Get() *HTTPValidationError { + return v.value +} + +func (v *NullableHTTPValidationError) Set(val *HTTPValidationError) { + v.value = val + v.isSet = true +} + +func (v NullableHTTPValidationError) IsSet() bool { + return v.isSet +} + +func (v *NullableHTTPValidationError) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableHTTPValidationError(val *HTTPValidationError) *NullableHTTPValidationError { + return &NullableHTTPValidationError{value: val, isSet: true} +} + +func (v NullableHTTPValidationError) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableHTTPValidationError) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_identity_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_identity_read.go new file mode 100644 index 00000000..399b57eb --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_identity_read.go @@ -0,0 +1,257 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// IdentityRead struct for IdentityRead +type IdentityRead struct { + // Unique User Id of this identity in the identity provider (including the provider type) + UserId string `json:"user_id"` + // The identity provider type this identity came from + Provider string `json:"provider"` + // Unique User Id of this identity in the identity provider (NOT including the provider type) + Sub string `json:"sub"` + // Email connected to this account identity + Email string `json:"email"` + // Whether this email address connected to this account identity is verified or not. For social providers like 'Login with Google' this is done automatically, otherwise we will send the user a verification link in email. + EmailVerified bool `json:"email_verified"` + // Raw user info json coming from our identity provider and matching a specific account identity + Auth0Info map[string]interface{} `json:"auth0_info"` +} + +// NewIdentityRead instantiates a new IdentityRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewIdentityRead(userId string, provider string, sub string, email string, emailVerified bool, auth0Info map[string]interface{}) *IdentityRead { + this := IdentityRead{} + this.UserId = userId + this.Provider = provider + this.Sub = sub + this.Email = email + this.EmailVerified = emailVerified + this.Auth0Info = auth0Info + return &this +} + +// NewIdentityReadWithDefaults instantiates a new IdentityRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewIdentityReadWithDefaults() *IdentityRead { + this := IdentityRead{} + return &this +} + +// GetUserId returns the UserId field value +func (o *IdentityRead) GetUserId() string { + if o == nil { + var ret string + return ret + } + + return o.UserId +} + +// GetUserIdOk returns a tuple with the UserId field value +// and a boolean to check if the value has been set. +func (o *IdentityRead) GetUserIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.UserId, true +} + +// SetUserId sets field value +func (o *IdentityRead) SetUserId(v string) { + o.UserId = v +} + +// GetProvider returns the Provider field value +func (o *IdentityRead) GetProvider() string { + if o == nil { + var ret string + return ret + } + + return o.Provider +} + +// GetProviderOk returns a tuple with the Provider field value +// and a boolean to check if the value has been set. +func (o *IdentityRead) GetProviderOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Provider, true +} + +// SetProvider sets field value +func (o *IdentityRead) SetProvider(v string) { + o.Provider = v +} + +// GetSub returns the Sub field value +func (o *IdentityRead) GetSub() string { + if o == nil { + var ret string + return ret + } + + return o.Sub +} + +// GetSubOk returns a tuple with the Sub field value +// and a boolean to check if the value has been set. +func (o *IdentityRead) GetSubOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Sub, true +} + +// SetSub sets field value +func (o *IdentityRead) SetSub(v string) { + o.Sub = v +} + +// GetEmail returns the Email field value +func (o *IdentityRead) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *IdentityRead) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *IdentityRead) SetEmail(v string) { + o.Email = v +} + +// GetEmailVerified returns the EmailVerified field value +func (o *IdentityRead) GetEmailVerified() bool { + if o == nil { + var ret bool + return ret + } + + return o.EmailVerified +} + +// GetEmailVerifiedOk returns a tuple with the EmailVerified field value +// and a boolean to check if the value has been set. +func (o *IdentityRead) GetEmailVerifiedOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.EmailVerified, true +} + +// SetEmailVerified sets field value +func (o *IdentityRead) SetEmailVerified(v bool) { + o.EmailVerified = v +} + +// GetAuth0Info returns the Auth0Info field value +func (o *IdentityRead) GetAuth0Info() map[string]interface{} { + if o == nil { + var ret map[string]interface{} + return ret + } + + return o.Auth0Info +} + +// GetAuth0InfoOk returns a tuple with the Auth0Info field value +// and a boolean to check if the value has been set. +func (o *IdentityRead) GetAuth0InfoOk() (map[string]interface{}, bool) { + if o == nil { + return map[string]interface{}{}, false + } + return o.Auth0Info, true +} + +// SetAuth0Info sets field value +func (o *IdentityRead) SetAuth0Info(v map[string]interface{}) { + o.Auth0Info = v +} + +func (o IdentityRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["user_id"] = o.UserId + } + if true { + toSerialize["provider"] = o.Provider + } + if true { + toSerialize["sub"] = o.Sub + } + if true { + toSerialize["email"] = o.Email + } + if true { + toSerialize["email_verified"] = o.EmailVerified + } + if true { + toSerialize["auth0_info"] = o.Auth0Info + } + return json.Marshal(toSerialize) +} + +type NullableIdentityRead struct { + value *IdentityRead + isSet bool +} + +func (v NullableIdentityRead) Get() *IdentityRead { + return v.value +} + +func (v *NullableIdentityRead) Set(val *IdentityRead) { + v.value = val + v.isSet = true +} + +func (v NullableIdentityRead) IsSet() bool { + return v.isSet +} + +func (v *NullableIdentityRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableIdentityRead(val *IdentityRead) *NullableIdentityRead { + return &NullableIdentityRead{value: val, isSet: true} +} + +func (v NullableIdentityRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableIdentityRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_attempt_result.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_attempt_result.go new file mode 100644 index 00000000..fbdcf015 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_attempt_result.go @@ -0,0 +1,155 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// InviteAttemptResult struct for InviteAttemptResult +type InviteAttemptResult struct { + // the invite code was accepted + InviteSuccessful *bool `json:"invite_successful,omitempty"` + // if the invite failed, the reason it failed + InviteFailedReason *string `json:"invite_failed_reason,omitempty"` +} + +// NewInviteAttemptResult instantiates a new InviteAttemptResult object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewInviteAttemptResult() *InviteAttemptResult { + this := InviteAttemptResult{} + var inviteSuccessful bool = false + this.InviteSuccessful = &inviteSuccessful + return &this +} + +// NewInviteAttemptResultWithDefaults instantiates a new InviteAttemptResult object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewInviteAttemptResultWithDefaults() *InviteAttemptResult { + this := InviteAttemptResult{} + var inviteSuccessful bool = false + this.InviteSuccessful = &inviteSuccessful + return &this +} + +// GetInviteSuccessful returns the InviteSuccessful field value if set, zero value otherwise. +func (o *InviteAttemptResult) GetInviteSuccessful() bool { + if o == nil || IsNil(o.InviteSuccessful) { + var ret bool + return ret + } + return *o.InviteSuccessful +} + +// GetInviteSuccessfulOk returns a tuple with the InviteSuccessful field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *InviteAttemptResult) GetInviteSuccessfulOk() (*bool, bool) { + if o == nil || IsNil(o.InviteSuccessful) { + return nil, false + } + return o.InviteSuccessful, true +} + +// HasInviteSuccessful returns a boolean if a field has been set. +func (o *InviteAttemptResult) HasInviteSuccessful() bool { + if o != nil && !IsNil(o.InviteSuccessful) { + return true + } + + return false +} + +// SetInviteSuccessful gets a reference to the given bool and assigns it to the InviteSuccessful field. +func (o *InviteAttemptResult) SetInviteSuccessful(v bool) { + o.InviteSuccessful = &v +} + +// GetInviteFailedReason returns the InviteFailedReason field value if set, zero value otherwise. +func (o *InviteAttemptResult) GetInviteFailedReason() string { + if o == nil || IsNil(o.InviteFailedReason) { + var ret string + return ret + } + return *o.InviteFailedReason +} + +// GetInviteFailedReasonOk returns a tuple with the InviteFailedReason field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *InviteAttemptResult) GetInviteFailedReasonOk() (*string, bool) { + if o == nil || IsNil(o.InviteFailedReason) { + return nil, false + } + return o.InviteFailedReason, true +} + +// HasInviteFailedReason returns a boolean if a field has been set. +func (o *InviteAttemptResult) HasInviteFailedReason() bool { + if o != nil && !IsNil(o.InviteFailedReason) { + return true + } + + return false +} + +// SetInviteFailedReason gets a reference to the given string and assigns it to the InviteFailedReason field. +func (o *InviteAttemptResult) SetInviteFailedReason(v string) { + o.InviteFailedReason = &v +} + +func (o InviteAttemptResult) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.InviteSuccessful) { + toSerialize["invite_successful"] = o.InviteSuccessful + } + if !IsNil(o.InviteFailedReason) { + toSerialize["invite_failed_reason"] = o.InviteFailedReason + } + return json.Marshal(toSerialize) +} + +type NullableInviteAttemptResult struct { + value *InviteAttemptResult + isSet bool +} + +func (v NullableInviteAttemptResult) Get() *InviteAttemptResult { + return v.value +} + +func (v *NullableInviteAttemptResult) Set(val *InviteAttemptResult) { + v.value = val + v.isSet = true +} + +func (v NullableInviteAttemptResult) IsSet() bool { + return v.isSet +} + +func (v *NullableInviteAttemptResult) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInviteAttemptResult(val *InviteAttemptResult) *NullableInviteAttemptResult { + return &NullableInviteAttemptResult{value: val, isSet: true} +} + +func (v NullableInviteAttemptResult) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInviteAttemptResult) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_create.go new file mode 100644 index 00000000..ed6144ce --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_create.go @@ -0,0 +1,137 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// InviteCreate struct for InviteCreate +type InviteCreate struct { + // The invited member's email address + Email string `json:"email"` + // The role the member will be assigned with + Role string `json:"role"` +} + +// NewInviteCreate instantiates a new InviteCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewInviteCreate(email string, role string) *InviteCreate { + this := InviteCreate{} + this.Email = email + this.Role = role + return &this +} + +// NewInviteCreateWithDefaults instantiates a new InviteCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewInviteCreateWithDefaults() *InviteCreate { + this := InviteCreate{} + return &this +} + +// GetEmail returns the Email field value +func (o *InviteCreate) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *InviteCreate) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *InviteCreate) SetEmail(v string) { + o.Email = v +} + +// GetRole returns the Role field value +func (o *InviteCreate) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *InviteCreate) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *InviteCreate) SetRole(v string) { + o.Role = v +} + +func (o InviteCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["email"] = o.Email + } + if true { + toSerialize["role"] = o.Role + } + return json.Marshal(toSerialize) +} + +type NullableInviteCreate struct { + value *InviteCreate + isSet bool +} + +func (v NullableInviteCreate) Get() *InviteCreate { + return v.value +} + +func (v *NullableInviteCreate) Set(val *InviteCreate) { + v.value = val + v.isSet = true +} + +func (v NullableInviteCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableInviteCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInviteCreate(val *InviteCreate) *NullableInviteCreate { + return &NullableInviteCreate{value: val, isSet: true} +} + +func (v NullableInviteCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInviteCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_read.go new file mode 100644 index 00000000..a67d4170 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_read.go @@ -0,0 +1,325 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// InviteRead struct for InviteRead +type InviteRead struct { + // The invited member's email address + Email string `json:"email"` + // The role the member will be assigned with + Role string `json:"role"` + // Unique id of the invite + Id string `json:"id"` + // Unique id of the organization that the invite belongs to. + OrganizationId string `json:"organization_id"` + // The invite code that is sent to the member's email + InviteCode string `json:"invite_code"` + // Date and time when the invite was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // The status of the invite (pending, failed, etc) + Status InviteStatus `json:"status"` + // if failed, the reason the invitation failed + FailedReason *string `json:"failed_reason,omitempty"` +} + +// NewInviteRead instantiates a new InviteRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewInviteRead(email string, role string, id string, organizationId string, inviteCode string, createdAt time.Time, status InviteStatus) *InviteRead { + this := InviteRead{} + this.Email = email + this.Role = role + this.Id = id + this.OrganizationId = organizationId + this.InviteCode = inviteCode + this.CreatedAt = createdAt + this.Status = status + return &this +} + +// NewInviteReadWithDefaults instantiates a new InviteRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewInviteReadWithDefaults() *InviteRead { + this := InviteRead{} + return &this +} + +// GetEmail returns the Email field value +func (o *InviteRead) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *InviteRead) SetEmail(v string) { + o.Email = v +} + +// GetRole returns the Role field value +func (o *InviteRead) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *InviteRead) SetRole(v string) { + o.Role = v +} + +// GetId returns the Id field value +func (o *InviteRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *InviteRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *InviteRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *InviteRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetInviteCode returns the InviteCode field value +func (o *InviteRead) GetInviteCode() string { + if o == nil { + var ret string + return ret + } + + return o.InviteCode +} + +// GetInviteCodeOk returns a tuple with the InviteCode field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetInviteCodeOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.InviteCode, true +} + +// SetInviteCode sets field value +func (o *InviteRead) SetInviteCode(v string) { + o.InviteCode = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *InviteRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *InviteRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetStatus returns the Status field value +func (o *InviteRead) GetStatus() InviteStatus { + if o == nil { + var ret InviteStatus + return ret + } + + return o.Status +} + +// GetStatusOk returns a tuple with the Status field value +// and a boolean to check if the value has been set. +func (o *InviteRead) GetStatusOk() (*InviteStatus, bool) { + if o == nil { + return nil, false + } + return &o.Status, true +} + +// SetStatus sets field value +func (o *InviteRead) SetStatus(v InviteStatus) { + o.Status = v +} + +// GetFailedReason returns the FailedReason field value if set, zero value otherwise. +func (o *InviteRead) GetFailedReason() string { + if o == nil || IsNil(o.FailedReason) { + var ret string + return ret + } + return *o.FailedReason +} + +// GetFailedReasonOk returns a tuple with the FailedReason field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *InviteRead) GetFailedReasonOk() (*string, bool) { + if o == nil || IsNil(o.FailedReason) { + return nil, false + } + return o.FailedReason, true +} + +// HasFailedReason returns a boolean if a field has been set. +func (o *InviteRead) HasFailedReason() bool { + if o != nil && !IsNil(o.FailedReason) { + return true + } + + return false +} + +// SetFailedReason gets a reference to the given string and assigns it to the FailedReason field. +func (o *InviteRead) SetFailedReason(v string) { + o.FailedReason = &v +} + +func (o InviteRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["email"] = o.Email + } + if true { + toSerialize["role"] = o.Role + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["invite_code"] = o.InviteCode + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["status"] = o.Status + } + if !IsNil(o.FailedReason) { + toSerialize["failed_reason"] = o.FailedReason + } + return json.Marshal(toSerialize) +} + +type NullableInviteRead struct { + value *InviteRead + isSet bool +} + +func (v NullableInviteRead) Get() *InviteRead { + return v.value +} + +func (v *NullableInviteRead) Set(val *InviteRead) { + v.value = val + v.isSet = true +} + +func (v NullableInviteRead) IsSet() bool { + return v.isSet +} + +func (v *NullableInviteRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInviteRead(val *InviteRead) *NullableInviteRead { + return &NullableInviteRead{value: val, isSet: true} +} + +func (v NullableInviteRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInviteRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_status.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_status.go new file mode 100644 index 00000000..4c9b0467 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_invite_status.go @@ -0,0 +1,114 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// InviteStatus An enumeration. +type InviteStatus string + +// List of InviteStatus +const ( + INVITE_PENDING InviteStatus = "pending" + INVITE_ACCEPTED InviteStatus = "accepted" + INVITE_FAILED InviteStatus = "failed" + INVITE_CANCELED InviteStatus = "canceled" +) + +// All allowed values of InviteStatus enum +var AllowedInviteStatusEnumValues = []InviteStatus{ + "pending", + "accepted", + "failed", + "canceled", +} + +func (v *InviteStatus) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := InviteStatus(value) + for _, existing := range AllowedInviteStatusEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid InviteStatus", value) +} + +// NewInviteStatusFromValue returns a pointer to a valid InviteStatus +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewInviteStatusFromValue(v string) (*InviteStatus, error) { + ev := InviteStatus(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for InviteStatus: valid values are %v", v, AllowedInviteStatusEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v InviteStatus) IsValid() bool { + for _, existing := range AllowedInviteStatusEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to InviteStatus value +func (v InviteStatus) Ptr() *InviteStatus { + return &v +} + +type NullableInviteStatus struct { + value *InviteStatus + isSet bool +} + +func (v NullableInviteStatus) Get() *InviteStatus { + return v.value +} + +func (v *NullableInviteStatus) Set(val *InviteStatus) { + v.value = val + v.isSet = true +} + +func (v NullableInviteStatus) IsSet() bool { + return v.isSet +} + +func (v *NullableInviteStatus) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInviteStatus(val *InviteStatus) *NullableInviteStatus { + return &NullableInviteStatus{value: val, isSet: true} +} + +func (v NullableInviteStatus) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInviteStatus) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_jwks.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_jwks.go new file mode 100644 index 00000000..d771800c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_jwks.go @@ -0,0 +1,116 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the Jwks type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Jwks{} + +// Jwks jwks for element frontend only login +type Jwks struct { + // The keys to match against the request headers + Keys []map[string]interface{} `json:"keys"` +} + +// NewJwks instantiates a new Jwks object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewJwks(keys []map[string]interface{}) *Jwks { + this := Jwks{} + this.Keys = keys + return &this +} + +// NewJwksWithDefaults instantiates a new Jwks object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewJwksWithDefaults() *Jwks { + this := Jwks{} + return &this +} + +// GetKeys returns the Keys field value +func (o *Jwks) GetKeys() []map[string]interface{} { + if o == nil { + var ret []map[string]interface{} + return ret + } + + return o.Keys +} + +// GetKeysOk returns a tuple with the Keys field value +// and a boolean to check if the value has been set. +func (o *Jwks) GetKeysOk() ([]map[string]interface{}, bool) { + if o == nil { + return nil, false + } + return o.Keys, true +} + +// SetKeys sets field value +func (o *Jwks) SetKeys(v []map[string]interface{}) { + o.Keys = v +} + +func (o Jwks) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Jwks) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["keys"] = o.Keys + return toSerialize, nil +} + +type NullableJwks struct { + value *Jwks + isSet bool +} + +func (v NullableJwks) Get() *Jwks { + return v.value +} + +func (v *NullableJwks) Set(val *Jwks) { + v.value = val + v.isSet = true +} + +func (v NullableJwks) IsSet() bool { + return v.isSet +} + +func (v *NullableJwks) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableJwks(val *Jwks) *NullableJwks { + return &NullableJwks{value: val, isSet: true} +} + +func (v NullableJwks) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableJwks) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_labels.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_labels.go new file mode 100644 index 00000000..ed3ce88b --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_labels.go @@ -0,0 +1,135 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// Labels struct for Labels +type Labels struct { + Id string `json:"id"` + Version string `json:"version"` +} + +// NewLabels instantiates a new Labels object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLabels(id string, version string) *Labels { + this := Labels{} + this.Id = id + this.Version = version + return &this +} + +// NewLabelsWithDefaults instantiates a new Labels object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLabelsWithDefaults() *Labels { + this := Labels{} + return &this +} + +// GetId returns the Id field value +func (o *Labels) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *Labels) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *Labels) SetId(v string) { + o.Id = v +} + +// GetVersion returns the Version field value +func (o *Labels) GetVersion() string { + if o == nil { + var ret string + return ret + } + + return o.Version +} + +// GetVersionOk returns a tuple with the Version field value +// and a boolean to check if the value has been set. +func (o *Labels) GetVersionOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Version, true +} + +// SetVersion sets field value +func (o *Labels) SetVersion(v string) { + o.Version = v +} + +func (o Labels) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["version"] = o.Version + } + return json.Marshal(toSerialize) +} + +type NullableLabels struct { + value *Labels + isSet bool +} + +func (v NullableLabels) Get() *Labels { + return v.value +} + +func (v *NullableLabels) Set(val *Labels) { + v.value = val + v.isSet = true +} + +func (v NullableLabels) IsSet() bool { + return v.isSet +} + +func (v *NullableLabels) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLabels(val *Labels) *NullableLabels { + return &NullableLabels{value: val, isSet: true} +} + +func (v NullableLabels) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLabels) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_language_instructions.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_language_instructions.go new file mode 100644 index 00000000..d70087e2 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_language_instructions.go @@ -0,0 +1,164 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// LanguageInstructions struct for LanguageInstructions +type LanguageInstructions struct { + Language ProgrammingLanguage `json:"language"` + Label string `json:"label"` + Instructions string `json:"instructions"` +} + +// NewLanguageInstructions instantiates a new LanguageInstructions object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLanguageInstructions(language ProgrammingLanguage, label string, instructions string) *LanguageInstructions { + this := LanguageInstructions{} + this.Language = language + this.Label = label + this.Instructions = instructions + return &this +} + +// NewLanguageInstructionsWithDefaults instantiates a new LanguageInstructions object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLanguageInstructionsWithDefaults() *LanguageInstructions { + this := LanguageInstructions{} + return &this +} + +// GetLanguage returns the Language field value +func (o *LanguageInstructions) GetLanguage() ProgrammingLanguage { + if o == nil { + var ret ProgrammingLanguage + return ret + } + + return o.Language +} + +// GetLanguageOk returns a tuple with the Language field value +// and a boolean to check if the value has been set. +func (o *LanguageInstructions) GetLanguageOk() (*ProgrammingLanguage, bool) { + if o == nil { + return nil, false + } + return &o.Language, true +} + +// SetLanguage sets field value +func (o *LanguageInstructions) SetLanguage(v ProgrammingLanguage) { + o.Language = v +} + +// GetLabel returns the Label field value +func (o *LanguageInstructions) GetLabel() string { + if o == nil { + var ret string + return ret + } + + return o.Label +} + +// GetLabelOk returns a tuple with the Label field value +// and a boolean to check if the value has been set. +func (o *LanguageInstructions) GetLabelOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Label, true +} + +// SetLabel sets field value +func (o *LanguageInstructions) SetLabel(v string) { + o.Label = v +} + +// GetInstructions returns the Instructions field value +func (o *LanguageInstructions) GetInstructions() string { + if o == nil { + var ret string + return ret + } + + return o.Instructions +} + +// GetInstructionsOk returns a tuple with the Instructions field value +// and a boolean to check if the value has been set. +func (o *LanguageInstructions) GetInstructionsOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Instructions, true +} + +// SetInstructions sets field value +func (o *LanguageInstructions) SetInstructions(v string) { + o.Instructions = v +} + +func (o LanguageInstructions) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["language"] = o.Language + } + if true { + toSerialize["label"] = o.Label + } + if true { + toSerialize["instructions"] = o.Instructions + } + return json.Marshal(toSerialize) +} + +type NullableLanguageInstructions struct { + value *LanguageInstructions + isSet bool +} + +func (v NullableLanguageInstructions) Get() *LanguageInstructions { + return v.value +} + +func (v *NullableLanguageInstructions) Set(val *LanguageInstructions) { + v.value = val + v.isSet = true +} + +func (v NullableLanguageInstructions) IsSet() bool { + return v.isSet +} + +func (v *NullableLanguageInstructions) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLanguageInstructions(val *LanguageInstructions) *NullableLanguageInstructions { + return &NullableLanguageInstructions{value: val, isSet: true} +} + +func (v NullableLanguageInstructions) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLanguageInstructions) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_location_inner.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_location_inner.go new file mode 100644 index 00000000..90fdd5ae --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_location_inner.go @@ -0,0 +1,103 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// LocationInner struct for LocationInner +type LocationInner struct { + int32 *int32 + string *string +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *LocationInner) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into int32 + err = json.Unmarshal(data, &dst.int32) + if err == nil { + jsonint32, _ := json.Marshal(dst.int32) + if string(jsonint32) == "{}" { // empty struct + dst.int32 = nil + } else { + return nil // data stored in dst.int32, return on the first match + } + } else { + dst.int32 = nil + } + + // try to unmarshal JSON data into string + err = json.Unmarshal(data, &dst.string) + if err == nil { + jsonstring, _ := json.Marshal(dst.string) + if string(jsonstring) == "{}" { // empty struct + dst.string = nil + } else { + return nil // data stored in dst.string, return on the first match + } + } else { + dst.string = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(LocationInner)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *LocationInner) MarshalJSON() ([]byte, error) { + if src.int32 != nil { + return json.Marshal(&src.int32) + } + + if src.string != nil { + return json.Marshal(&src.string) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableLocationInner struct { + value *LocationInner + isSet bool +} + +func (v NullableLocationInner) Get() *LocationInner { + return v.value +} + +func (v *NullableLocationInner) Set(val *LocationInner) { + v.value = val + v.isSet = true +} + +func (v NullableLocationInner) IsSet() bool { + return v.isSet +} + +func (v *NullableLocationInner) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLocationInner(val *LocationInner) *NullableLocationInner { + return &NullableLocationInner{value: val, isSet: true} +} + +func (v NullableLocationInner) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLocationInner) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_login_result.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_login_result.go new file mode 100644 index 00000000..ab94ed81 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_login_result.go @@ -0,0 +1,210 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// LoginResult struct for LoginResult +type LoginResult struct { + // whether login was successful + LoggedIn bool `json:"logged_in"` + // when will the login session expire (the unix timestamp in seconds) + ExpiresAt int32 `json:"expires_at"` + // the active organization on the session after the login + ActiveOrgId *string `json:"active_org_id,omitempty"` + InviteAttempt *InviteAttemptResult `json:"invite_attempt,omitempty"` +} + +// NewLoginResult instantiates a new LoginResult object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLoginResult(loggedIn bool, expiresAt int32) *LoginResult { + this := LoginResult{} + this.LoggedIn = loggedIn + this.ExpiresAt = expiresAt + return &this +} + +// NewLoginResultWithDefaults instantiates a new LoginResult object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLoginResultWithDefaults() *LoginResult { + this := LoginResult{} + return &this +} + +// GetLoggedIn returns the LoggedIn field value +func (o *LoginResult) GetLoggedIn() bool { + if o == nil { + var ret bool + return ret + } + + return o.LoggedIn +} + +// GetLoggedInOk returns a tuple with the LoggedIn field value +// and a boolean to check if the value has been set. +func (o *LoginResult) GetLoggedInOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.LoggedIn, true +} + +// SetLoggedIn sets field value +func (o *LoginResult) SetLoggedIn(v bool) { + o.LoggedIn = v +} + +// GetExpiresAt returns the ExpiresAt field value +func (o *LoginResult) GetExpiresAt() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.ExpiresAt +} + +// GetExpiresAtOk returns a tuple with the ExpiresAt field value +// and a boolean to check if the value has been set. +func (o *LoginResult) GetExpiresAtOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.ExpiresAt, true +} + +// SetExpiresAt sets field value +func (o *LoginResult) SetExpiresAt(v int32) { + o.ExpiresAt = v +} + +// GetActiveOrgId returns the ActiveOrgId field value if set, zero value otherwise. +func (o *LoginResult) GetActiveOrgId() string { + if o == nil || IsNil(o.ActiveOrgId) { + var ret string + return ret + } + return *o.ActiveOrgId +} + +// GetActiveOrgIdOk returns a tuple with the ActiveOrgId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *LoginResult) GetActiveOrgIdOk() (*string, bool) { + if o == nil || IsNil(o.ActiveOrgId) { + return nil, false + } + return o.ActiveOrgId, true +} + +// HasActiveOrgId returns a boolean if a field has been set. +func (o *LoginResult) HasActiveOrgId() bool { + if o != nil && !IsNil(o.ActiveOrgId) { + return true + } + + return false +} + +// SetActiveOrgId gets a reference to the given string and assigns it to the ActiveOrgId field. +func (o *LoginResult) SetActiveOrgId(v string) { + o.ActiveOrgId = &v +} + +// GetInviteAttempt returns the InviteAttempt field value if set, zero value otherwise. +func (o *LoginResult) GetInviteAttempt() InviteAttemptResult { + if o == nil || IsNil(o.InviteAttempt) { + var ret InviteAttemptResult + return ret + } + return *o.InviteAttempt +} + +// GetInviteAttemptOk returns a tuple with the InviteAttempt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *LoginResult) GetInviteAttemptOk() (*InviteAttemptResult, bool) { + if o == nil || IsNil(o.InviteAttempt) { + return nil, false + } + return o.InviteAttempt, true +} + +// HasInviteAttempt returns a boolean if a field has been set. +func (o *LoginResult) HasInviteAttempt() bool { + if o != nil && !IsNil(o.InviteAttempt) { + return true + } + + return false +} + +// SetInviteAttempt gets a reference to the given InviteAttemptResult and assigns it to the InviteAttempt field. +func (o *LoginResult) SetInviteAttempt(v InviteAttemptResult) { + o.InviteAttempt = &v +} + +func (o LoginResult) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["logged_in"] = o.LoggedIn + } + if true { + toSerialize["expires_at"] = o.ExpiresAt + } + if !IsNil(o.ActiveOrgId) { + toSerialize["active_org_id"] = o.ActiveOrgId + } + if !IsNil(o.InviteAttempt) { + toSerialize["invite_attempt"] = o.InviteAttempt + } + return json.Marshal(toSerialize) +} + +type NullableLoginResult struct { + value *LoginResult + isSet bool +} + +func (v NullableLoginResult) Get() *LoginResult { + return v.value +} + +func (v *NullableLoginResult) Set(val *LoginResult) { + v.value = val + v.isSet = true +} + +func (v NullableLoginResult) IsSet() bool { + return v.isSet +} + +func (v *NullableLoginResult) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLoginResult(val *LoginResult) *NullableLoginResult { + return &NullableLoginResult{value: val, isSet: true} +} + +func (v NullableLoginResult) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLoginResult) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_mapping_rule.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_mapping_rule.go new file mode 100644 index 00000000..1e775692 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_mapping_rule.go @@ -0,0 +1,349 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// UrlMatchType defines the type of URL matching +type UrlMatchType string + +const ( + // URLMatchTypeRegex indicates regex URL matching + URLMatchTypeRegex UrlMatchType = "regex" +) + +// checks if the MappingRule type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &MappingRule{} + +// MappingRule struct for MappingRule +type MappingRule struct { + // The URL to match against the request URL + Url string `json:"url"` + HttpMethod Methods `json:"http_method"` + // The resource to match against the request resource + Resource string `json:"resource"` + // The headers to match against the request headers + Headers *map[string]string `json:"headers,omitempty"` + // The action to match against the request action + Action *string `json:"action,omitempty"` + // The priority of the mapping rule. The higher the priority, the higher the precedence + Priority *int32 `json:"priority,omitempty"` + // The type of URL matching to use (empty for exact match, 'regex' for regular expression matching) + UrlType *UrlMatchType `json:"url_type,omitempty"` +} + +// NewMappingRule instantiates a new MappingRule object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewMappingRule(url string, httpMethod Methods, resource string) *MappingRule { + this := MappingRule{} + this.Url = url + this.HttpMethod = httpMethod + this.Resource = resource + return &this +} + +// NewMappingRuleWithDefaults instantiates a new MappingRule object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewMappingRuleWithDefaults() *MappingRule { + this := MappingRule{} + return &this +} + +// GetUrl returns the Url field value +func (o *MappingRule) GetUrl() string { + if o == nil { + var ret string + return ret + } + + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value +// and a boolean to check if the value has been set. +func (o *MappingRule) GetUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Url, true +} + +// SetUrl sets field value +func (o *MappingRule) SetUrl(v string) { + o.Url = v +} + +// GetHttpMethod returns the HttpMethod field value +func (o *MappingRule) GetHttpMethod() Methods { + if o == nil { + var ret Methods + return ret + } + + return o.HttpMethod +} + +// GetHttpMethodOk returns a tuple with the HttpMethod field value +// and a boolean to check if the value has been set. +func (o *MappingRule) GetHttpMethodOk() (*Methods, bool) { + if o == nil { + return nil, false + } + return &o.HttpMethod, true +} + +// SetHttpMethod sets field value +func (o *MappingRule) SetHttpMethod(v Methods) { + o.HttpMethod = v +} + +// GetResource returns the Resource field value +func (o *MappingRule) GetResource() string { + if o == nil { + var ret string + return ret + } + + return o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value +// and a boolean to check if the value has been set. +func (o *MappingRule) GetResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Resource, true +} + +// SetResource sets field value +func (o *MappingRule) SetResource(v string) { + o.Resource = v +} + +// GetHeaders returns the Headers field value if set, zero value otherwise. +func (o *MappingRule) GetHeaders() map[string]string { + if o == nil || IsNil(o.Headers) { + var ret map[string]string + return ret + } + return *o.Headers +} + +// GetHeadersOk returns a tuple with the Headers field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MappingRule) GetHeadersOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Headers) { + return nil, false + } + return o.Headers, true +} + +// HasHeaders returns a boolean if a field has been set. +func (o *MappingRule) HasHeaders() bool { + if o != nil && !IsNil(o.Headers) { + return true + } + + return false +} + +// SetHeaders gets a reference to the given map[string]string and assigns it to the Headers field. +func (o *MappingRule) SetHeaders(v map[string]string) { + o.Headers = &v +} + +// GetAction returns the Action field value if set, zero value otherwise. +func (o *MappingRule) GetAction() string { + if o == nil || IsNil(o.Action) { + var ret string + return ret + } + return *o.Action +} + +// GetActionOk returns a tuple with the Action field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MappingRule) GetActionOk() (*string, bool) { + if o == nil || IsNil(o.Action) { + return nil, false + } + return o.Action, true +} + +// HasAction returns a boolean if a field has been set. +func (o *MappingRule) HasAction() bool { + if o != nil && !IsNil(o.Action) { + return true + } + + return false +} + +// SetAction gets a reference to the given string and assigns it to the Action field. +func (o *MappingRule) SetAction(v string) { + o.Action = &v +} + +// GetPriority returns the Priority field value if set, zero value otherwise. +func (o *MappingRule) GetPriority() int32 { + if o == nil || IsNil(o.Priority) { + var ret int32 + return ret + } + return *o.Priority +} + +// GetPriorityOk returns a tuple with the Priority field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MappingRule) GetPriorityOk() (*int32, bool) { + if o == nil || IsNil(o.Priority) { + return nil, false + } + return o.Priority, true +} + +// HasPriority returns a boolean if a field has been set. +func (o *MappingRule) HasPriority() bool { + if o != nil && !IsNil(o.Priority) { + return true + } + + return false +} + +// SetPriority gets a reference to the given int32 and assigns it to the Priority field. +func (o *MappingRule) SetPriority(v int32) { + o.Priority = &v +} + +// GetUrlType returns the UrlType field value if set, zero value otherwise. +func (o *MappingRule) GetUrlType() UrlMatchType { + if o == nil || IsNil(o.UrlType) { + var ret UrlMatchType + return ret + } + return *o.UrlType +} + +// GetUrlTypeOk returns a tuple with the UrlType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MappingRule) GetUrlTypeOk() (*UrlMatchType, bool) { + if o == nil || IsNil(o.UrlType) { + return nil, false + } + return o.UrlType, true +} + +// HasUrlType returns a boolean if a field has been set. +func (o *MappingRule) HasUrlType() bool { + if o != nil && !IsNil(o.UrlType) { + return true + } + + return false +} + +// SetUrlType gets a reference to the given UrlMatchType and assigns it to the UrlType field. +func (o *MappingRule) SetUrlType(v UrlMatchType) { + o.UrlType = &v +} + +// IsRegexUrl returns true if URL matching is using regex +func (o *MappingRule) IsRegexUrl() bool { + return o.HasUrlType() && o.GetUrlType() == URLMatchTypeRegex +} + +func (o MappingRule) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o MappingRule) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["url"] = o.Url + toSerialize["http_method"] = o.HttpMethod + toSerialize["resource"] = o.Resource + if !IsNil(o.Headers) { + toSerialize["headers"] = o.Headers + } + if !IsNil(o.Action) { + toSerialize["action"] = o.Action + } + if !IsNil(o.Priority) { + toSerialize["priority"] = o.Priority + } + if !IsNil(o.UrlType) && *o.UrlType == URLMatchTypeRegex { + toSerialize["url_type"] = o.UrlType + } + return toSerialize, nil +} + +// UnmarshalJSON supports both string and custom type for UrlMatchType +func (u *UrlMatchType) UnmarshalJSON(data []byte) error { + var str string + if err := json.Unmarshal(data, &str); err != nil { + return err + } + + switch str { + case "regex", "": + *u = UrlMatchType(str) + return nil + default: + return fmt.Errorf("invalid url match type: %s, must be empty or 'regex'", str) + } +} + +type NullableMappingRule struct { + value *MappingRule + isSet bool +} + +func (v NullableMappingRule) Get() *MappingRule { + return v.value +} + +func (v *NullableMappingRule) Set(val *MappingRule) { + v.value = val + v.isSet = true +} + +func (v NullableMappingRule) IsSet() bool { + return v.isSet +} + +func (v *NullableMappingRule) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMappingRule(val *MappingRule) *NullableMappingRule { + return &NullableMappingRule{value: val, isSet: true} +} + +func (v NullableMappingRule) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMappingRule) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_level.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_level.go new file mode 100644 index 00000000..18766df6 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_level.go @@ -0,0 +1,112 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// MemberAccessLevel An enumeration. +type MemberAccessLevel string + +// List of MemberAccessLevel +const ( + READ MemberAccessLevel = "read" + WRITE MemberAccessLevel = "write" + ADMIN MemberAccessLevel = "admin" +) + +// All allowed values of MemberAccessLevel enum +var AllowedMemberAccessLevelEnumValues = []MemberAccessLevel{ + "read", + "write", + "admin", +} + +func (v *MemberAccessLevel) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := MemberAccessLevel(value) + for _, existing := range AllowedMemberAccessLevelEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid MemberAccessLevel", value) +} + +// NewMemberAccessLevelFromValue returns a pointer to a valid MemberAccessLevel +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewMemberAccessLevelFromValue(v string) (*MemberAccessLevel, error) { + ev := MemberAccessLevel(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for MemberAccessLevel: valid values are %v", v, AllowedMemberAccessLevelEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v MemberAccessLevel) IsValid() bool { + for _, existing := range AllowedMemberAccessLevelEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to MemberAccessLevel value +func (v MemberAccessLevel) Ptr() *MemberAccessLevel { + return &v +} + +type NullableMemberAccessLevel struct { + value *MemberAccessLevel + isSet bool +} + +func (v NullableMemberAccessLevel) Get() *MemberAccessLevel { + return v.value +} + +func (v *NullableMemberAccessLevel) Set(val *MemberAccessLevel) { + v.value = val + v.isSet = true +} + +func (v NullableMemberAccessLevel) IsSet() bool { + return v.isSet +} + +func (v *NullableMemberAccessLevel) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMemberAccessLevel(val *MemberAccessLevel) *NullableMemberAccessLevel { + return &NullableMemberAccessLevel{value: val, isSet: true} +} + +func (v NullableMemberAccessLevel) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMemberAccessLevel) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_obj.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_obj.go new file mode 100644 index 00000000..9ea5a153 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_member_access_obj.go @@ -0,0 +1,112 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// MemberAccessObj An enumeration. +type MemberAccessObj string + +// List of MemberAccessObj +const ( + ORG MemberAccessObj = "org" + PROJECT MemberAccessObj = "project" + ENV MemberAccessObj = "env" +) + +// All allowed values of MemberAccessObj enum +var AllowedMemberAccessObjEnumValues = []MemberAccessObj{ + "org", + "project", + "env", +} + +func (v *MemberAccessObj) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := MemberAccessObj(value) + for _, existing := range AllowedMemberAccessObjEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid MemberAccessObj", value) +} + +// NewMemberAccessObjFromValue returns a pointer to a valid MemberAccessObj +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewMemberAccessObjFromValue(v string) (*MemberAccessObj, error) { + ev := MemberAccessObj(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for MemberAccessObj: valid values are %v", v, AllowedMemberAccessObjEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v MemberAccessObj) IsValid() bool { + for _, existing := range AllowedMemberAccessObjEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to MemberAccessObj value +func (v MemberAccessObj) Ptr() *MemberAccessObj { + return &v +} + +type NullableMemberAccessObj struct { + value *MemberAccessObj + isSet bool +} + +func (v NullableMemberAccessObj) Get() *MemberAccessObj { + return v.value +} + +func (v *NullableMemberAccessObj) Set(val *MemberAccessObj) { + v.value = val + v.isSet = true +} + +func (v NullableMemberAccessObj) IsSet() bool { + return v.isSet +} + +func (v *NullableMemberAccessObj) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMemberAccessObj(val *MemberAccessObj) *NullableMemberAccessObj { + return &NullableMemberAccessObj{value: val, isSet: true} +} + +func (v NullableMemberAccessObj) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMemberAccessObj) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_methods.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_methods.go new file mode 100644 index 00000000..a2e0556e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_methods.go @@ -0,0 +1,120 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// Methods An enumeration. +type Methods string + +// List of Methods +const ( + GET Methods = "get" + POST Methods = "post" + PUT Methods = "put" + PATCH Methods = "patch" + DELETE Methods = "delete" + HEAD Methods = "head" + OPTIONS Methods = "options" +) + +// All allowed values of Methods enum +var AllowedMethodsEnumValues = []Methods{ + "get", + "post", + "put", + "patch", + "delete", + "head", + "options", +} + +func (v *Methods) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := Methods(value) + for _, existing := range AllowedMethodsEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid Methods", value) +} + +// NewMethodsFromValue returns a pointer to a valid Methods +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewMethodsFromValue(v string) (*Methods, error) { + ev := Methods(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for Methods: valid values are %v", v, AllowedMethodsEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Methods) IsValid() bool { + for _, existing := range AllowedMethodsEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to Methods value +func (v Methods) Ptr() *Methods { + return &v +} + +type NullableMethods struct { + value *Methods + isSet bool +} + +func (v NullableMethods) Get() *Methods { + return v.value +} + +func (v *NullableMethods) Set(val *Methods) { + v.value = val + v.isSet = true +} + +func (v NullableMethods) IsSet() bool { + return v.isSet +} + +func (v *NullableMethods) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMethods(val *Methods) *NullableMethods { + return &NullableMethods{value: val, isSet: true} +} + +func (v NullableMethods) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMethods) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_multi_invite_result.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_multi_invite_result.go new file mode 100644 index 00000000..da185145 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_multi_invite_result.go @@ -0,0 +1,143 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// MultiInviteResult struct for MultiInviteResult +type MultiInviteResult struct { + Success []InviteRead `json:"success"` + // invites that were not even attempted, and the reason why + Failed []FailedInvite `json:"failed,omitempty"` +} + +// NewMultiInviteResult instantiates a new MultiInviteResult object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewMultiInviteResult(success []InviteRead) *MultiInviteResult { + this := MultiInviteResult{} + this.Success = success + return &this +} + +// NewMultiInviteResultWithDefaults instantiates a new MultiInviteResult object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewMultiInviteResultWithDefaults() *MultiInviteResult { + this := MultiInviteResult{} + return &this +} + +// GetSuccess returns the Success field value +func (o *MultiInviteResult) GetSuccess() []InviteRead { + if o == nil { + var ret []InviteRead + return ret + } + + return o.Success +} + +// GetSuccessOk returns a tuple with the Success field value +// and a boolean to check if the value has been set. +func (o *MultiInviteResult) GetSuccessOk() ([]InviteRead, bool) { + if o == nil { + return nil, false + } + return o.Success, true +} + +// SetSuccess sets field value +func (o *MultiInviteResult) SetSuccess(v []InviteRead) { + o.Success = v +} + +// GetFailed returns the Failed field value if set, zero value otherwise. +func (o *MultiInviteResult) GetFailed() []FailedInvite { + if o == nil || IsNil(o.Failed) { + var ret []FailedInvite + return ret + } + return o.Failed +} + +// GetFailedOk returns a tuple with the Failed field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MultiInviteResult) GetFailedOk() ([]FailedInvite, bool) { + if o == nil || IsNil(o.Failed) { + return nil, false + } + return o.Failed, true +} + +// HasFailed returns a boolean if a field has been set. +func (o *MultiInviteResult) HasFailed() bool { + if o != nil && !IsNil(o.Failed) { + return true + } + + return false +} + +// SetFailed gets a reference to the given []FailedInvite and assigns it to the Failed field. +func (o *MultiInviteResult) SetFailed(v []FailedInvite) { + o.Failed = v +} + +func (o MultiInviteResult) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["success"] = o.Success + } + if !IsNil(o.Failed) { + toSerialize["failed"] = o.Failed + } + return json.Marshal(toSerialize) +} + +type NullableMultiInviteResult struct { + value *MultiInviteResult + isSet bool +} + +func (v NullableMultiInviteResult) Get() *MultiInviteResult { + return v.value +} + +func (v *NullableMultiInviteResult) Set(val *MultiInviteResult) { + v.value = val + v.isSet = true +} + +func (v NullableMultiInviteResult) IsSet() bool { + return v.isSet +} + +func (v *NullableMultiInviteResult) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMultiInviteResult(val *MultiInviteResult) *NullableMultiInviteResult { + return &NullableMultiInviteResult{value: val, isSet: true} +} + +func (v NullableMultiInviteResult) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMultiInviteResult) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_new.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_new.go new file mode 100644 index 00000000..1ad16e76 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_new.go @@ -0,0 +1,254 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the New type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &New{} + +// New Description of the environment to create. This environment must not already exist. +type New struct { + // A URL-friendly name of the environment (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the environment. + Key string `json:"key"` + // The name of the environment + Name string `json:"name"` + // an optional longer description of the environment + Description *string `json:"description,omitempty"` + // when using gitops feature, an optional branch name for the environment + CustomBranchName *string `json:"custom_branch_name,omitempty"` + Jwks *Jwks `json:"jwks,omitempty"` +} + +// NewNew instantiates a new New object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewNew(key string, name string) *New { + this := New{} + this.Key = key + this.Name = name + return &this +} + +// NewNewWithDefaults instantiates a new New object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewNewWithDefaults() *New { + this := New{} + return &this +} + +// GetKey returns the Key field value +func (o *New) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *New) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *New) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *New) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *New) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *New) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *New) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *New) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *New) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *New) SetDescription(v string) { + o.Description = &v +} + +// GetCustomBranchName returns the CustomBranchName field value if set, zero value otherwise. +func (o *New) GetCustomBranchName() string { + if o == nil || IsNil(o.CustomBranchName) { + var ret string + return ret + } + return *o.CustomBranchName +} + +// GetCustomBranchNameOk returns a tuple with the CustomBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *New) GetCustomBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.CustomBranchName) { + return nil, false + } + return o.CustomBranchName, true +} + +// HasCustomBranchName returns a boolean if a field has been set. +func (o *New) HasCustomBranchName() bool { + if o != nil && !IsNil(o.CustomBranchName) { + return true + } + + return false +} + +// SetCustomBranchName gets a reference to the given string and assigns it to the CustomBranchName field. +func (o *New) SetCustomBranchName(v string) { + o.CustomBranchName = &v +} + +// GetJwks returns the Jwks field value if set, zero value otherwise. +func (o *New) GetJwks() Jwks { + if o == nil || IsNil(o.Jwks) { + var ret Jwks + return ret + } + return *o.Jwks +} + +// GetJwksOk returns a tuple with the Jwks field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *New) GetJwksOk() (*Jwks, bool) { + if o == nil || IsNil(o.Jwks) { + return nil, false + } + return o.Jwks, true +} + +// HasJwks returns a boolean if a field has been set. +func (o *New) HasJwks() bool { + if o != nil && !IsNil(o.Jwks) { + return true + } + + return false +} + +// SetJwks gets a reference to the given Jwks and assigns it to the Jwks field. +func (o *New) SetJwks(v Jwks) { + o.Jwks = &v +} + +func (o New) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o New) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.CustomBranchName) { + toSerialize["custom_branch_name"] = o.CustomBranchName + } + if !IsNil(o.Jwks) { + toSerialize["jwks"] = o.Jwks + } + return toSerialize, nil +} + +type NullableNew struct { + value *New + isSet bool +} + +func (v NullableNew) Get() *New { + return v.value +} + +func (v *NullableNew) Set(val *New) { + v.value = val + v.isSet = true +} + +func (v NullableNew) IsSet() bool { + return v.isSet +} + +func (v *NullableNew) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableNew(val *New) *NullableNew { + return &NullableNew{value: val, isSet: true} +} + +func (v NullableNew) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableNew) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_onboarding_step.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_onboarding_step.go new file mode 100644 index 00000000..5dfc1c07 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_onboarding_step.go @@ -0,0 +1,122 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// OnboardingStep An enumeration. +type OnboardingStep string + +// List of OnboardingStep +const ( + CREATE_ORGANIZATION OnboardingStep = "create_organization" + CREATE_PROJECT OnboardingStep = "create_project" + CREATE_RESOURCE OnboardingStep = "create_resource" + CREATE_ACTIONS OnboardingStep = "create_actions" + ASSIGN_PERMISSIONS OnboardingStep = "assign_permissions" + ASSIGN_USER_ROLES OnboardingStep = "assign_user_roles" + CONNECT_SDK OnboardingStep = "connect_sdk" + DONE OnboardingStep = "done" +) + +// All allowed values of OnboardingStep enum +var AllowedOnboardingStepEnumValues = []OnboardingStep{ + "create_organization", + "create_project", + "create_resource", + "create_actions", + "assign_permissions", + "assign_user_roles", + "connect_sdk", + "done", +} + +func (v *OnboardingStep) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := OnboardingStep(value) + for _, existing := range AllowedOnboardingStepEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid OnboardingStep", value) +} + +// NewOnboardingStepFromValue returns a pointer to a valid OnboardingStep +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewOnboardingStepFromValue(v string) (*OnboardingStep, error) { + ev := OnboardingStep(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for OnboardingStep: valid values are %v", v, AllowedOnboardingStepEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v OnboardingStep) IsValid() bool { + for _, existing := range AllowedOnboardingStepEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to OnboardingStep value +func (v OnboardingStep) Ptr() *OnboardingStep { + return &v +} + +type NullableOnboardingStep struct { + value *OnboardingStep + isSet bool +} + +func (v NullableOnboardingStep) Get() *OnboardingStep { + return v.value +} + +func (v *NullableOnboardingStep) Set(val *OnboardingStep) { + v.value = val + v.isSet = true +} + +func (v NullableOnboardingStep) IsSet() bool { + return v.isSet +} + +func (v *NullableOnboardingStep) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOnboardingStep(val *OnboardingStep) *NullableOnboardingStep { + return &NullableOnboardingStep{value: val, isSet: true} +} + +func (v NullableOnboardingStep) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOnboardingStep) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_opa_decision_log.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_opa_decision_log.go new file mode 100644 index 00000000..35f277f7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_opa_decision_log.go @@ -0,0 +1,309 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// OPADecisionLog struct for OPADecisionLog +type OPADecisionLog struct { + DecisionId string `json:"decision_id"` + Labels Labels `json:"labels"` + RunId *string `json:"run_id,omitempty"` + Timestamp time.Time `json:"timestamp"` + Path *string `json:"path,omitempty"` + Input map[string]interface{} `json:"input,omitempty"` + Result map[string]interface{} `json:"result,omitempty"` +} + +// NewOPADecisionLog instantiates a new OPADecisionLog object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOPADecisionLog(decisionId string, labels Labels, timestamp time.Time) *OPADecisionLog { + this := OPADecisionLog{} + this.DecisionId = decisionId + this.Labels = labels + this.Timestamp = timestamp + return &this +} + +// NewOPADecisionLogWithDefaults instantiates a new OPADecisionLog object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOPADecisionLogWithDefaults() *OPADecisionLog { + this := OPADecisionLog{} + return &this +} + +// GetDecisionId returns the DecisionId field value +func (o *OPADecisionLog) GetDecisionId() string { + if o == nil { + var ret string + return ret + } + + return o.DecisionId +} + +// GetDecisionIdOk returns a tuple with the DecisionId field value +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetDecisionIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.DecisionId, true +} + +// SetDecisionId sets field value +func (o *OPADecisionLog) SetDecisionId(v string) { + o.DecisionId = v +} + +// GetLabels returns the Labels field value +func (o *OPADecisionLog) GetLabels() Labels { + if o == nil { + var ret Labels + return ret + } + + return o.Labels +} + +// GetLabelsOk returns a tuple with the Labels field value +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetLabelsOk() (*Labels, bool) { + if o == nil { + return nil, false + } + return &o.Labels, true +} + +// SetLabels sets field value +func (o *OPADecisionLog) SetLabels(v Labels) { + o.Labels = v +} + +// GetRunId returns the RunId field value if set, zero value otherwise. +func (o *OPADecisionLog) GetRunId() string { + if o == nil || IsNil(o.RunId) { + var ret string + return ret + } + return *o.RunId +} + +// GetRunIdOk returns a tuple with the RunId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetRunIdOk() (*string, bool) { + if o == nil || IsNil(o.RunId) { + return nil, false + } + return o.RunId, true +} + +// HasRunId returns a boolean if a field has been set. +func (o *OPADecisionLog) HasRunId() bool { + if o != nil && !IsNil(o.RunId) { + return true + } + + return false +} + +// SetRunId gets a reference to the given string and assigns it to the RunId field. +func (o *OPADecisionLog) SetRunId(v string) { + o.RunId = &v +} + +// GetTimestamp returns the Timestamp field value +func (o *OPADecisionLog) GetTimestamp() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.Timestamp +} + +// GetTimestampOk returns a tuple with the Timestamp field value +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetTimestampOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.Timestamp, true +} + +// SetTimestamp sets field value +func (o *OPADecisionLog) SetTimestamp(v time.Time) { + o.Timestamp = v +} + +// GetPath returns the Path field value if set, zero value otherwise. +func (o *OPADecisionLog) GetPath() string { + if o == nil || IsNil(o.Path) { + var ret string + return ret + } + return *o.Path +} + +// GetPathOk returns a tuple with the Path field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetPathOk() (*string, bool) { + if o == nil || IsNil(o.Path) { + return nil, false + } + return o.Path, true +} + +// HasPath returns a boolean if a field has been set. +func (o *OPADecisionLog) HasPath() bool { + if o != nil && !IsNil(o.Path) { + return true + } + + return false +} + +// SetPath gets a reference to the given string and assigns it to the Path field. +func (o *OPADecisionLog) SetPath(v string) { + o.Path = &v +} + +// GetInput returns the Input field value if set, zero value otherwise. +func (o *OPADecisionLog) GetInput() map[string]interface{} { + if o == nil || IsNil(o.Input) { + var ret map[string]interface{} + return ret + } + return o.Input +} + +// GetInputOk returns a tuple with the Input field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetInputOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Input) { + return map[string]interface{}{}, false + } + return o.Input, true +} + +// HasInput returns a boolean if a field has been set. +func (o *OPADecisionLog) HasInput() bool { + if o != nil && !IsNil(o.Input) { + return true + } + + return false +} + +// SetInput gets a reference to the given map[string]interface{} and assigns it to the Input field. +func (o *OPADecisionLog) SetInput(v map[string]interface{}) { + o.Input = v +} + +// GetResult returns the Result field value if set, zero value otherwise. +func (o *OPADecisionLog) GetResult() map[string]interface{} { + if o == nil || IsNil(o.Result) { + var ret map[string]interface{} + return ret + } + return o.Result +} + +// GetResultOk returns a tuple with the Result field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OPADecisionLog) GetResultOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Result) { + return map[string]interface{}{}, false + } + return o.Result, true +} + +// HasResult returns a boolean if a field has been set. +func (o *OPADecisionLog) HasResult() bool { + if o != nil && !IsNil(o.Result) { + return true + } + + return false +} + +// SetResult gets a reference to the given map[string]interface{} and assigns it to the Result field. +func (o *OPADecisionLog) SetResult(v map[string]interface{}) { + o.Result = v +} + +func (o OPADecisionLog) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["decision_id"] = o.DecisionId + } + if true { + toSerialize["labels"] = o.Labels + } + if !IsNil(o.RunId) { + toSerialize["run_id"] = o.RunId + } + if true { + toSerialize["timestamp"] = o.Timestamp + } + if !IsNil(o.Path) { + toSerialize["path"] = o.Path + } + if !IsNil(o.Input) { + toSerialize["input"] = o.Input + } + if !IsNil(o.Result) { + toSerialize["result"] = o.Result + } + return json.Marshal(toSerialize) +} + +type NullableOPADecisionLog struct { + value *OPADecisionLog + isSet bool +} + +func (v NullableOPADecisionLog) Get() *OPADecisionLog { + return v.value +} + +func (v *NullableOPADecisionLog) Set(val *OPADecisionLog) { + v.value = val + v.isSet = true +} + +func (v NullableOPADecisionLog) IsSet() bool { + return v.isSet +} + +func (v *NullableOPADecisionLog) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOPADecisionLog(val *OPADecisionLog) *NullableOPADecisionLog { + return &NullableOPADecisionLog{value: val, isSet: true} +} + +func (v NullableOPADecisionLog) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOPADecisionLog) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_opal_client.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_opal_client.go new file mode 100644 index 00000000..d2b83657 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_opal_client.go @@ -0,0 +1,287 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// OPALClient struct for OPALClient +type OPALClient struct { + DATA_TOPICS []string `json:"DATA_TOPICS"` + CLIENT_TOKEN string `json:"CLIENT_TOKEN"` + SERVER_URL string `json:"SERVER_URL"` + SERVER_WS_URL string `json:"SERVER_WS_URL"` + SERVER_PUBSUB_URL string `json:"SERVER_PUBSUB_URL"` + DEFAULT_DATA_SOURCES_CONFIG_URL string `json:"DEFAULT_DATA_SOURCES_CONFIG_URL"` + SCOPE_ID *string `json:"SCOPE_ID,omitempty"` +} + +// NewOPALClient instantiates a new OPALClient object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOPALClient(dATATOPICS []string, cLIENTTOKEN string, sERVERURL string, sERVERWSURL string, sERVERPUBSUBURL string, dEFAULTDATASOURCESCONFIGURL string) *OPALClient { + this := OPALClient{} + this.DATA_TOPICS = dATATOPICS + this.CLIENT_TOKEN = cLIENTTOKEN + this.SERVER_URL = sERVERURL + this.SERVER_WS_URL = sERVERWSURL + this.SERVER_PUBSUB_URL = sERVERPUBSUBURL + this.DEFAULT_DATA_SOURCES_CONFIG_URL = dEFAULTDATASOURCESCONFIGURL + return &this +} + +// NewOPALClientWithDefaults instantiates a new OPALClient object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOPALClientWithDefaults() *OPALClient { + this := OPALClient{} + return &this +} + +// GetDATA_TOPICS returns the DATA_TOPICS field value +func (o *OPALClient) GetDATA_TOPICS() []string { + if o == nil { + var ret []string + return ret + } + + return o.DATA_TOPICS +} + +// GetDATA_TOPICSOk returns a tuple with the DATA_TOPICS field value +// and a boolean to check if the value has been set. +func (o *OPALClient) GetDATA_TOPICSOk() ([]string, bool) { + if o == nil { + return nil, false + } + return o.DATA_TOPICS, true +} + +// SetDATA_TOPICS sets field value +func (o *OPALClient) SetDATA_TOPICS(v []string) { + o.DATA_TOPICS = v +} + +// GetCLIENT_TOKEN returns the CLIENT_TOKEN field value +func (o *OPALClient) GetCLIENT_TOKEN() string { + if o == nil { + var ret string + return ret + } + + return o.CLIENT_TOKEN +} + +// GetCLIENT_TOKENOk returns a tuple with the CLIENT_TOKEN field value +// and a boolean to check if the value has been set. +func (o *OPALClient) GetCLIENT_TOKENOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.CLIENT_TOKEN, true +} + +// SetCLIENT_TOKEN sets field value +func (o *OPALClient) SetCLIENT_TOKEN(v string) { + o.CLIENT_TOKEN = v +} + +// GetSERVER_URL returns the SERVER_URL field value +func (o *OPALClient) GetSERVER_URL() string { + if o == nil { + var ret string + return ret + } + + return o.SERVER_URL +} + +// GetSERVER_URLOk returns a tuple with the SERVER_URL field value +// and a boolean to check if the value has been set. +func (o *OPALClient) GetSERVER_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SERVER_URL, true +} + +// SetSERVER_URL sets field value +func (o *OPALClient) SetSERVER_URL(v string) { + o.SERVER_URL = v +} + +// GetSERVER_WS_URL returns the SERVER_WS_URL field value +func (o *OPALClient) GetSERVER_WS_URL() string { + if o == nil { + var ret string + return ret + } + + return o.SERVER_WS_URL +} + +// GetSERVER_WS_URLOk returns a tuple with the SERVER_WS_URL field value +// and a boolean to check if the value has been set. +func (o *OPALClient) GetSERVER_WS_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SERVER_WS_URL, true +} + +// SetSERVER_WS_URL sets field value +func (o *OPALClient) SetSERVER_WS_URL(v string) { + o.SERVER_WS_URL = v +} + +// GetSERVER_PUBSUB_URL returns the SERVER_PUBSUB_URL field value +func (o *OPALClient) GetSERVER_PUBSUB_URL() string { + if o == nil { + var ret string + return ret + } + + return o.SERVER_PUBSUB_URL +} + +// GetSERVER_PUBSUB_URLOk returns a tuple with the SERVER_PUBSUB_URL field value +// and a boolean to check if the value has been set. +func (o *OPALClient) GetSERVER_PUBSUB_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SERVER_PUBSUB_URL, true +} + +// SetSERVER_PUBSUB_URL sets field value +func (o *OPALClient) SetSERVER_PUBSUB_URL(v string) { + o.SERVER_PUBSUB_URL = v +} + +// GetDEFAULT_DATA_SOURCES_CONFIG_URL returns the DEFAULT_DATA_SOURCES_CONFIG_URL field value +func (o *OPALClient) GetDEFAULT_DATA_SOURCES_CONFIG_URL() string { + if o == nil { + var ret string + return ret + } + + return o.DEFAULT_DATA_SOURCES_CONFIG_URL +} + +// GetDEFAULT_DATA_SOURCES_CONFIG_URLOk returns a tuple with the DEFAULT_DATA_SOURCES_CONFIG_URL field value +// and a boolean to check if the value has been set. +func (o *OPALClient) GetDEFAULT_DATA_SOURCES_CONFIG_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.DEFAULT_DATA_SOURCES_CONFIG_URL, true +} + +// SetDEFAULT_DATA_SOURCES_CONFIG_URL sets field value +func (o *OPALClient) SetDEFAULT_DATA_SOURCES_CONFIG_URL(v string) { + o.DEFAULT_DATA_SOURCES_CONFIG_URL = v +} + +// GetSCOPE_ID returns the SCOPE_ID field value if set, zero value otherwise. +func (o *OPALClient) GetSCOPE_ID() string { + if o == nil || IsNil(o.SCOPE_ID) { + var ret string + return ret + } + return *o.SCOPE_ID +} + +// GetSCOPE_IDOk returns a tuple with the SCOPE_ID field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OPALClient) GetSCOPE_IDOk() (*string, bool) { + if o == nil || IsNil(o.SCOPE_ID) { + return nil, false + } + return o.SCOPE_ID, true +} + +// HasSCOPE_ID returns a boolean if a field has been set. +func (o *OPALClient) HasSCOPE_ID() bool { + if o != nil && !IsNil(o.SCOPE_ID) { + return true + } + + return false +} + +// SetSCOPE_ID gets a reference to the given string and assigns it to the SCOPE_ID field. +func (o *OPALClient) SetSCOPE_ID(v string) { + o.SCOPE_ID = &v +} + +func (o OPALClient) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["DATA_TOPICS"] = o.DATA_TOPICS + } + if true { + toSerialize["CLIENT_TOKEN"] = o.CLIENT_TOKEN + } + if true { + toSerialize["SERVER_URL"] = o.SERVER_URL + } + if true { + toSerialize["SERVER_WS_URL"] = o.SERVER_WS_URL + } + if true { + toSerialize["SERVER_PUBSUB_URL"] = o.SERVER_PUBSUB_URL + } + if true { + toSerialize["DEFAULT_DATA_SOURCES_CONFIG_URL"] = o.DEFAULT_DATA_SOURCES_CONFIG_URL + } + if !IsNil(o.SCOPE_ID) { + toSerialize["SCOPE_ID"] = o.SCOPE_ID + } + return json.Marshal(toSerialize) +} + +type NullableOPALClient struct { + value *OPALClient + isSet bool +} + +func (v NullableOPALClient) Get() *OPALClient { + return v.value +} + +func (v *NullableOPALClient) Set(val *OPALClient) { + v.value = val + v.isSet = true +} + +func (v NullableOPALClient) IsSet() bool { + return v.isSet +} + +func (v *NullableOPALClient) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOPALClient(val *OPALClient) *NullableOPALClient { + return &NullableOPALClient{value: val, isSet: true} +} + +func (v NullableOPALClient) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOPALClient) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_read.go new file mode 100644 index 00000000..677de366 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_read.go @@ -0,0 +1,614 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// OrgMemberRead struct for OrgMemberRead +type OrgMemberRead struct { + // Unique id of the account member + Id string `json:"id"` + // Email of the user controlling this account + Email string `json:"email"` + // Whether this email address is verified or not. For social providers like 'Login with Google' this is done automatically, otherwise we will send the user a verification link in email. + EmailVerified bool `json:"email_verified"` + // Name of this user + Name *string `json:"name,omitempty"` + // First name of the user + GivenName *string `json:"given_name,omitempty"` + // Last name of the user + FamilyName *string `json:"family_name,omitempty"` + // URL to picture, photo, or avatar of the user that controls this account. + Picture *string `json:"picture,omitempty"` + // Whether or not this user has special access to permit.io organizations + IsSuperuser bool `json:"is_superuser"` + // Whether or not this user is currently onboarding, needs to be replaced by a user journey object + IsOnboarding bool `json:"is_onboarding"` + // the step the user is currently going through in onboarding + OnboardingStep OnboardingStep `json:"onboarding_step"` + // Date and time when the account member was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Last date and time this user logged in (ISO_8601 format). + LastLogin *time.Time `json:"last_login,omitempty"` + // Last IP address from which this user logged in. + LastIp *string `json:"last_ip,omitempty"` + // Total number of logins this user has performed. + LoginsCount *int32 `json:"logins_count,omitempty"` + Identities []IdentityRead `json:"identities"` + // Custom permit.io dashboard settings, such as preferred theme, etc. + Settings map[string]interface{} `json:"settings"` +} + +// NewOrgMemberRead instantiates a new OrgMemberRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOrgMemberRead(id string, email string, emailVerified bool, isSuperuser bool, isOnboarding bool, onboardingStep OnboardingStep, createdAt time.Time, identities []IdentityRead, settings map[string]interface{}) *OrgMemberRead { + this := OrgMemberRead{} + this.Id = id + this.Email = email + this.EmailVerified = emailVerified + this.IsSuperuser = isSuperuser + this.IsOnboarding = isOnboarding + this.OnboardingStep = onboardingStep + this.CreatedAt = createdAt + var lastIp string = "0.0.0.0" + this.LastIp = &lastIp + var loginsCount int32 = 0 + this.LoginsCount = &loginsCount + this.Identities = identities + this.Settings = settings + return &this +} + +// NewOrgMemberReadWithDefaults instantiates a new OrgMemberRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOrgMemberReadWithDefaults() *OrgMemberRead { + this := OrgMemberRead{} + var lastIp string = "0.0.0.0" + this.LastIp = &lastIp + var loginsCount int32 = 0 + this.LoginsCount = &loginsCount + return &this +} + +// GetId returns the Id field value +func (o *OrgMemberRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *OrgMemberRead) SetId(v string) { + o.Id = v +} + +// GetEmail returns the Email field value +func (o *OrgMemberRead) GetEmail() string { + if o == nil { + var ret string + return ret + } + + return o.Email +} + +// GetEmailOk returns a tuple with the Email field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetEmailOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Email, true +} + +// SetEmail sets field value +func (o *OrgMemberRead) SetEmail(v string) { + o.Email = v +} + +// GetEmailVerified returns the EmailVerified field value +func (o *OrgMemberRead) GetEmailVerified() bool { + if o == nil { + var ret bool + return ret + } + + return o.EmailVerified +} + +// GetEmailVerifiedOk returns a tuple with the EmailVerified field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetEmailVerifiedOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.EmailVerified, true +} + +// SetEmailVerified sets field value +func (o *OrgMemberRead) SetEmailVerified(v bool) { + o.EmailVerified = v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *OrgMemberRead) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *OrgMemberRead) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *OrgMemberRead) SetName(v string) { + o.Name = &v +} + +// GetGivenName returns the GivenName field value if set, zero value otherwise. +func (o *OrgMemberRead) GetGivenName() string { + if o == nil || IsNil(o.GivenName) { + var ret string + return ret + } + return *o.GivenName +} + +// GetGivenNameOk returns a tuple with the GivenName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetGivenNameOk() (*string, bool) { + if o == nil || IsNil(o.GivenName) { + return nil, false + } + return o.GivenName, true +} + +// HasGivenName returns a boolean if a field has been set. +func (o *OrgMemberRead) HasGivenName() bool { + if o != nil && !IsNil(o.GivenName) { + return true + } + + return false +} + +// SetGivenName gets a reference to the given string and assigns it to the GivenName field. +func (o *OrgMemberRead) SetGivenName(v string) { + o.GivenName = &v +} + +// GetFamilyName returns the FamilyName field value if set, zero value otherwise. +func (o *OrgMemberRead) GetFamilyName() string { + if o == nil || IsNil(o.FamilyName) { + var ret string + return ret + } + return *o.FamilyName +} + +// GetFamilyNameOk returns a tuple with the FamilyName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetFamilyNameOk() (*string, bool) { + if o == nil || IsNil(o.FamilyName) { + return nil, false + } + return o.FamilyName, true +} + +// HasFamilyName returns a boolean if a field has been set. +func (o *OrgMemberRead) HasFamilyName() bool { + if o != nil && !IsNil(o.FamilyName) { + return true + } + + return false +} + +// SetFamilyName gets a reference to the given string and assigns it to the FamilyName field. +func (o *OrgMemberRead) SetFamilyName(v string) { + o.FamilyName = &v +} + +// GetPicture returns the Picture field value if set, zero value otherwise. +func (o *OrgMemberRead) GetPicture() string { + if o == nil || IsNil(o.Picture) { + var ret string + return ret + } + return *o.Picture +} + +// GetPictureOk returns a tuple with the Picture field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetPictureOk() (*string, bool) { + if o == nil || IsNil(o.Picture) { + return nil, false + } + return o.Picture, true +} + +// HasPicture returns a boolean if a field has been set. +func (o *OrgMemberRead) HasPicture() bool { + if o != nil && !IsNil(o.Picture) { + return true + } + + return false +} + +// SetPicture gets a reference to the given string and assigns it to the Picture field. +func (o *OrgMemberRead) SetPicture(v string) { + o.Picture = &v +} + +// GetIsSuperuser returns the IsSuperuser field value +func (o *OrgMemberRead) GetIsSuperuser() bool { + if o == nil { + var ret bool + return ret + } + + return o.IsSuperuser +} + +// GetIsSuperuserOk returns a tuple with the IsSuperuser field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetIsSuperuserOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.IsSuperuser, true +} + +// SetIsSuperuser sets field value +func (o *OrgMemberRead) SetIsSuperuser(v bool) { + o.IsSuperuser = v +} + +// GetIsOnboarding returns the IsOnboarding field value +func (o *OrgMemberRead) GetIsOnboarding() bool { + if o == nil { + var ret bool + return ret + } + + return o.IsOnboarding +} + +// GetIsOnboardingOk returns a tuple with the IsOnboarding field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetIsOnboardingOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.IsOnboarding, true +} + +// SetIsOnboarding sets field value +func (o *OrgMemberRead) SetIsOnboarding(v bool) { + o.IsOnboarding = v +} + +// GetOnboardingStep returns the OnboardingStep field value +func (o *OrgMemberRead) GetOnboardingStep() OnboardingStep { + if o == nil { + var ret OnboardingStep + return ret + } + + return o.OnboardingStep +} + +// GetOnboardingStepOk returns a tuple with the OnboardingStep field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetOnboardingStepOk() (*OnboardingStep, bool) { + if o == nil { + return nil, false + } + return &o.OnboardingStep, true +} + +// SetOnboardingStep sets field value +func (o *OrgMemberRead) SetOnboardingStep(v OnboardingStep) { + o.OnboardingStep = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *OrgMemberRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *OrgMemberRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetLastLogin returns the LastLogin field value if set, zero value otherwise. +func (o *OrgMemberRead) GetLastLogin() time.Time { + if o == nil || IsNil(o.LastLogin) { + var ret time.Time + return ret + } + return *o.LastLogin +} + +// GetLastLoginOk returns a tuple with the LastLogin field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetLastLoginOk() (*time.Time, bool) { + if o == nil || IsNil(o.LastLogin) { + return nil, false + } + return o.LastLogin, true +} + +// HasLastLogin returns a boolean if a field has been set. +func (o *OrgMemberRead) HasLastLogin() bool { + if o != nil && !IsNil(o.LastLogin) { + return true + } + + return false +} + +// SetLastLogin gets a reference to the given time.Time and assigns it to the LastLogin field. +func (o *OrgMemberRead) SetLastLogin(v time.Time) { + o.LastLogin = &v +} + +// GetLastIp returns the LastIp field value if set, zero value otherwise. +func (o *OrgMemberRead) GetLastIp() string { + if o == nil || IsNil(o.LastIp) { + var ret string + return ret + } + return *o.LastIp +} + +// GetLastIpOk returns a tuple with the LastIp field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetLastIpOk() (*string, bool) { + if o == nil || IsNil(o.LastIp) { + return nil, false + } + return o.LastIp, true +} + +// HasLastIp returns a boolean if a field has been set. +func (o *OrgMemberRead) HasLastIp() bool { + if o != nil && !IsNil(o.LastIp) { + return true + } + + return false +} + +// SetLastIp gets a reference to the given string and assigns it to the LastIp field. +func (o *OrgMemberRead) SetLastIp(v string) { + o.LastIp = &v +} + +// GetLoginsCount returns the LoginsCount field value if set, zero value otherwise. +func (o *OrgMemberRead) GetLoginsCount() int32 { + if o == nil || IsNil(o.LoginsCount) { + var ret int32 + return ret + } + return *o.LoginsCount +} + +// GetLoginsCountOk returns a tuple with the LoginsCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetLoginsCountOk() (*int32, bool) { + if o == nil || IsNil(o.LoginsCount) { + return nil, false + } + return o.LoginsCount, true +} + +// HasLoginsCount returns a boolean if a field has been set. +func (o *OrgMemberRead) HasLoginsCount() bool { + if o != nil && !IsNil(o.LoginsCount) { + return true + } + + return false +} + +// SetLoginsCount gets a reference to the given int32 and assigns it to the LoginsCount field. +func (o *OrgMemberRead) SetLoginsCount(v int32) { + o.LoginsCount = &v +} + +// GetIdentities returns the Identities field value +func (o *OrgMemberRead) GetIdentities() []IdentityRead { + if o == nil { + var ret []IdentityRead + return ret + } + + return o.Identities +} + +// GetIdentitiesOk returns a tuple with the Identities field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetIdentitiesOk() ([]IdentityRead, bool) { + if o == nil { + return nil, false + } + return o.Identities, true +} + +// SetIdentities sets field value +func (o *OrgMemberRead) SetIdentities(v []IdentityRead) { + o.Identities = v +} + +// GetSettings returns the Settings field value +func (o *OrgMemberRead) GetSettings() map[string]interface{} { + if o == nil { + var ret map[string]interface{} + return ret + } + + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value +// and a boolean to check if the value has been set. +func (o *OrgMemberRead) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// SetSettings sets field value +func (o *OrgMemberRead) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +func (o OrgMemberRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["email"] = o.Email + } + if true { + toSerialize["email_verified"] = o.EmailVerified + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.GivenName) { + toSerialize["given_name"] = o.GivenName + } + if !IsNil(o.FamilyName) { + toSerialize["family_name"] = o.FamilyName + } + if !IsNil(o.Picture) { + toSerialize["picture"] = o.Picture + } + if true { + toSerialize["is_superuser"] = o.IsSuperuser + } + if true { + toSerialize["is_onboarding"] = o.IsOnboarding + } + if true { + toSerialize["onboarding_step"] = o.OnboardingStep + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.LastLogin) { + toSerialize["last_login"] = o.LastLogin + } + if !IsNil(o.LastIp) { + toSerialize["last_ip"] = o.LastIp + } + if !IsNil(o.LoginsCount) { + toSerialize["logins_count"] = o.LoginsCount + } + if true { + toSerialize["identities"] = o.Identities + } + if true { + toSerialize["settings"] = o.Settings + } + return json.Marshal(toSerialize) +} + +type NullableOrgMemberRead struct { + value *OrgMemberRead + isSet bool +} + +func (v NullableOrgMemberRead) Get() *OrgMemberRead { + return v.value +} + +func (v *NullableOrgMemberRead) Set(val *OrgMemberRead) { + v.value = val + v.isSet = true +} + +func (v NullableOrgMemberRead) IsSet() bool { + return v.isSet +} + +func (v *NullableOrgMemberRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrgMemberRead(val *OrgMemberRead) *NullableOrgMemberRead { + return &NullableOrgMemberRead{value: val, isSet: true} +} + +func (v NullableOrgMemberRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrgMemberRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_update.go new file mode 100644 index 00000000..afe42430 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_org_member_update.go @@ -0,0 +1,151 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// OrgMemberUpdate struct for OrgMemberUpdate +type OrgMemberUpdate struct { + // Custom permit.io dashboard settings, such as preferred theme, etc. + Settings map[string]interface{} `json:"settings,omitempty"` + // updates the onboarding step (optional) + OnboardingStep *OnboardingStep `json:"onboarding_step,omitempty"` +} + +// NewOrgMemberUpdate instantiates a new OrgMemberUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOrgMemberUpdate() *OrgMemberUpdate { + this := OrgMemberUpdate{} + return &this +} + +// NewOrgMemberUpdateWithDefaults instantiates a new OrgMemberUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOrgMemberUpdateWithDefaults() *OrgMemberUpdate { + this := OrgMemberUpdate{} + return &this +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *OrgMemberUpdate) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberUpdate) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *OrgMemberUpdate) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *OrgMemberUpdate) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +// GetOnboardingStep returns the OnboardingStep field value if set, zero value otherwise. +func (o *OrgMemberUpdate) GetOnboardingStep() OnboardingStep { + if o == nil || IsNil(o.OnboardingStep) { + var ret OnboardingStep + return ret + } + return *o.OnboardingStep +} + +// GetOnboardingStepOk returns a tuple with the OnboardingStep field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrgMemberUpdate) GetOnboardingStepOk() (*OnboardingStep, bool) { + if o == nil || IsNil(o.OnboardingStep) { + return nil, false + } + return o.OnboardingStep, true +} + +// HasOnboardingStep returns a boolean if a field has been set. +func (o *OrgMemberUpdate) HasOnboardingStep() bool { + if o != nil && !IsNil(o.OnboardingStep) { + return true + } + + return false +} + +// SetOnboardingStep gets a reference to the given OnboardingStep and assigns it to the OnboardingStep field. +func (o *OrgMemberUpdate) SetOnboardingStep(v OnboardingStep) { + o.OnboardingStep = &v +} + +func (o OrgMemberUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + if !IsNil(o.OnboardingStep) { + toSerialize["onboarding_step"] = o.OnboardingStep + } + return json.Marshal(toSerialize) +} + +type NullableOrgMemberUpdate struct { + value *OrgMemberUpdate + isSet bool +} + +func (v NullableOrgMemberUpdate) Get() *OrgMemberUpdate { + return v.value +} + +func (v *NullableOrgMemberUpdate) Set(val *OrgMemberUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableOrgMemberUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableOrgMemberUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrgMemberUpdate(val *OrgMemberUpdate) *NullableOrgMemberUpdate { + return &NullableOrgMemberUpdate{value: val, isSet: true} +} + +func (v NullableOrgMemberUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrgMemberUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_create.go new file mode 100644 index 00000000..750fdc71 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_create.go @@ -0,0 +1,174 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// OrganizationCreate struct for OrganizationCreate +type OrganizationCreate struct { + // A URL-friendly name of the organization (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the organization. + Key string `json:"key"` + // The name of the organization, usually it's your company's name. + Name string `json:"name"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` +} + +// NewOrganizationCreate instantiates a new OrganizationCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOrganizationCreate(key string, name string) *OrganizationCreate { + this := OrganizationCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewOrganizationCreateWithDefaults instantiates a new OrganizationCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOrganizationCreateWithDefaults() *OrganizationCreate { + this := OrganizationCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *OrganizationCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *OrganizationCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *OrganizationCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *OrganizationCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *OrganizationCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *OrganizationCreate) SetName(v string) { + o.Name = v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *OrganizationCreate) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationCreate) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *OrganizationCreate) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *OrganizationCreate) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +func (o OrganizationCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + return json.Marshal(toSerialize) +} + +type NullableOrganizationCreate struct { + value *OrganizationCreate + isSet bool +} + +func (v NullableOrganizationCreate) Get() *OrganizationCreate { + return v.value +} + +func (v *NullableOrganizationCreate) Set(val *OrganizationCreate) { + v.value = val + v.isSet = true +} + +func (v NullableOrganizationCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableOrganizationCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrganizationCreate(val *OrganizationCreate) *NullableOrganizationCreate { + return &NullableOrganizationCreate{value: val, isSet: true} +} + +func (v NullableOrganizationCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrganizationCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read.go new file mode 100644 index 00000000..ff38ac09 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read.go @@ -0,0 +1,265 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// OrganizationRead struct for OrganizationRead +type OrganizationRead struct { + // A URL-friendly name of the organization (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the organization. + Key string `json:"key"` + // Unique id of the organization + Id string `json:"id"` + // Date and time when the organization was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the organization was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The name of the organization, usually it's your company's name. + Name string `json:"name"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` +} + +// NewOrganizationRead instantiates a new OrganizationRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOrganizationRead(key string, id string, createdAt time.Time, updatedAt time.Time, name string) *OrganizationRead { + this := OrganizationRead{} + this.Key = key + this.Id = id + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + return &this +} + +// NewOrganizationReadWithDefaults instantiates a new OrganizationRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOrganizationReadWithDefaults() *OrganizationRead { + this := OrganizationRead{} + return &this +} + +// GetKey returns the Key field value +func (o *OrganizationRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *OrganizationRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *OrganizationRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *OrganizationRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *OrganizationRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *OrganizationRead) SetId(v string) { + o.Id = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *OrganizationRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *OrganizationRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *OrganizationRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *OrganizationRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *OrganizationRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *OrganizationRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetName returns the Name field value +func (o *OrganizationRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *OrganizationRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *OrganizationRead) SetName(v string) { + o.Name = v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *OrganizationRead) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationRead) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *OrganizationRead) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *OrganizationRead) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +func (o OrganizationRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + return json.Marshal(toSerialize) +} + +type NullableOrganizationRead struct { + value *OrganizationRead + isSet bool +} + +func (v NullableOrganizationRead) Get() *OrganizationRead { + return v.value +} + +func (v *NullableOrganizationRead) Set(val *OrganizationRead) { + v.value = val + v.isSet = true +} + +func (v NullableOrganizationRead) IsSet() bool { + return v.isSet +} + +func (v *NullableOrganizationRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrganizationRead(val *OrganizationRead) *NullableOrganizationRead { + return &NullableOrganizationRead{value: val, isSet: true} +} + +func (v NullableOrganizationRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrganizationRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read_with_api_key.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read_with_api_key.go new file mode 100644 index 00000000..9e4ed2e7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_read_with_api_key.go @@ -0,0 +1,337 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// OrganizationReadWithAPIKey struct for OrganizationReadWithAPIKey +type OrganizationReadWithAPIKey struct { + // A URL-friendly name of the organization (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the organization. + Key string `json:"key"` + // Unique id of the organization + Id string `json:"id"` + // Date and time when the organization was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the organization was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The name of the organization, usually it's your company's name. + Name string `json:"name"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` + ApiKeyId *string `json:"api_key_id,omitempty"` + ApiKeySecret *string `json:"api_key_secret,omitempty"` +} + +// NewOrganizationReadWithAPIKey instantiates a new OrganizationReadWithAPIKey object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOrganizationReadWithAPIKey(key string, id string, createdAt time.Time, updatedAt time.Time, name string) *OrganizationReadWithAPIKey { + this := OrganizationReadWithAPIKey{} + this.Key = key + this.Id = id + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + return &this +} + +// NewOrganizationReadWithAPIKeyWithDefaults instantiates a new OrganizationReadWithAPIKey object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOrganizationReadWithAPIKeyWithDefaults() *OrganizationReadWithAPIKey { + this := OrganizationReadWithAPIKey{} + return &this +} + +// GetKey returns the Key field value +func (o *OrganizationReadWithAPIKey) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *OrganizationReadWithAPIKey) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *OrganizationReadWithAPIKey) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *OrganizationReadWithAPIKey) SetId(v string) { + o.Id = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *OrganizationReadWithAPIKey) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *OrganizationReadWithAPIKey) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *OrganizationReadWithAPIKey) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *OrganizationReadWithAPIKey) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetName returns the Name field value +func (o *OrganizationReadWithAPIKey) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *OrganizationReadWithAPIKey) SetName(v string) { + o.Name = v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *OrganizationReadWithAPIKey) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *OrganizationReadWithAPIKey) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *OrganizationReadWithAPIKey) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +// GetApiKeyId returns the ApiKeyId field value if set, zero value otherwise. +func (o *OrganizationReadWithAPIKey) GetApiKeyId() string { + if o == nil || IsNil(o.ApiKeyId) { + var ret string + return ret + } + return *o.ApiKeyId +} + +// GetApiKeyIdOk returns a tuple with the ApiKeyId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetApiKeyIdOk() (*string, bool) { + if o == nil || IsNil(o.ApiKeyId) { + return nil, false + } + return o.ApiKeyId, true +} + +// HasApiKeyId returns a boolean if a field has been set. +func (o *OrganizationReadWithAPIKey) HasApiKeyId() bool { + if o != nil && !IsNil(o.ApiKeyId) { + return true + } + + return false +} + +// SetApiKeyId gets a reference to the given string and assigns it to the ApiKeyId field. +func (o *OrganizationReadWithAPIKey) SetApiKeyId(v string) { + o.ApiKeyId = &v +} + +// GetApiKeySecret returns the ApiKeySecret field value if set, zero value otherwise. +func (o *OrganizationReadWithAPIKey) GetApiKeySecret() string { + if o == nil || IsNil(o.ApiKeySecret) { + var ret string + return ret + } + return *o.ApiKeySecret +} + +// GetApiKeySecretOk returns a tuple with the ApiKeySecret field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationReadWithAPIKey) GetApiKeySecretOk() (*string, bool) { + if o == nil || IsNil(o.ApiKeySecret) { + return nil, false + } + return o.ApiKeySecret, true +} + +// HasApiKeySecret returns a boolean if a field has been set. +func (o *OrganizationReadWithAPIKey) HasApiKeySecret() bool { + if o != nil && !IsNil(o.ApiKeySecret) { + return true + } + + return false +} + +// SetApiKeySecret gets a reference to the given string and assigns it to the ApiKeySecret field. +func (o *OrganizationReadWithAPIKey) SetApiKeySecret(v string) { + o.ApiKeySecret = &v +} + +func (o OrganizationReadWithAPIKey) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + if !IsNil(o.ApiKeyId) { + toSerialize["api_key_id"] = o.ApiKeyId + } + if !IsNil(o.ApiKeySecret) { + toSerialize["api_key_secret"] = o.ApiKeySecret + } + return json.Marshal(toSerialize) +} + +type NullableOrganizationReadWithAPIKey struct { + value *OrganizationReadWithAPIKey + isSet bool +} + +func (v NullableOrganizationReadWithAPIKey) Get() *OrganizationReadWithAPIKey { + return v.value +} + +func (v *NullableOrganizationReadWithAPIKey) Set(val *OrganizationReadWithAPIKey) { + v.value = val + v.isSet = true +} + +func (v NullableOrganizationReadWithAPIKey) IsSet() bool { + return v.isSet +} + +func (v *NullableOrganizationReadWithAPIKey) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrganizationReadWithAPIKey(val *OrganizationReadWithAPIKey) *NullableOrganizationReadWithAPIKey { + return &NullableOrganizationReadWithAPIKey{value: val, isSet: true} +} + +func (v NullableOrganizationReadWithAPIKey) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrganizationReadWithAPIKey) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_update.go new file mode 100644 index 00000000..7f4917a6 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_organization_update.go @@ -0,0 +1,151 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// OrganizationUpdate struct for OrganizationUpdate +type OrganizationUpdate struct { + // The name of the organization, usually it's your company's name. + Name *string `json:"name,omitempty"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` +} + +// NewOrganizationUpdate instantiates a new OrganizationUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOrganizationUpdate() *OrganizationUpdate { + this := OrganizationUpdate{} + return &this +} + +// NewOrganizationUpdateWithDefaults instantiates a new OrganizationUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOrganizationUpdateWithDefaults() *OrganizationUpdate { + this := OrganizationUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *OrganizationUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *OrganizationUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *OrganizationUpdate) SetName(v string) { + o.Name = &v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *OrganizationUpdate) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OrganizationUpdate) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *OrganizationUpdate) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *OrganizationUpdate) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +func (o OrganizationUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + return json.Marshal(toSerialize) +} + +type NullableOrganizationUpdate struct { + value *OrganizationUpdate + isSet bool +} + +func (v NullableOrganizationUpdate) Get() *OrganizationUpdate { + return v.value +} + +func (v *NullableOrganizationUpdate) Set(val *OrganizationUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableOrganizationUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableOrganizationUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOrganizationUpdate(val *OrganizationUpdate) *NullableOrganizationUpdate { + return &NullableOrganizationUpdate{value: val, isSet: true} +} + +func (v NullableOrganizationUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOrganizationUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_api_key_read_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_api_key_read_.go new file mode 100644 index 00000000..c327fc55 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_api_key_read_.go @@ -0,0 +1,175 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PaginatedResultAPIKeyRead struct for PaginatedResultAPIKeyRead +type PaginatedResultAPIKeyRead struct { + Data []APIKeyRead `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultAPIKeyRead instantiates a new PaginatedResultAPIKeyRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultAPIKeyRead(data []APIKeyRead, totalCount int32) *PaginatedResultAPIKeyRead { + this := PaginatedResultAPIKeyRead{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultAPIKeyReadWithDefaults instantiates a new PaginatedResultAPIKeyRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultAPIKeyReadWithDefaults() *PaginatedResultAPIKeyRead { + this := PaginatedResultAPIKeyRead{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultAPIKeyRead) GetData() []APIKeyRead { + if o == nil { + var ret []APIKeyRead + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultAPIKeyRead) GetDataOk() ([]APIKeyRead, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultAPIKeyRead) SetData(v []APIKeyRead) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultAPIKeyRead) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultAPIKeyRead) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultAPIKeyRead) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultAPIKeyRead) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultAPIKeyRead) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultAPIKeyRead) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultAPIKeyRead) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultAPIKeyRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["data"] = o.Data + } + if true { + toSerialize["total_count"] = o.TotalCount + } + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return json.Marshal(toSerialize) +} + +type NullablePaginatedResultAPIKeyRead struct { + value *PaginatedResultAPIKeyRead + isSet bool +} + +func (v NullablePaginatedResultAPIKeyRead) Get() *PaginatedResultAPIKeyRead { + return v.value +} + +func (v *NullablePaginatedResultAPIKeyRead) Set(val *PaginatedResultAPIKeyRead) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultAPIKeyRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultAPIKeyRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultAPIKeyRead(val *PaginatedResultAPIKeyRead) *NullablePaginatedResultAPIKeyRead { + return &NullablePaginatedResultAPIKeyRead{value: val, isSet: true} +} + +func (v NullablePaginatedResultAPIKeyRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultAPIKeyRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_condition_set_read_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_condition_set_read_.go new file mode 100644 index 00000000..c6ed5256 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_condition_set_read_.go @@ -0,0 +1,183 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the PaginatedResultConditionSetRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PaginatedResultConditionSetRead{} + +// PaginatedResultConditionSetRead struct for PaginatedResultConditionSetRead +type PaginatedResultConditionSetRead struct { + // List of Condition Sets + Data []ConditionSetRead `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultConditionSetRead instantiates a new PaginatedResultConditionSetRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultConditionSetRead(data []ConditionSetRead, totalCount int32) *PaginatedResultConditionSetRead { + this := PaginatedResultConditionSetRead{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultConditionSetReadWithDefaults instantiates a new PaginatedResultConditionSetRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultConditionSetReadWithDefaults() *PaginatedResultConditionSetRead { + this := PaginatedResultConditionSetRead{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultConditionSetRead) GetData() []ConditionSetRead { + if o == nil { + var ret []ConditionSetRead + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultConditionSetRead) GetDataOk() ([]ConditionSetRead, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultConditionSetRead) SetData(v []ConditionSetRead) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultConditionSetRead) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultConditionSetRead) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultConditionSetRead) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultConditionSetRead) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultConditionSetRead) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultConditionSetRead) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultConditionSetRead) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultConditionSetRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PaginatedResultConditionSetRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["data"] = o.Data + toSerialize["total_count"] = o.TotalCount + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return toSerialize, nil +} + +type NullablePaginatedResultConditionSetRead struct { + value *PaginatedResultConditionSetRead + isSet bool +} + +func (v NullablePaginatedResultConditionSetRead) Get() *PaginatedResultConditionSetRead { + return v.value +} + +func (v *NullablePaginatedResultConditionSetRead) Set(val *PaginatedResultConditionSetRead) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultConditionSetRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultConditionSetRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultConditionSetRead(val *PaginatedResultConditionSetRead) *NullablePaginatedResultConditionSetRead { + return &NullablePaginatedResultConditionSetRead{value: val, isSet: true} +} + +func (v NullablePaginatedResultConditionSetRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultConditionSetRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_elements_config_read_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_elements_config_read_.go new file mode 100644 index 00000000..b7c6c567 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_elements_config_read_.go @@ -0,0 +1,175 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PaginatedResultElementsConfigRead struct for PaginatedResultElementsConfigRead +type PaginatedResultElementsConfigRead struct { + Data []ElementsConfigRead `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultElementsConfigRead instantiates a new PaginatedResultElementsConfigRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultElementsConfigRead(data []ElementsConfigRead, totalCount int32) *PaginatedResultElementsConfigRead { + this := PaginatedResultElementsConfigRead{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultElementsConfigReadWithDefaults instantiates a new PaginatedResultElementsConfigRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultElementsConfigReadWithDefaults() *PaginatedResultElementsConfigRead { + this := PaginatedResultElementsConfigRead{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultElementsConfigRead) GetData() []ElementsConfigRead { + if o == nil { + var ret []ElementsConfigRead + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultElementsConfigRead) GetDataOk() ([]ElementsConfigRead, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultElementsConfigRead) SetData(v []ElementsConfigRead) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultElementsConfigRead) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultElementsConfigRead) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultElementsConfigRead) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultElementsConfigRead) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultElementsConfigRead) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultElementsConfigRead) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultElementsConfigRead) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultElementsConfigRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["data"] = o.Data + } + if true { + toSerialize["total_count"] = o.TotalCount + } + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return json.Marshal(toSerialize) +} + +type NullablePaginatedResultElementsConfigRead struct { + value *PaginatedResultElementsConfigRead + isSet bool +} + +func (v NullablePaginatedResultElementsConfigRead) Get() *PaginatedResultElementsConfigRead { + return v.value +} + +func (v *NullablePaginatedResultElementsConfigRead) Set(val *PaginatedResultElementsConfigRead) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultElementsConfigRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultElementsConfigRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultElementsConfigRead(val *PaginatedResultElementsConfigRead) *NullablePaginatedResultElementsConfigRead { + return &NullablePaginatedResultElementsConfigRead{value: val, isSet: true} +} + +func (v NullablePaginatedResultElementsConfigRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultElementsConfigRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_opa_decision_log_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_opa_decision_log_.go new file mode 100644 index 00000000..26229cbc --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_opa_decision_log_.go @@ -0,0 +1,175 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PaginatedResultOPADecisionLog struct for PaginatedResultOPADecisionLog +type PaginatedResultOPADecisionLog struct { + Data []OPADecisionLog `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultOPADecisionLog instantiates a new PaginatedResultOPADecisionLog object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultOPADecisionLog(data []OPADecisionLog, totalCount int32) *PaginatedResultOPADecisionLog { + this := PaginatedResultOPADecisionLog{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultOPADecisionLogWithDefaults instantiates a new PaginatedResultOPADecisionLog object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultOPADecisionLogWithDefaults() *PaginatedResultOPADecisionLog { + this := PaginatedResultOPADecisionLog{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultOPADecisionLog) GetData() []OPADecisionLog { + if o == nil { + var ret []OPADecisionLog + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultOPADecisionLog) GetDataOk() ([]OPADecisionLog, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultOPADecisionLog) SetData(v []OPADecisionLog) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultOPADecisionLog) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultOPADecisionLog) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultOPADecisionLog) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultOPADecisionLog) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultOPADecisionLog) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultOPADecisionLog) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultOPADecisionLog) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultOPADecisionLog) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["data"] = o.Data + } + if true { + toSerialize["total_count"] = o.TotalCount + } + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return json.Marshal(toSerialize) +} + +type NullablePaginatedResultOPADecisionLog struct { + value *PaginatedResultOPADecisionLog + isSet bool +} + +func (v NullablePaginatedResultOPADecisionLog) Get() *PaginatedResultOPADecisionLog { + return v.value +} + +func (v *NullablePaginatedResultOPADecisionLog) Set(val *PaginatedResultOPADecisionLog) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultOPADecisionLog) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultOPADecisionLog) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultOPADecisionLog(val *PaginatedResultOPADecisionLog) *NullablePaginatedResultOPADecisionLog { + return &NullablePaginatedResultOPADecisionLog{value: val, isSet: true} +} + +func (v NullablePaginatedResultOPADecisionLog) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultOPADecisionLog) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_relation_read_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_relation_read_.go new file mode 100644 index 00000000..75ed55b4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_relation_read_.go @@ -0,0 +1,183 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the PaginatedResultRelationRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PaginatedResultRelationRead{} + +// PaginatedResultRelationRead struct for PaginatedResultRelationRead +type PaginatedResultRelationRead struct { + // List of Relations + Data []RelationRead `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultRelationRead instantiates a new PaginatedResultRelationRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultRelationRead(data []RelationRead, totalCount int32) *PaginatedResultRelationRead { + this := PaginatedResultRelationRead{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultRelationReadWithDefaults instantiates a new PaginatedResultRelationRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultRelationReadWithDefaults() *PaginatedResultRelationRead { + this := PaginatedResultRelationRead{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultRelationRead) GetData() []RelationRead { + if o == nil { + var ret []RelationRead + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultRelationRead) GetDataOk() ([]RelationRead, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultRelationRead) SetData(v []RelationRead) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultRelationRead) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultRelationRead) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultRelationRead) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultRelationRead) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultRelationRead) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultRelationRead) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultRelationRead) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultRelationRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PaginatedResultRelationRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["data"] = o.Data + toSerialize["total_count"] = o.TotalCount + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return toSerialize, nil +} + +type NullablePaginatedResultRelationRead struct { + value *PaginatedResultRelationRead + isSet bool +} + +func (v NullablePaginatedResultRelationRead) Get() *PaginatedResultRelationRead { + return v.value +} + +func (v *NullablePaginatedResultRelationRead) Set(val *PaginatedResultRelationRead) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultRelationRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultRelationRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultRelationRead(val *PaginatedResultRelationRead) *NullablePaginatedResultRelationRead { + return &NullablePaginatedResultRelationRead{value: val, isSet: true} +} + +func (v NullablePaginatedResultRelationRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultRelationRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_resource_role_read_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_resource_role_read_.go new file mode 100644 index 00000000..0404c3ca --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_resource_role_read_.go @@ -0,0 +1,183 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the PaginatedResultResourceRoleRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PaginatedResultResourceRoleRead{} + +// PaginatedResultResourceRoleRead struct for PaginatedResultResourceRoleRead +type PaginatedResultResourceRoleRead struct { + // List of Resource Roles + Data []ResourceRoleRead `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultResourceRoleRead instantiates a new PaginatedResultResourceRoleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultResourceRoleRead(data []ResourceRoleRead, totalCount int32) *PaginatedResultResourceRoleRead { + this := PaginatedResultResourceRoleRead{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultResourceRoleReadWithDefaults instantiates a new PaginatedResultResourceRoleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultResourceRoleReadWithDefaults() *PaginatedResultResourceRoleRead { + this := PaginatedResultResourceRoleRead{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultResourceRoleRead) GetData() []ResourceRoleRead { + if o == nil { + var ret []ResourceRoleRead + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultResourceRoleRead) GetDataOk() ([]ResourceRoleRead, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultResourceRoleRead) SetData(v []ResourceRoleRead) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultResourceRoleRead) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultResourceRoleRead) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultResourceRoleRead) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultResourceRoleRead) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultResourceRoleRead) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultResourceRoleRead) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultResourceRoleRead) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultResourceRoleRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PaginatedResultResourceRoleRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["data"] = o.Data + toSerialize["total_count"] = o.TotalCount + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return toSerialize, nil +} + +type NullablePaginatedResultResourceRoleRead struct { + value *PaginatedResultResourceRoleRead + isSet bool +} + +func (v NullablePaginatedResultResourceRoleRead) Get() *PaginatedResultResourceRoleRead { + return v.value +} + +func (v *NullablePaginatedResultResourceRoleRead) Set(val *PaginatedResultResourceRoleRead) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultResourceRoleRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultResourceRoleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultResourceRoleRead(val *PaginatedResultResourceRoleRead) *NullablePaginatedResultResourceRoleRead { + return &NullablePaginatedResultResourceRoleRead{value: val, isSet: true} +} + +func (v NullablePaginatedResultResourceRoleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultResourceRoleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_user_read_.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_user_read_.go new file mode 100644 index 00000000..3597d294 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_paginated_result_user_read_.go @@ -0,0 +1,175 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PaginatedResultUserRead struct for PaginatedResultUserRead +type PaginatedResultUserRead struct { + Data []UserRead `json:"data"` + TotalCount int32 `json:"total_count"` + PageCount *int32 `json:"page_count,omitempty"` +} + +// NewPaginatedResultUserRead instantiates a new PaginatedResultUserRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPaginatedResultUserRead(data []UserRead, totalCount int32) *PaginatedResultUserRead { + this := PaginatedResultUserRead{} + this.Data = data + this.TotalCount = totalCount + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// NewPaginatedResultUserReadWithDefaults instantiates a new PaginatedResultUserRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPaginatedResultUserReadWithDefaults() *PaginatedResultUserRead { + this := PaginatedResultUserRead{} + var pageCount int32 = 0 + this.PageCount = &pageCount + return &this +} + +// GetData returns the Data field value +func (o *PaginatedResultUserRead) GetData() []UserRead { + if o == nil { + var ret []UserRead + return ret + } + + return o.Data +} + +// GetDataOk returns a tuple with the Data field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultUserRead) GetDataOk() ([]UserRead, bool) { + if o == nil { + return nil, false + } + return o.Data, true +} + +// SetData sets field value +func (o *PaginatedResultUserRead) SetData(v []UserRead) { + o.Data = v +} + +// GetTotalCount returns the TotalCount field value +func (o *PaginatedResultUserRead) GetTotalCount() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.TotalCount +} + +// GetTotalCountOk returns a tuple with the TotalCount field value +// and a boolean to check if the value has been set. +func (o *PaginatedResultUserRead) GetTotalCountOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.TotalCount, true +} + +// SetTotalCount sets field value +func (o *PaginatedResultUserRead) SetTotalCount(v int32) { + o.TotalCount = v +} + +// GetPageCount returns the PageCount field value if set, zero value otherwise. +func (o *PaginatedResultUserRead) GetPageCount() int32 { + if o == nil || IsNil(o.PageCount) { + var ret int32 + return ret + } + return *o.PageCount +} + +// GetPageCountOk returns a tuple with the PageCount field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PaginatedResultUserRead) GetPageCountOk() (*int32, bool) { + if o == nil || IsNil(o.PageCount) { + return nil, false + } + return o.PageCount, true +} + +// HasPageCount returns a boolean if a field has been set. +func (o *PaginatedResultUserRead) HasPageCount() bool { + if o != nil && !IsNil(o.PageCount) { + return true + } + + return false +} + +// SetPageCount gets a reference to the given int32 and assigns it to the PageCount field. +func (o *PaginatedResultUserRead) SetPageCount(v int32) { + o.PageCount = &v +} + +func (o PaginatedResultUserRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["data"] = o.Data + } + if true { + toSerialize["total_count"] = o.TotalCount + } + if !IsNil(o.PageCount) { + toSerialize["page_count"] = o.PageCount + } + return json.Marshal(toSerialize) +} + +type NullablePaginatedResultUserRead struct { + value *PaginatedResultUserRead + isSet bool +} + +func (v NullablePaginatedResultUserRead) Get() *PaginatedResultUserRead { + return v.value +} + +func (v *NullablePaginatedResultUserRead) Set(val *PaginatedResultUserRead) { + v.value = val + v.isSet = true +} + +func (v NullablePaginatedResultUserRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePaginatedResultUserRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePaginatedResultUserRead(val *PaginatedResultUserRead) *NullablePaginatedResultUserRead { + return &NullablePaginatedResultUserRead{value: val, isSet: true} +} + +func (v NullablePaginatedResultUserRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePaginatedResultUserRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_parent_id.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_parent_id.go new file mode 100644 index 00000000..62189b40 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_parent_id.go @@ -0,0 +1,85 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ParentId Parent Condition Set +type ParentId struct { + string *string +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *ParentId) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into string + err = json.Unmarshal(data, &dst.string) + if err == nil { + jsonstring, _ := json.Marshal(dst.string) + if string(jsonstring) == "{}" { // empty struct + dst.string = nil + } else { + return nil // data stored in dst.string, return on the first match + } + } else { + dst.string = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(ParentId)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *ParentId) MarshalJSON() ([]byte, error) { + if src.string != nil { + return json.Marshal(&src.string) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableParentId struct { + value *ParentId + isSet bool +} + +func (v NullableParentId) Get() *ParentId { + return v.value +} + +func (v *NullableParentId) Set(val *ParentId) { + v.value = val + v.isSet = true +} + +func (v NullableParentId) IsSet() bool { + return v.isSet +} + +func (v *NullableParentId) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableParentId(val *ParentId) *NullableParentId { + return &NullableParentId{value: val, isSet: true} +} + +func (v NullableParentId) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableParentId) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp.go new file mode 100644 index 00000000..7026fd56 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp.go @@ -0,0 +1,164 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// Pdp struct for Pdp +type Pdp struct { + BACKEND_SERVICE_URL string `json:"BACKEND_SERVICE_URL"` + OPA_DECISION_LOG_INGRESS_ROUTE string `json:"OPA_DECISION_LOG_INGRESS_ROUTE"` + OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL string `json:"OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL"` +} + +// NewPdp instantiates a new Pdp object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPdp(bACKENDSERVICEURL string, oPADECISIONLOGINGRESSROUTE string, oPADECISIONLOGINGRESSBACKENDTIERURL string) *Pdp { + this := Pdp{} + this.BACKEND_SERVICE_URL = bACKENDSERVICEURL + this.OPA_DECISION_LOG_INGRESS_ROUTE = oPADECISIONLOGINGRESSROUTE + this.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL = oPADECISIONLOGINGRESSBACKENDTIERURL + return &this +} + +// NewPdpWithDefaults instantiates a new Pdp object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPdpWithDefaults() *Pdp { + this := Pdp{} + return &this +} + +// GetBACKEND_SERVICE_URL returns the BACKEND_SERVICE_URL field value +func (o *Pdp) GetBACKEND_SERVICE_URL() string { + if o == nil { + var ret string + return ret + } + + return o.BACKEND_SERVICE_URL +} + +// GetBACKEND_SERVICE_URLOk returns a tuple with the BACKEND_SERVICE_URL field value +// and a boolean to check if the value has been set. +func (o *Pdp) GetBACKEND_SERVICE_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.BACKEND_SERVICE_URL, true +} + +// SetBACKEND_SERVICE_URL sets field value +func (o *Pdp) SetBACKEND_SERVICE_URL(v string) { + o.BACKEND_SERVICE_URL = v +} + +// GetOPA_DECISION_LOG_INGRESS_ROUTE returns the OPA_DECISION_LOG_INGRESS_ROUTE field value +func (o *Pdp) GetOPA_DECISION_LOG_INGRESS_ROUTE() string { + if o == nil { + var ret string + return ret + } + + return o.OPA_DECISION_LOG_INGRESS_ROUTE +} + +// GetOPA_DECISION_LOG_INGRESS_ROUTEOk returns a tuple with the OPA_DECISION_LOG_INGRESS_ROUTE field value +// and a boolean to check if the value has been set. +func (o *Pdp) GetOPA_DECISION_LOG_INGRESS_ROUTEOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OPA_DECISION_LOG_INGRESS_ROUTE, true +} + +// SetOPA_DECISION_LOG_INGRESS_ROUTE sets field value +func (o *Pdp) SetOPA_DECISION_LOG_INGRESS_ROUTE(v string) { + o.OPA_DECISION_LOG_INGRESS_ROUTE = v +} + +// GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL returns the OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL field value +func (o *Pdp) GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL() string { + if o == nil { + var ret string + return ret + } + + return o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL +} + +// GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URLOk returns a tuple with the OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL field value +// and a boolean to check if the value has been set. +func (o *Pdp) GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL, true +} + +// SetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL sets field value +func (o *Pdp) SetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL(v string) { + o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL = v +} + +func (o Pdp) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["BACKEND_SERVICE_URL"] = o.BACKEND_SERVICE_URL + } + if true { + toSerialize["OPA_DECISION_LOG_INGRESS_ROUTE"] = o.OPA_DECISION_LOG_INGRESS_ROUTE + } + if true { + toSerialize["OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL"] = o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL + } + return json.Marshal(toSerialize) +} + +type NullablePdp struct { + value *Pdp + isSet bool +} + +func (v NullablePdp) Get() *Pdp { + return v.value +} + +func (v *NullablePdp) Set(val *Pdp) { + v.value = val + v.isSet = true +} + +func (v NullablePdp) IsSet() bool { + return v.isSet +} + +func (v *NullablePdp) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePdp(val *Pdp) *NullablePdp { + return &NullablePdp{value: val, isSet: true} +} + +func (v NullablePdp) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePdp) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_config_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_config_read.go new file mode 100644 index 00000000..201a0c61 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_config_read.go @@ -0,0 +1,261 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PDPConfigRead struct for PDPConfigRead +type PDPConfigRead struct { + Id string `json:"id"` + Name *string `json:"name,omitempty"` + // Unique id of the organization that the pdp_config belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the pdp_config belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the pdp_config belongs to. + EnvironmentId string `json:"environment_id"` + ClientSecret string `json:"client_secret"` +} + +// NewPDPConfigRead instantiates a new PDPConfigRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPDPConfigRead(id string, organizationId string, projectId string, environmentId string, clientSecret string) *PDPConfigRead { + this := PDPConfigRead{} + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.ClientSecret = clientSecret + return &this +} + +// NewPDPConfigReadWithDefaults instantiates a new PDPConfigRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPDPConfigReadWithDefaults() *PDPConfigRead { + this := PDPConfigRead{} + return &this +} + +// GetId returns the Id field value +func (o *PDPConfigRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *PDPConfigRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *PDPConfigRead) SetId(v string) { + o.Id = v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *PDPConfigRead) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PDPConfigRead) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *PDPConfigRead) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *PDPConfigRead) SetName(v string) { + o.Name = &v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *PDPConfigRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *PDPConfigRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *PDPConfigRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *PDPConfigRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *PDPConfigRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *PDPConfigRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *PDPConfigRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *PDPConfigRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *PDPConfigRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetClientSecret returns the ClientSecret field value +func (o *PDPConfigRead) GetClientSecret() string { + if o == nil { + var ret string + return ret + } + + return o.ClientSecret +} + +// GetClientSecretOk returns a tuple with the ClientSecret field value +// and a boolean to check if the value has been set. +func (o *PDPConfigRead) GetClientSecretOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ClientSecret, true +} + +// SetClientSecret sets field value +func (o *PDPConfigRead) SetClientSecret(v string) { + o.ClientSecret = v +} + +func (o PDPConfigRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["client_secret"] = o.ClientSecret + } + return json.Marshal(toSerialize) +} + +type NullablePDPConfigRead struct { + value *PDPConfigRead + isSet bool +} + +func (v NullablePDPConfigRead) Get() *PDPConfigRead { + return v.value +} + +func (v *NullablePDPConfigRead) Set(val *PDPConfigRead) { + v.value = val + v.isSet = true +} + +func (v NullablePDPConfigRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePDPConfigRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePDPConfigRead(val *PDPConfigRead) *NullablePDPConfigRead { + return &NullablePDPConfigRead{value: val, isSet: true} +} + +func (v NullablePDPConfigRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePDPConfigRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_context.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_context.go new file mode 100644 index 00000000..ca4db465 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_context.go @@ -0,0 +1,204 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PDPContext struct for PDPContext +type PDPContext struct { + CustomerId string `json:"customer_id"` + ClientId string `json:"client_id"` + BackendTier string `json:"backend_tier"` + Component *string `json:"component,omitempty"` +} + +// NewPDPContext instantiates a new PDPContext object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPDPContext(customerId string, clientId string, backendTier string) *PDPContext { + this := PDPContext{} + this.CustomerId = customerId + this.ClientId = clientId + this.BackendTier = backendTier + var component string = "sidecar" + this.Component = &component + return &this +} + +// NewPDPContextWithDefaults instantiates a new PDPContext object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPDPContextWithDefaults() *PDPContext { + this := PDPContext{} + var component string = "sidecar" + this.Component = &component + return &this +} + +// GetCustomerId returns the CustomerId field value +func (o *PDPContext) GetCustomerId() string { + if o == nil { + var ret string + return ret + } + + return o.CustomerId +} + +// GetCustomerIdOk returns a tuple with the CustomerId field value +// and a boolean to check if the value has been set. +func (o *PDPContext) GetCustomerIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.CustomerId, true +} + +// SetCustomerId sets field value +func (o *PDPContext) SetCustomerId(v string) { + o.CustomerId = v +} + +// GetClientId returns the ClientId field value +func (o *PDPContext) GetClientId() string { + if o == nil { + var ret string + return ret + } + + return o.ClientId +} + +// GetClientIdOk returns a tuple with the ClientId field value +// and a boolean to check if the value has been set. +func (o *PDPContext) GetClientIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ClientId, true +} + +// SetClientId sets field value +func (o *PDPContext) SetClientId(v string) { + o.ClientId = v +} + +// GetBackendTier returns the BackendTier field value +func (o *PDPContext) GetBackendTier() string { + if o == nil { + var ret string + return ret + } + + return o.BackendTier +} + +// GetBackendTierOk returns a tuple with the BackendTier field value +// and a boolean to check if the value has been set. +func (o *PDPContext) GetBackendTierOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.BackendTier, true +} + +// SetBackendTier sets field value +func (o *PDPContext) SetBackendTier(v string) { + o.BackendTier = v +} + +// GetComponent returns the Component field value if set, zero value otherwise. +func (o *PDPContext) GetComponent() string { + if o == nil || IsNil(o.Component) { + var ret string + return ret + } + return *o.Component +} + +// GetComponentOk returns a tuple with the Component field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PDPContext) GetComponentOk() (*string, bool) { + if o == nil || IsNil(o.Component) { + return nil, false + } + return o.Component, true +} + +// HasComponent returns a boolean if a field has been set. +func (o *PDPContext) HasComponent() bool { + if o != nil && !IsNil(o.Component) { + return true + } + + return false +} + +// SetComponent gets a reference to the given string and assigns it to the Component field. +func (o *PDPContext) SetComponent(v string) { + o.Component = &v +} + +func (o PDPContext) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["customer_id"] = o.CustomerId + } + if true { + toSerialize["client_id"] = o.ClientId + } + if true { + toSerialize["backend_tier"] = o.BackendTier + } + if !IsNil(o.Component) { + toSerialize["component"] = o.Component + } + return json.Marshal(toSerialize) +} + +type NullablePDPContext struct { + value *PDPContext + isSet bool +} + +func (v NullablePDPContext) Get() *PDPContext { + return v.value +} + +func (v *NullablePDPContext) Set(val *PDPContext) { + v.value = val + v.isSet = true +} + +func (v NullablePDPContext) IsSet() bool { + return v.isSet +} + +func (v *NullablePDPContext) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePDPContext(val *PDPContext) *NullablePDPContext { + return &NullablePDPContext{value: val, isSet: true} +} + +func (v NullablePDPContext) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePDPContext) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state.go new file mode 100644 index 00000000..9faea18a --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state.go @@ -0,0 +1,106 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PDPState struct for PDPState +type PDPState struct { + ApiVersion int32 `json:"api_version"` +} + +// NewPDPState instantiates a new PDPState object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPDPState(apiVersion int32) *PDPState { + this := PDPState{} + this.ApiVersion = apiVersion + return &this +} + +// NewPDPStateWithDefaults instantiates a new PDPState object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPDPStateWithDefaults() *PDPState { + this := PDPState{} + return &this +} + +// GetApiVersion returns the ApiVersion field value +func (o *PDPState) GetApiVersion() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.ApiVersion +} + +// GetApiVersionOk returns a tuple with the ApiVersion field value +// and a boolean to check if the value has been set. +func (o *PDPState) GetApiVersionOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.ApiVersion, true +} + +// SetApiVersion sets field value +func (o *PDPState) SetApiVersion(v int32) { + o.ApiVersion = v +} + +func (o PDPState) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["api_version"] = o.ApiVersion + } + return json.Marshal(toSerialize) +} + +type NullablePDPState struct { + value *PDPState + isSet bool +} + +func (v NullablePDPState) Get() *PDPState { + return v.value +} + +func (v *NullablePDPState) Set(val *PDPState) { + v.value = val + v.isSet = true +} + +func (v NullablePDPState) IsSet() bool { + return v.isSet +} + +func (v *NullablePDPState) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePDPState(val *PDPState) *NullablePDPState { + return &NullablePDPState{value: val, isSet: true} +} + +func (v NullablePDPState) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePDPState) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state_update.go new file mode 100644 index 00000000..2fd32837 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_state_update.go @@ -0,0 +1,135 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PDPStateUpdate struct for PDPStateUpdate +type PDPStateUpdate struct { + PdpInstanceId string `json:"pdp_instance_id"` + State PDPState `json:"state"` +} + +// NewPDPStateUpdate instantiates a new PDPStateUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPDPStateUpdate(pdpInstanceId string, state PDPState) *PDPStateUpdate { + this := PDPStateUpdate{} + this.PdpInstanceId = pdpInstanceId + this.State = state + return &this +} + +// NewPDPStateUpdateWithDefaults instantiates a new PDPStateUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPDPStateUpdateWithDefaults() *PDPStateUpdate { + this := PDPStateUpdate{} + return &this +} + +// GetPdpInstanceId returns the PdpInstanceId field value +func (o *PDPStateUpdate) GetPdpInstanceId() string { + if o == nil { + var ret string + return ret + } + + return o.PdpInstanceId +} + +// GetPdpInstanceIdOk returns a tuple with the PdpInstanceId field value +// and a boolean to check if the value has been set. +func (o *PDPStateUpdate) GetPdpInstanceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PdpInstanceId, true +} + +// SetPdpInstanceId sets field value +func (o *PDPStateUpdate) SetPdpInstanceId(v string) { + o.PdpInstanceId = v +} + +// GetState returns the State field value +func (o *PDPStateUpdate) GetState() PDPState { + if o == nil { + var ret PDPState + return ret + } + + return o.State +} + +// GetStateOk returns a tuple with the State field value +// and a boolean to check if the value has been set. +func (o *PDPStateUpdate) GetStateOk() (*PDPState, bool) { + if o == nil { + return nil, false + } + return &o.State, true +} + +// SetState sets field value +func (o *PDPStateUpdate) SetState(v PDPState) { + o.State = v +} + +func (o PDPStateUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["pdp_instance_id"] = o.PdpInstanceId + } + if true { + toSerialize["state"] = o.State + } + return json.Marshal(toSerialize) +} + +type NullablePDPStateUpdate struct { + value *PDPStateUpdate + isSet bool +} + +func (v NullablePDPStateUpdate) Get() *PDPStateUpdate { + return v.value +} + +func (v *NullablePDPStateUpdate) Set(val *PDPStateUpdate) { + v.value = val + v.isSet = true +} + +func (v NullablePDPStateUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullablePDPStateUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePDPStateUpdate(val *PDPStateUpdate) *NullablePDPStateUpdate { + return &NullablePDPStateUpdate{value: val, isSet: true} +} + +func (v NullablePDPStateUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePDPStateUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_values.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_values.go new file mode 100644 index 00000000..50729c21 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_pdp_values.go @@ -0,0 +1,164 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PdpValues struct for PdpValues +type PdpValues struct { + BACKEND_SERVICE_URL string `json:"BACKEND_SERVICE_URL"` + OPA_DECISION_LOG_INGRESS_ROUTE string `json:"OPA_DECISION_LOG_INGRESS_ROUTE"` + OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL string `json:"OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL"` +} + +// NewPdpValues instantiates a new PdpValues object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPdpValues(bACKENDSERVICEURL string, oPADECISIONLOGINGRESSROUTE string, oPADECISIONLOGINGRESSBACKENDTIERURL string) *PdpValues { + this := PdpValues{} + this.BACKEND_SERVICE_URL = bACKENDSERVICEURL + this.OPA_DECISION_LOG_INGRESS_ROUTE = oPADECISIONLOGINGRESSROUTE + this.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL = oPADECISIONLOGINGRESSBACKENDTIERURL + return &this +} + +// NewPdpValuesWithDefaults instantiates a new PdpValues object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPdpValuesWithDefaults() *PdpValues { + this := PdpValues{} + return &this +} + +// GetBACKEND_SERVICE_URL returns the BACKEND_SERVICE_URL field value +func (o *PdpValues) GetBACKEND_SERVICE_URL() string { + if o == nil { + var ret string + return ret + } + + return o.BACKEND_SERVICE_URL +} + +// GetBACKEND_SERVICE_URLOk returns a tuple with the BACKEND_SERVICE_URL field value +// and a boolean to check if the value has been set. +func (o *PdpValues) GetBACKEND_SERVICE_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.BACKEND_SERVICE_URL, true +} + +// SetBACKEND_SERVICE_URL sets field value +func (o *PdpValues) SetBACKEND_SERVICE_URL(v string) { + o.BACKEND_SERVICE_URL = v +} + +// GetOPA_DECISION_LOG_INGRESS_ROUTE returns the OPA_DECISION_LOG_INGRESS_ROUTE field value +func (o *PdpValues) GetOPA_DECISION_LOG_INGRESS_ROUTE() string { + if o == nil { + var ret string + return ret + } + + return o.OPA_DECISION_LOG_INGRESS_ROUTE +} + +// GetOPA_DECISION_LOG_INGRESS_ROUTEOk returns a tuple with the OPA_DECISION_LOG_INGRESS_ROUTE field value +// and a boolean to check if the value has been set. +func (o *PdpValues) GetOPA_DECISION_LOG_INGRESS_ROUTEOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OPA_DECISION_LOG_INGRESS_ROUTE, true +} + +// SetOPA_DECISION_LOG_INGRESS_ROUTE sets field value +func (o *PdpValues) SetOPA_DECISION_LOG_INGRESS_ROUTE(v string) { + o.OPA_DECISION_LOG_INGRESS_ROUTE = v +} + +// GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL returns the OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL field value +func (o *PdpValues) GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL() string { + if o == nil { + var ret string + return ret + } + + return o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL +} + +// GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URLOk returns a tuple with the OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL field value +// and a boolean to check if the value has been set. +func (o *PdpValues) GetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URLOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL, true +} + +// SetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL sets field value +func (o *PdpValues) SetOPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL(v string) { + o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL = v +} + +func (o PdpValues) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["BACKEND_SERVICE_URL"] = o.BACKEND_SERVICE_URL + } + if true { + toSerialize["OPA_DECISION_LOG_INGRESS_ROUTE"] = o.OPA_DECISION_LOG_INGRESS_ROUTE + } + if true { + toSerialize["OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL"] = o.OPA_DECISION_LOG_INGRESS_BACKEND_TIER_URL + } + return json.Marshal(toSerialize) +} + +type NullablePdpValues struct { + value *PdpValues + isSet bool +} + +func (v NullablePdpValues) Get() *PdpValues { + return v.value +} + +func (v *NullablePdpValues) Set(val *PdpValues) { + v.value = val + v.isSet = true +} + +func (v NullablePdpValues) IsSet() bool { + return v.isSet +} + +func (v *NullablePdpValues) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePdpValues(val *PdpValues) *NullablePdpValues { + return &NullablePdpValues{value: val, isSet: true} +} + +func (v NullablePdpValues) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePdpValues) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_permission_level_role_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_permission_level_role_read.go new file mode 100644 index 00000000..a8eb3f4e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_permission_level_role_read.go @@ -0,0 +1,166 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PermissionLevelRoleRead struct for PermissionLevelRoleRead +type PermissionLevelRoleRead struct { + // Unique id of the elements_env + Id string `json:"id"` + // A URL-friendly name of the elements_env (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the elements_env. + Key string `json:"key"` + Name string `json:"name"` +} + +// NewPermissionLevelRoleRead instantiates a new PermissionLevelRoleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPermissionLevelRoleRead(id string, key string, name string) *PermissionLevelRoleRead { + this := PermissionLevelRoleRead{} + this.Id = id + this.Key = key + this.Name = name + return &this +} + +// NewPermissionLevelRoleReadWithDefaults instantiates a new PermissionLevelRoleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPermissionLevelRoleReadWithDefaults() *PermissionLevelRoleRead { + this := PermissionLevelRoleRead{} + return &this +} + +// GetId returns the Id field value +func (o *PermissionLevelRoleRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *PermissionLevelRoleRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *PermissionLevelRoleRead) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *PermissionLevelRoleRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *PermissionLevelRoleRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *PermissionLevelRoleRead) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *PermissionLevelRoleRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *PermissionLevelRoleRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *PermissionLevelRoleRead) SetName(v string) { + o.Name = v +} + +func (o PermissionLevelRoleRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) +} + +type NullablePermissionLevelRoleRead struct { + value *PermissionLevelRoleRead + isSet bool +} + +func (v NullablePermissionLevelRoleRead) Get() *PermissionLevelRoleRead { + return v.value +} + +func (v *NullablePermissionLevelRoleRead) Set(val *PermissionLevelRoleRead) { + v.value = val + v.isSet = true +} + +func (v NullablePermissionLevelRoleRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePermissionLevelRoleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePermissionLevelRoleRead(val *PermissionLevelRoleRead) *NullablePermissionLevelRoleRead { + return &NullablePermissionLevelRoleRead{value: val, isSet: true} +} + +func (v NullablePermissionLevelRoleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePermissionLevelRoleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_derived_role_rule__derivation_settings.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_derived_role_rule__derivation_settings.go new file mode 100644 index 00000000..33b35941 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_derived_role_rule__derivation_settings.go @@ -0,0 +1,129 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{} + +// PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings Settings for a derived role or a derived role rule +type PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings struct { + // If true, the derived role or the specific rule will not apply if the resource has any direct role + NoDirectRolesOnObject *bool `json:"no_direct_roles_on_object,omitempty"` +} + +// NewPermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings instantiates a new PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings() *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + this := PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{} + var noDirectRolesOnObject bool = false + this.NoDirectRolesOnObject = &noDirectRolesOnObject + return &this +} + +// NewPermitBackendSchemasSchemaDerivedRoleRuleDerivationSettingsWithDefaults instantiates a new PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPermitBackendSchemasSchemaDerivedRoleRuleDerivationSettingsWithDefaults() *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + this := PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{} + var noDirectRolesOnObject bool = false + this.NoDirectRolesOnObject = &noDirectRolesOnObject + return &this +} + +// GetNoDirectRolesOnObject returns the NoDirectRolesOnObject field value if set, zero value otherwise. +func (o *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) GetNoDirectRolesOnObject() bool { + if o == nil || IsNil(o.NoDirectRolesOnObject) { + var ret bool + return ret + } + return *o.NoDirectRolesOnObject +} + +// GetNoDirectRolesOnObjectOk returns a tuple with the NoDirectRolesOnObject field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) GetNoDirectRolesOnObjectOk() (*bool, bool) { + if o == nil || IsNil(o.NoDirectRolesOnObject) { + return nil, false + } + return o.NoDirectRolesOnObject, true +} + +// HasNoDirectRolesOnObject returns a boolean if a field has been set. +func (o *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) HasNoDirectRolesOnObject() bool { + if o != nil && !IsNil(o.NoDirectRolesOnObject) { + return true + } + + return false +} + +// SetNoDirectRolesOnObject gets a reference to the given bool and assigns it to the NoDirectRolesOnObject field. +func (o *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) SetNoDirectRolesOnObject(v bool) { + o.NoDirectRolesOnObject = &v +} + +func (o PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.NoDirectRolesOnObject) { + toSerialize["no_direct_roles_on_object"] = o.NoDirectRolesOnObject + } + return toSerialize, nil +} + +type NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings struct { + value *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + isSet bool +} + +func (v NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) Get() *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + return v.value +} + +func (v *NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) Set(val *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) { + v.value = val + v.isSet = true +} + +func (v NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) IsSet() bool { + return v.isSet +} + +func (v *NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings(val *PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) *NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings { + return &NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings{value: val, isSet: true} +} + +func (v NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_opal_data__derivation_settings.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_opal_data__derivation_settings.go new file mode 100644 index 00000000..fa29ade0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_permit_backend__schemas__schema_opal_data__derivation_settings.go @@ -0,0 +1,128 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the PermitBackendSchemasSchemaOpalDataDerivationSettings type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PermitBackendSchemasSchemaOpalDataDerivationSettings{} + +// PermitBackendSchemasSchemaOpalDataDerivationSettings struct for PermitBackendSchemasSchemaOpalDataDerivationSettings +type PermitBackendSchemasSchemaOpalDataDerivationSettings struct { + SupersededByDirectRole *bool `json:"superseded_by_direct_role,omitempty"` +} + +// NewPermitBackendSchemasSchemaOpalDataDerivationSettings instantiates a new PermitBackendSchemasSchemaOpalDataDerivationSettings object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPermitBackendSchemasSchemaOpalDataDerivationSettings() *PermitBackendSchemasSchemaOpalDataDerivationSettings { + this := PermitBackendSchemasSchemaOpalDataDerivationSettings{} + var supersededByDirectRole bool = false + this.SupersededByDirectRole = &supersededByDirectRole + return &this +} + +// NewPermitBackendSchemasSchemaOpalDataDerivationSettingsWithDefaults instantiates a new PermitBackendSchemasSchemaOpalDataDerivationSettings object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPermitBackendSchemasSchemaOpalDataDerivationSettingsWithDefaults() *PermitBackendSchemasSchemaOpalDataDerivationSettings { + this := PermitBackendSchemasSchemaOpalDataDerivationSettings{} + var supersededByDirectRole bool = false + this.SupersededByDirectRole = &supersededByDirectRole + return &this +} + +// GetSupersededByDirectRole returns the SupersededByDirectRole field value if set, zero value otherwise. +func (o *PermitBackendSchemasSchemaOpalDataDerivationSettings) GetSupersededByDirectRole() bool { + if o == nil || IsNil(o.SupersededByDirectRole) { + var ret bool + return ret + } + return *o.SupersededByDirectRole +} + +// GetSupersededByDirectRoleOk returns a tuple with the SupersededByDirectRole field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PermitBackendSchemasSchemaOpalDataDerivationSettings) GetSupersededByDirectRoleOk() (*bool, bool) { + if o == nil || IsNil(o.SupersededByDirectRole) { + return nil, false + } + return o.SupersededByDirectRole, true +} + +// HasSupersededByDirectRole returns a boolean if a field has been set. +func (o *PermitBackendSchemasSchemaOpalDataDerivationSettings) HasSupersededByDirectRole() bool { + if o != nil && !IsNil(o.SupersededByDirectRole) { + return true + } + + return false +} + +// SetSupersededByDirectRole gets a reference to the given bool and assigns it to the SupersededByDirectRole field. +func (o *PermitBackendSchemasSchemaOpalDataDerivationSettings) SetSupersededByDirectRole(v bool) { + o.SupersededByDirectRole = &v +} + +func (o PermitBackendSchemasSchemaOpalDataDerivationSettings) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PermitBackendSchemasSchemaOpalDataDerivationSettings) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.SupersededByDirectRole) { + toSerialize["superseded_by_direct_role"] = o.SupersededByDirectRole + } + return toSerialize, nil +} + +type NullablePermitBackendSchemasSchemaOpalDataDerivationSettings struct { + value *PermitBackendSchemasSchemaOpalDataDerivationSettings + isSet bool +} + +func (v NullablePermitBackendSchemasSchemaOpalDataDerivationSettings) Get() *PermitBackendSchemasSchemaOpalDataDerivationSettings { + return v.value +} + +func (v *NullablePermitBackendSchemasSchemaOpalDataDerivationSettings) Set(val *PermitBackendSchemasSchemaOpalDataDerivationSettings) { + v.value = val + v.isSet = true +} + +func (v NullablePermitBackendSchemasSchemaOpalDataDerivationSettings) IsSet() bool { + return v.isSet +} + +func (v *NullablePermitBackendSchemasSchemaOpalDataDerivationSettings) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePermitBackendSchemasSchemaOpalDataDerivationSettings(val *PermitBackendSchemasSchemaOpalDataDerivationSettings) *NullablePermitBackendSchemasSchemaOpalDataDerivationSettings { + return &NullablePermitBackendSchemasSchemaOpalDataDerivationSettings{value: val, isSet: true} +} + +func (v NullablePermitBackendSchemasSchemaOpalDataDerivationSettings) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePermitBackendSchemasSchemaOpalDataDerivationSettings) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_create.go new file mode 100644 index 00000000..c69e9846 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_create.go @@ -0,0 +1,246 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PolicyRepoCreate struct for PolicyRepoCreate +type PolicyRepoCreate struct { + // A URL-friendly name of the policy repo (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the policy repo. + Key string `json:"key"` + Url string `json:"url"` + MainBranchName *string `json:"main_branch_name,omitempty"` + Credentials SSHAuthData `json:"credentials"` + // if you want to change your policy repository to this repo right after it is validated + ActivateWhenValidated *bool `json:"activate_when_validated,omitempty"` +} + +// NewPolicyRepoCreate instantiates a new PolicyRepoCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPolicyRepoCreate(key string, url string, credentials SSHAuthData) *PolicyRepoCreate { + this := PolicyRepoCreate{} + this.Key = key + this.Url = url + var mainBranchName string = "main" + this.MainBranchName = &mainBranchName + this.Credentials = credentials + var activateWhenValidated bool = false + this.ActivateWhenValidated = &activateWhenValidated + return &this +} + +// NewPolicyRepoCreateWithDefaults instantiates a new PolicyRepoCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPolicyRepoCreateWithDefaults() *PolicyRepoCreate { + this := PolicyRepoCreate{} + var mainBranchName string = "main" + this.MainBranchName = &mainBranchName + var activateWhenValidated bool = false + this.ActivateWhenValidated = &activateWhenValidated + return &this +} + +// GetKey returns the Key field value +func (o *PolicyRepoCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *PolicyRepoCreate) SetKey(v string) { + o.Key = v +} + +// GetUrl returns the Url field value +func (o *PolicyRepoCreate) GetUrl() string { + if o == nil { + var ret string + return ret + } + + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoCreate) GetUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Url, true +} + +// SetUrl sets field value +func (o *PolicyRepoCreate) SetUrl(v string) { + o.Url = v +} + +// GetMainBranchName returns the MainBranchName field value if set, zero value otherwise. +func (o *PolicyRepoCreate) GetMainBranchName() string { + if o == nil || IsNil(o.MainBranchName) { + var ret string + return ret + } + return *o.MainBranchName +} + +// GetMainBranchNameOk returns a tuple with the MainBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PolicyRepoCreate) GetMainBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.MainBranchName) { + return nil, false + } + return o.MainBranchName, true +} + +// HasMainBranchName returns a boolean if a field has been set. +func (o *PolicyRepoCreate) HasMainBranchName() bool { + if o != nil && !IsNil(o.MainBranchName) { + return true + } + + return false +} + +// SetMainBranchName gets a reference to the given string and assigns it to the MainBranchName field. +func (o *PolicyRepoCreate) SetMainBranchName(v string) { + o.MainBranchName = &v +} + +// GetCredentials returns the Credentials field value +func (o *PolicyRepoCreate) GetCredentials() SSHAuthData { + if o == nil { + var ret SSHAuthData + return ret + } + + return o.Credentials +} + +// GetCredentialsOk returns a tuple with the Credentials field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoCreate) GetCredentialsOk() (*SSHAuthData, bool) { + if o == nil { + return nil, false + } + return &o.Credentials, true +} + +// SetCredentials sets field value +func (o *PolicyRepoCreate) SetCredentials(v SSHAuthData) { + o.Credentials = v +} + +// GetActivateWhenValidated returns the ActivateWhenValidated field value if set, zero value otherwise. +func (o *PolicyRepoCreate) GetActivateWhenValidated() bool { + if o == nil || IsNil(o.ActivateWhenValidated) { + var ret bool + return ret + } + return *o.ActivateWhenValidated +} + +// GetActivateWhenValidatedOk returns a tuple with the ActivateWhenValidated field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PolicyRepoCreate) GetActivateWhenValidatedOk() (*bool, bool) { + if o == nil || IsNil(o.ActivateWhenValidated) { + return nil, false + } + return o.ActivateWhenValidated, true +} + +// HasActivateWhenValidated returns a boolean if a field has been set. +func (o *PolicyRepoCreate) HasActivateWhenValidated() bool { + if o != nil && !IsNil(o.ActivateWhenValidated) { + return true + } + + return false +} + +// SetActivateWhenValidated gets a reference to the given bool and assigns it to the ActivateWhenValidated field. +func (o *PolicyRepoCreate) SetActivateWhenValidated(v bool) { + o.ActivateWhenValidated = &v +} + +func (o PolicyRepoCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["url"] = o.Url + } + if !IsNil(o.MainBranchName) { + toSerialize["main_branch_name"] = o.MainBranchName + } + if true { + toSerialize["credentials"] = o.Credentials + } + if !IsNil(o.ActivateWhenValidated) { + toSerialize["activate_when_validated"] = o.ActivateWhenValidated + } + return json.Marshal(toSerialize) +} + +type NullablePolicyRepoCreate struct { + value *PolicyRepoCreate + isSet bool +} + +func (v NullablePolicyRepoCreate) Get() *PolicyRepoCreate { + return v.value +} + +func (v *NullablePolicyRepoCreate) Set(val *PolicyRepoCreate) { + v.value = val + v.isSet = true +} + +func (v NullablePolicyRepoCreate) IsSet() bool { + return v.isSet +} + +func (v *NullablePolicyRepoCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePolicyRepoCreate(val *PolicyRepoCreate) *NullablePolicyRepoCreate { + return &NullablePolicyRepoCreate{value: val, isSet: true} +} + +func (v NullablePolicyRepoCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePolicyRepoCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_read.go new file mode 100644 index 00000000..4594c5e4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_read.go @@ -0,0 +1,305 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// PolicyRepoRead struct for PolicyRepoRead +type PolicyRepoRead struct { + // Unique id of the policy repo + Id string `json:"id"` + Status PolicyRepoStatus `json:"status"` + // A URL-friendly name of the policy repo (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the policy repo. + Key string `json:"key"` + Url string `json:"url"` + MainBranchName *string `json:"main_branch_name,omitempty"` + Credentials SSHAuthData `json:"credentials"` + // if you want to change your policy repository to this repo right after it is validated + ActivateWhenValidated *bool `json:"activate_when_validated,omitempty"` +} + +// NewPolicyRepoRead instantiates a new PolicyRepoRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPolicyRepoRead(id string, status PolicyRepoStatus, key string, url string, credentials SSHAuthData) *PolicyRepoRead { + this := PolicyRepoRead{} + this.Id = id + this.Status = status + this.Key = key + this.Url = url + var mainBranchName string = "main" + this.MainBranchName = &mainBranchName + this.Credentials = credentials + var activateWhenValidated bool = false + this.ActivateWhenValidated = &activateWhenValidated + return &this +} + +// NewPolicyRepoReadWithDefaults instantiates a new PolicyRepoRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPolicyRepoReadWithDefaults() *PolicyRepoRead { + this := PolicyRepoRead{} + var mainBranchName string = "main" + this.MainBranchName = &mainBranchName + var activateWhenValidated bool = false + this.ActivateWhenValidated = &activateWhenValidated + return &this +} + +// GetId returns the Id field value +func (o *PolicyRepoRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *PolicyRepoRead) SetId(v string) { + o.Id = v +} + +// GetStatus returns the Status field value +func (o *PolicyRepoRead) GetStatus() PolicyRepoStatus { + if o == nil { + var ret PolicyRepoStatus + return ret + } + + return o.Status +} + +// GetStatusOk returns a tuple with the Status field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetStatusOk() (*PolicyRepoStatus, bool) { + if o == nil { + return nil, false + } + return &o.Status, true +} + +// SetStatus sets field value +func (o *PolicyRepoRead) SetStatus(v PolicyRepoStatus) { + o.Status = v +} + +// GetKey returns the Key field value +func (o *PolicyRepoRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *PolicyRepoRead) SetKey(v string) { + o.Key = v +} + +// GetUrl returns the Url field value +func (o *PolicyRepoRead) GetUrl() string { + if o == nil { + var ret string + return ret + } + + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Url, true +} + +// SetUrl sets field value +func (o *PolicyRepoRead) SetUrl(v string) { + o.Url = v +} + +// GetMainBranchName returns the MainBranchName field value if set, zero value otherwise. +func (o *PolicyRepoRead) GetMainBranchName() string { + if o == nil || IsNil(o.MainBranchName) { + var ret string + return ret + } + return *o.MainBranchName +} + +// GetMainBranchNameOk returns a tuple with the MainBranchName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetMainBranchNameOk() (*string, bool) { + if o == nil || IsNil(o.MainBranchName) { + return nil, false + } + return o.MainBranchName, true +} + +// HasMainBranchName returns a boolean if a field has been set. +func (o *PolicyRepoRead) HasMainBranchName() bool { + if o != nil && !IsNil(o.MainBranchName) { + return true + } + + return false +} + +// SetMainBranchName gets a reference to the given string and assigns it to the MainBranchName field. +func (o *PolicyRepoRead) SetMainBranchName(v string) { + o.MainBranchName = &v +} + +// GetCredentials returns the Credentials field value +func (o *PolicyRepoRead) GetCredentials() SSHAuthData { + if o == nil { + var ret SSHAuthData + return ret + } + + return o.Credentials +} + +// GetCredentialsOk returns a tuple with the Credentials field value +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetCredentialsOk() (*SSHAuthData, bool) { + if o == nil { + return nil, false + } + return &o.Credentials, true +} + +// SetCredentials sets field value +func (o *PolicyRepoRead) SetCredentials(v SSHAuthData) { + o.Credentials = v +} + +// GetActivateWhenValidated returns the ActivateWhenValidated field value if set, zero value otherwise. +func (o *PolicyRepoRead) GetActivateWhenValidated() bool { + if o == nil || IsNil(o.ActivateWhenValidated) { + var ret bool + return ret + } + return *o.ActivateWhenValidated +} + +// GetActivateWhenValidatedOk returns a tuple with the ActivateWhenValidated field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PolicyRepoRead) GetActivateWhenValidatedOk() (*bool, bool) { + if o == nil || IsNil(o.ActivateWhenValidated) { + return nil, false + } + return o.ActivateWhenValidated, true +} + +// HasActivateWhenValidated returns a boolean if a field has been set. +func (o *PolicyRepoRead) HasActivateWhenValidated() bool { + if o != nil && !IsNil(o.ActivateWhenValidated) { + return true + } + + return false +} + +// SetActivateWhenValidated gets a reference to the given bool and assigns it to the ActivateWhenValidated field. +func (o *PolicyRepoRead) SetActivateWhenValidated(v bool) { + o.ActivateWhenValidated = &v +} + +func (o PolicyRepoRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["status"] = o.Status + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["url"] = o.Url + } + if !IsNil(o.MainBranchName) { + toSerialize["main_branch_name"] = o.MainBranchName + } + if true { + toSerialize["credentials"] = o.Credentials + } + if !IsNil(o.ActivateWhenValidated) { + toSerialize["activate_when_validated"] = o.ActivateWhenValidated + } + return json.Marshal(toSerialize) +} + +type NullablePolicyRepoRead struct { + value *PolicyRepoRead + isSet bool +} + +func (v NullablePolicyRepoRead) Get() *PolicyRepoRead { + return v.value +} + +func (v *NullablePolicyRepoRead) Set(val *PolicyRepoRead) { + v.value = val + v.isSet = true +} + +func (v NullablePolicyRepoRead) IsSet() bool { + return v.isSet +} + +func (v *NullablePolicyRepoRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePolicyRepoRead(val *PolicyRepoRead) *NullablePolicyRepoRead { + return &NullablePolicyRepoRead{value: val, isSet: true} +} + +func (v NullablePolicyRepoRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePolicyRepoRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_status.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_status.go new file mode 100644 index 00000000..97ec819c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_policy_repo_status.go @@ -0,0 +1,112 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// PolicyRepoStatus An enumeration. +type PolicyRepoStatus string + +// List of PolicyRepoStatus +const ( + INVALID PolicyRepoStatus = "invalid" + PENDING PolicyRepoStatus = "pending" + VALID PolicyRepoStatus = "valid" +) + +// All allowed values of PolicyRepoStatus enum +var AllowedPolicyRepoStatusEnumValues = []PolicyRepoStatus{ + "invalid", + "pending", + "valid", +} + +func (v *PolicyRepoStatus) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := PolicyRepoStatus(value) + for _, existing := range AllowedPolicyRepoStatusEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid PolicyRepoStatus", value) +} + +// NewPolicyRepoStatusFromValue returns a pointer to a valid PolicyRepoStatus +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewPolicyRepoStatusFromValue(v string) (*PolicyRepoStatus, error) { + ev := PolicyRepoStatus(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for PolicyRepoStatus: valid values are %v", v, AllowedPolicyRepoStatusEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v PolicyRepoStatus) IsValid() bool { + for _, existing := range AllowedPolicyRepoStatusEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to PolicyRepoStatus value +func (v PolicyRepoStatus) Ptr() *PolicyRepoStatus { + return &v +} + +type NullablePolicyRepoStatus struct { + value *PolicyRepoStatus + isSet bool +} + +func (v NullablePolicyRepoStatus) Get() *PolicyRepoStatus { + return v.value +} + +func (v *NullablePolicyRepoStatus) Set(val *PolicyRepoStatus) { + v.value = val + v.isSet = true +} + +func (v NullablePolicyRepoStatus) IsSet() bool { + return v.isSet +} + +func (v *NullablePolicyRepoStatus) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePolicyRepoStatus(val *PolicyRepoStatus) *NullablePolicyRepoStatus { + return &NullablePolicyRepoStatus{value: val, isSet: true} +} + +func (v NullablePolicyRepoStatus) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePolicyRepoStatus) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_programming_language.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_programming_language.go new file mode 100644 index 00000000..bb19a25f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_programming_language.go @@ -0,0 +1,116 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ProgrammingLanguage An enumeration. +type ProgrammingLanguage string + +// List of ProgrammingLanguage +const ( + JAVASCRIPT ProgrammingLanguage = "javascript" + PYTHON ProgrammingLanguage = "python" + DOTNET ProgrammingLanguage = "dotnet" + JAVA ProgrammingLanguage = "java" + KONG_GATEWAY ProgrammingLanguage = "kong_gateway" +) + +// All allowed values of ProgrammingLanguage enum +var AllowedProgrammingLanguageEnumValues = []ProgrammingLanguage{ + "javascript", + "python", + "dotnet", + "java", + "kong_gateway", +} + +func (v *ProgrammingLanguage) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ProgrammingLanguage(value) + for _, existing := range AllowedProgrammingLanguageEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ProgrammingLanguage", value) +} + +// NewProgrammingLanguageFromValue returns a pointer to a valid ProgrammingLanguage +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewProgrammingLanguageFromValue(v string) (*ProgrammingLanguage, error) { + ev := ProgrammingLanguage(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ProgrammingLanguage: valid values are %v", v, AllowedProgrammingLanguageEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ProgrammingLanguage) IsValid() bool { + for _, existing := range AllowedProgrammingLanguageEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ProgrammingLanguage value +func (v ProgrammingLanguage) Ptr() *ProgrammingLanguage { + return &v +} + +type NullableProgrammingLanguage struct { + value *ProgrammingLanguage + isSet bool +} + +func (v NullableProgrammingLanguage) Get() *ProgrammingLanguage { + return v.value +} + +func (v *NullableProgrammingLanguage) Set(val *ProgrammingLanguage) { + v.value = val + v.isSet = true +} + +func (v NullableProgrammingLanguage) IsSet() bool { + return v.isSet +} + +func (v *NullableProgrammingLanguage) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProgrammingLanguage(val *ProgrammingLanguage) *NullableProgrammingLanguage { + return &NullableProgrammingLanguage{value: val, isSet: true} +} + +func (v NullableProgrammingLanguage) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProgrammingLanguage) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_project_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_project_create.go new file mode 100644 index 00000000..eea112cc --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_project_create.go @@ -0,0 +1,285 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ProjectCreate struct for ProjectCreate +type ProjectCreate struct { + // A URL-friendly name of the project (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the project. + Key string `json:"key"` + // Optional namespace for URNs. If empty, URNs will be generated from project key. + UrnNamespace *string `json:"urn_namespace,omitempty"` + // The name of the project + Name string `json:"name"` + // a longer description outlining the project objectives + Description *string `json:"description,omitempty"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` + // the id of the policy repo to use for this project + ActivePolicyRepoId *string `json:"active_policy_repo_id,omitempty"` +} + +// NewProjectCreate instantiates a new ProjectCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProjectCreate(key string, name string) *ProjectCreate { + this := ProjectCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewProjectCreateWithDefaults instantiates a new ProjectCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProjectCreateWithDefaults() *ProjectCreate { + this := ProjectCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ProjectCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ProjectCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ProjectCreate) SetKey(v string) { + o.Key = v +} + +// GetUrnNamespace returns the UrnNamespace field value if set, zero value otherwise. +func (o *ProjectCreate) GetUrnNamespace() string { + if o == nil || IsNil(o.UrnNamespace) { + var ret string + return ret + } + return *o.UrnNamespace +} + +// GetUrnNamespaceOk returns a tuple with the UrnNamespace field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectCreate) GetUrnNamespaceOk() (*string, bool) { + if o == nil || IsNil(o.UrnNamespace) { + return nil, false + } + return o.UrnNamespace, true +} + +// HasUrnNamespace returns a boolean if a field has been set. +func (o *ProjectCreate) HasUrnNamespace() bool { + if o != nil && !IsNil(o.UrnNamespace) { + return true + } + + return false +} + +// SetUrnNamespace gets a reference to the given string and assigns it to the UrnNamespace field. +func (o *ProjectCreate) SetUrnNamespace(v string) { + o.UrnNamespace = &v +} + +// GetName returns the Name field value +func (o *ProjectCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ProjectCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ProjectCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ProjectCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ProjectCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ProjectCreate) SetDescription(v string) { + o.Description = &v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *ProjectCreate) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectCreate) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *ProjectCreate) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *ProjectCreate) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +// GetActivePolicyRepoId returns the ActivePolicyRepoId field value if set, zero value otherwise. +func (o *ProjectCreate) GetActivePolicyRepoId() string { + if o == nil || IsNil(o.ActivePolicyRepoId) { + var ret string + return ret + } + return *o.ActivePolicyRepoId +} + +// GetActivePolicyRepoIdOk returns a tuple with the ActivePolicyRepoId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectCreate) GetActivePolicyRepoIdOk() (*string, bool) { + if o == nil || IsNil(o.ActivePolicyRepoId) { + return nil, false + } + return o.ActivePolicyRepoId, true +} + +// HasActivePolicyRepoId returns a boolean if a field has been set. +func (o *ProjectCreate) HasActivePolicyRepoId() bool { + if o != nil && !IsNil(o.ActivePolicyRepoId) { + return true + } + + return false +} + +// SetActivePolicyRepoId gets a reference to the given string and assigns it to the ActivePolicyRepoId field. +func (o *ProjectCreate) SetActivePolicyRepoId(v string) { + o.ActivePolicyRepoId = &v +} + +func (o ProjectCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if !IsNil(o.UrnNamespace) { + toSerialize["urn_namespace"] = o.UrnNamespace + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + if !IsNil(o.ActivePolicyRepoId) { + toSerialize["active_policy_repo_id"] = o.ActivePolicyRepoId + } + return json.Marshal(toSerialize) +} + +type NullableProjectCreate struct { + value *ProjectCreate + isSet bool +} + +func (v NullableProjectCreate) Get() *ProjectCreate { + return v.value +} + +func (v *NullableProjectCreate) Set(val *ProjectCreate) { + v.value = val + v.isSet = true +} + +func (v NullableProjectCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableProjectCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProjectCreate(val *ProjectCreate) *NullableProjectCreate { + return &NullableProjectCreate{value: val, isSet: true} +} + +func (v NullableProjectCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProjectCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_project_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_project_read.go new file mode 100644 index 00000000..a21c96cf --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_project_read.go @@ -0,0 +1,406 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ProjectRead struct for ProjectRead +type ProjectRead struct { + // A URL-friendly name of the project (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the project. + Key string `json:"key"` + // Optional namespace for URNs. If empty, URNs will be generated from project key. + UrnNamespace *string `json:"urn_namespace,omitempty"` + // Unique id of the project + Id string `json:"id"` + // Unique id of the organization that the project belongs to. + OrganizationId string `json:"organization_id"` + // Date and time when the project was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the project was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The name of the project + Name string `json:"name"` + // a longer description outlining the project objectives + Description *string `json:"description,omitempty"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` + // the id of the policy repo to use for this project + ActivePolicyRepoId *string `json:"active_policy_repo_id,omitempty"` +} + +// NewProjectRead instantiates a new ProjectRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProjectRead(key string, id string, organizationId string, createdAt time.Time, updatedAt time.Time, name string) *ProjectRead { + this := ProjectRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + return &this +} + +// NewProjectReadWithDefaults instantiates a new ProjectRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProjectReadWithDefaults() *ProjectRead { + this := ProjectRead{} + return &this +} + +// GetKey returns the Key field value +func (o *ProjectRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ProjectRead) SetKey(v string) { + o.Key = v +} + +// GetUrnNamespace returns the UrnNamespace field value if set, zero value otherwise. +func (o *ProjectRead) GetUrnNamespace() string { + if o == nil || IsNil(o.UrnNamespace) { + var ret string + return ret + } + return *o.UrnNamespace +} + +// GetUrnNamespaceOk returns a tuple with the UrnNamespace field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetUrnNamespaceOk() (*string, bool) { + if o == nil || IsNil(o.UrnNamespace) { + return nil, false + } + return o.UrnNamespace, true +} + +// HasUrnNamespace returns a boolean if a field has been set. +func (o *ProjectRead) HasUrnNamespace() bool { + if o != nil && !IsNil(o.UrnNamespace) { + return true + } + + return false +} + +// SetUrnNamespace gets a reference to the given string and assigns it to the UrnNamespace field. +func (o *ProjectRead) SetUrnNamespace(v string) { + o.UrnNamespace = &v +} + +// GetId returns the Id field value +func (o *ProjectRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ProjectRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ProjectRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ProjectRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ProjectRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ProjectRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ProjectRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ProjectRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetName returns the Name field value +func (o *ProjectRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ProjectRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ProjectRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ProjectRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ProjectRead) SetDescription(v string) { + o.Description = &v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *ProjectRead) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *ProjectRead) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *ProjectRead) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +// GetActivePolicyRepoId returns the ActivePolicyRepoId field value if set, zero value otherwise. +func (o *ProjectRead) GetActivePolicyRepoId() string { + if o == nil || IsNil(o.ActivePolicyRepoId) { + var ret string + return ret + } + return *o.ActivePolicyRepoId +} + +// GetActivePolicyRepoIdOk returns a tuple with the ActivePolicyRepoId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectRead) GetActivePolicyRepoIdOk() (*string, bool) { + if o == nil || IsNil(o.ActivePolicyRepoId) { + return nil, false + } + return o.ActivePolicyRepoId, true +} + +// HasActivePolicyRepoId returns a boolean if a field has been set. +func (o *ProjectRead) HasActivePolicyRepoId() bool { + if o != nil && !IsNil(o.ActivePolicyRepoId) { + return true + } + + return false +} + +// SetActivePolicyRepoId gets a reference to the given string and assigns it to the ActivePolicyRepoId field. +func (o *ProjectRead) SetActivePolicyRepoId(v string) { + o.ActivePolicyRepoId = &v +} + +func (o ProjectRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if !IsNil(o.UrnNamespace) { + toSerialize["urn_namespace"] = o.UrnNamespace + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + if !IsNil(o.ActivePolicyRepoId) { + toSerialize["active_policy_repo_id"] = o.ActivePolicyRepoId + } + return json.Marshal(toSerialize) +} + +type NullableProjectRead struct { + value *ProjectRead + isSet bool +} + +func (v NullableProjectRead) Get() *ProjectRead { + return v.value +} + +func (v *NullableProjectRead) Set(val *ProjectRead) { + v.value = val + v.isSet = true +} + +func (v NullableProjectRead) IsSet() bool { + return v.isSet +} + +func (v *NullableProjectRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProjectRead(val *ProjectRead) *NullableProjectRead { + return &NullableProjectRead{value: val, isSet: true} +} + +func (v NullableProjectRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProjectRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_project_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_project_update.go new file mode 100644 index 00000000..bd29002d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_project_update.go @@ -0,0 +1,225 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ProjectUpdate struct for ProjectUpdate +type ProjectUpdate struct { + // The name of the project + Name *string `json:"name,omitempty"` + // a longer description outlining the project objectives + Description *string `json:"description,omitempty"` + // the settings for this project + Settings map[string]interface{} `json:"settings,omitempty"` + // the id of the policy repo to use for this project + ActivePolicyRepoId *string `json:"active_policy_repo_id,omitempty"` +} + +// NewProjectUpdate instantiates a new ProjectUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProjectUpdate() *ProjectUpdate { + this := ProjectUpdate{} + return &this +} + +// NewProjectUpdateWithDefaults instantiates a new ProjectUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProjectUpdateWithDefaults() *ProjectUpdate { + this := ProjectUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ProjectUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ProjectUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ProjectUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ProjectUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ProjectUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ProjectUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetSettings returns the Settings field value if set, zero value otherwise. +func (o *ProjectUpdate) GetSettings() map[string]interface{} { + if o == nil || IsNil(o.Settings) { + var ret map[string]interface{} + return ret + } + return o.Settings +} + +// GetSettingsOk returns a tuple with the Settings field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectUpdate) GetSettingsOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Settings) { + return map[string]interface{}{}, false + } + return o.Settings, true +} + +// HasSettings returns a boolean if a field has been set. +func (o *ProjectUpdate) HasSettings() bool { + if o != nil && !IsNil(o.Settings) { + return true + } + + return false +} + +// SetSettings gets a reference to the given map[string]interface{} and assigns it to the Settings field. +func (o *ProjectUpdate) SetSettings(v map[string]interface{}) { + o.Settings = v +} + +// GetActivePolicyRepoId returns the ActivePolicyRepoId field value if set, zero value otherwise. +func (o *ProjectUpdate) GetActivePolicyRepoId() string { + if o == nil || IsNil(o.ActivePolicyRepoId) { + var ret string + return ret + } + return *o.ActivePolicyRepoId +} + +// GetActivePolicyRepoIdOk returns a tuple with the ActivePolicyRepoId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProjectUpdate) GetActivePolicyRepoIdOk() (*string, bool) { + if o == nil || IsNil(o.ActivePolicyRepoId) { + return nil, false + } + return o.ActivePolicyRepoId, true +} + +// HasActivePolicyRepoId returns a boolean if a field has been set. +func (o *ProjectUpdate) HasActivePolicyRepoId() bool { + if o != nil && !IsNil(o.ActivePolicyRepoId) { + return true + } + + return false +} + +// SetActivePolicyRepoId gets a reference to the given string and assigns it to the ActivePolicyRepoId field. +func (o *ProjectUpdate) SetActivePolicyRepoId(v string) { + o.ActivePolicyRepoId = &v +} + +func (o ProjectUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Settings) { + toSerialize["settings"] = o.Settings + } + if !IsNil(o.ActivePolicyRepoId) { + toSerialize["active_policy_repo_id"] = o.ActivePolicyRepoId + } + return json.Marshal(toSerialize) +} + +type NullableProjectUpdate struct { + value *ProjectUpdate + isSet bool +} + +func (v NullableProjectUpdate) Get() *ProjectUpdate { + return v.value +} + +func (v *NullableProjectUpdate) Set(val *ProjectUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableProjectUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableProjectUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProjectUpdate(val *ProjectUpdate) *NullableProjectUpdate { + return &NullableProjectUpdate{value: val, isSet: true} +} + +func (v NullableProjectUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProjectUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_create.go new file mode 100644 index 00000000..00254975 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_create.go @@ -0,0 +1,248 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ProxyConfigCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ProxyConfigCreate{} + +// ProxyConfigCreate struct for ProxyConfigCreate +type ProxyConfigCreate struct { + Secret string `json:"secret"` + // Proxy Config is set to enable the Permit Proxy to make proxied requests as part of the Frontend AuthZ. + Key string `json:"key"` + // The name of the proxy config, for example: 'Stripe API' + Name string `json:"name"` + // Proxy config mapping rules will include the rules that will be used to map the request to the backend service by a URL and a http method. + MappingRules []MappingRule `json:"mapping_rules,omitempty"` + AuthMechanism *AuthMechanism `json:"auth_mechanism,omitempty"` +} + +// NewProxyConfigCreate instantiates a new ProxyConfigCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProxyConfigCreate(secret string, key string, name string) *ProxyConfigCreate { + this := ProxyConfigCreate{} + this.Secret = secret + this.Key = key + this.Name = name + var authMechanism AuthMechanism = BASIC + this.AuthMechanism = &authMechanism + return &this +} + +// NewProxyConfigCreateWithDefaults instantiates a new ProxyConfigCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProxyConfigCreateWithDefaults() *ProxyConfigCreate { + this := ProxyConfigCreate{} + var authMechanism AuthMechanism = BEARER + this.AuthMechanism = &authMechanism + return &this +} + +// GetSecret returns the Secret field value +func (o *ProxyConfigCreate) GetSecret() string { + if o == nil { + var ret string + return ret + } + + return o.Secret +} + +// GetSecretOk returns a tuple with the Secret field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigCreate) GetSecretOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Secret, true +} + +// SetSecret sets field value +func (o *ProxyConfigCreate) SetSecret(v string) { + o.Secret = v +} + +// GetKey returns the Key field value +func (o *ProxyConfigCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ProxyConfigCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *ProxyConfigCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ProxyConfigCreate) SetName(v string) { + o.Name = v +} + +// GetMappingRules returns the MappingRules field value if set, zero value otherwise. +func (o *ProxyConfigCreate) GetMappingRules() []MappingRule { + if o == nil || IsNil(o.MappingRules) { + var ret []MappingRule + return ret + } + return o.MappingRules +} + +// GetMappingRulesOk returns a tuple with the MappingRules field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigCreate) GetMappingRulesOk() ([]MappingRule, bool) { + if o == nil || IsNil(o.MappingRules) { + return nil, false + } + return o.MappingRules, true +} + +// HasMappingRules returns a boolean if a field has been set. +func (o *ProxyConfigCreate) HasMappingRules() bool { + if o != nil && !IsNil(o.MappingRules) { + return true + } + + return false +} + +// SetMappingRules gets a reference to the given []MappingRule and assigns it to the MappingRules field. +func (o *ProxyConfigCreate) SetMappingRules(v []MappingRule) { + o.MappingRules = v +} + +// GetAuthMechanism returns the AuthMechanism field value if set, zero value otherwise. +func (o *ProxyConfigCreate) GetAuthMechanism() AuthMechanism { + if o == nil || IsNil(o.AuthMechanism) { + var ret AuthMechanism + return ret + } + return *o.AuthMechanism +} + +// GetAuthMechanismOk returns a tuple with the AuthMechanism field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigCreate) GetAuthMechanismOk() (*AuthMechanism, bool) { + if o == nil || IsNil(o.AuthMechanism) { + return nil, false + } + return o.AuthMechanism, true +} + +// HasAuthMechanism returns a boolean if a field has been set. +func (o *ProxyConfigCreate) HasAuthMechanism() bool { + if o != nil && !IsNil(o.AuthMechanism) { + return true + } + + return false +} + +// SetAuthMechanism gets a reference to the given AuthMechanism and assigns it to the AuthMechanism field. +func (o *ProxyConfigCreate) SetAuthMechanism(v AuthMechanism) { + o.AuthMechanism = &v +} + +func (o ProxyConfigCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ProxyConfigCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["secret"] = o.Secret + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.MappingRules) { + toSerialize["mapping_rules"] = o.MappingRules + } + if !IsNil(o.AuthMechanism) { + toSerialize["auth_mechanism"] = o.AuthMechanism + } + return toSerialize, nil +} + +type NullableProxyConfigCreate struct { + value *ProxyConfigCreate + isSet bool +} + +func (v NullableProxyConfigCreate) Get() *ProxyConfigCreate { + return v.value +} + +func (v *NullableProxyConfigCreate) Set(val *ProxyConfigCreate) { + v.value = val + v.isSet = true +} + +func (v NullableProxyConfigCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableProxyConfigCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProxyConfigCreate(val *ProxyConfigCreate) *NullableProxyConfigCreate { + return &NullableProxyConfigCreate{value: val, isSet: true} +} + +func (v NullableProxyConfigCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProxyConfigCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_read.go new file mode 100644 index 00000000..88b65520 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_read.go @@ -0,0 +1,417 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the ProxyConfigRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ProxyConfigRead{} + +// ProxyConfigRead struct for ProxyConfigRead +type ProxyConfigRead struct { + // Proxy Config is set to enable the Permit Proxy to make proxied requests as part of the Frontend AuthZ. + Key string `json:"key"` + // Unique id of the proxy config + Id string `json:"id"` + // Unique id of the organization that the proxy config belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the proxy config belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the proxy config belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the proxy config was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the proxy config was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + Secret string `json:"secret"` + // The name of the proxy config, for example: 'Stripe API' + Name string `json:"name"` + // Proxy config mapping rules will include the rules that will be used to map the request to the backend service by a URL and a http method. + MappingRules []MappingRule `json:"mapping_rules,omitempty"` + AuthMechanism *AuthMechanism `json:"auth_mechanism,omitempty"` +} + +// NewProxyConfigRead instantiates a new ProxyConfigRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProxyConfigRead(key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, secret string, name string) *ProxyConfigRead { + this := ProxyConfigRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Secret = secret + this.Name = name + var authMechanism AuthMechanism = BEARER + this.AuthMechanism = &authMechanism + return &this +} + +// NewProxyConfigReadWithDefaults instantiates a new ProxyConfigRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProxyConfigReadWithDefaults() *ProxyConfigRead { + this := ProxyConfigRead{} + var authMechanism AuthMechanism = BEARER + this.AuthMechanism = &authMechanism + return &this +} + +// GetKey returns the Key field value +func (o *ProxyConfigRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ProxyConfigRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ProxyConfigRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ProxyConfigRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ProxyConfigRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ProxyConfigRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ProxyConfigRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ProxyConfigRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ProxyConfigRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ProxyConfigRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ProxyConfigRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ProxyConfigRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ProxyConfigRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ProxyConfigRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetSecret returns the Secret field value +func (o *ProxyConfigRead) GetSecret() string { + if o == nil { + var ret string + return ret + } + + return o.Secret +} + +// GetSecretOk returns a tuple with the Secret field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetSecretOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Secret, true +} + +// SetSecret sets field value +func (o *ProxyConfigRead) SetSecret(v string) { + o.Secret = v +} + +// GetName returns the Name field value +func (o *ProxyConfigRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ProxyConfigRead) SetName(v string) { + o.Name = v +} + +// GetMappingRules returns the MappingRules field value if set, zero value otherwise. +func (o *ProxyConfigRead) GetMappingRules() []MappingRule { + if o == nil || IsNil(o.MappingRules) { + var ret []MappingRule + return ret + } + return o.MappingRules +} + +// GetMappingRulesOk returns a tuple with the MappingRules field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetMappingRulesOk() ([]MappingRule, bool) { + if o == nil || IsNil(o.MappingRules) { + return nil, false + } + return o.MappingRules, true +} + +// HasMappingRules returns a boolean if a field has been set. +func (o *ProxyConfigRead) HasMappingRules() bool { + if o != nil && !IsNil(o.MappingRules) { + return true + } + + return false +} + +// SetMappingRules gets a reference to the given []MappingRule and assigns it to the MappingRules field. +func (o *ProxyConfigRead) SetMappingRules(v []MappingRule) { + o.MappingRules = v +} + +// GetAuthMechanism returns the AuthMechanism field value if set, zero value otherwise. +func (o *ProxyConfigRead) GetAuthMechanism() AuthMechanism { + if o == nil || IsNil(o.AuthMechanism) { + var ret AuthMechanism + return ret + } + return *o.AuthMechanism +} + +// GetAuthMechanismOk returns a tuple with the AuthMechanism field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigRead) GetAuthMechanismOk() (*AuthMechanism, bool) { + if o == nil || IsNil(o.AuthMechanism) { + return nil, false + } + return o.AuthMechanism, true +} + +// HasAuthMechanism returns a boolean if a field has been set. +func (o *ProxyConfigRead) HasAuthMechanism() bool { + if o != nil && !IsNil(o.AuthMechanism) { + return true + } + + return false +} + +// SetAuthMechanism gets a reference to the given AuthMechanism and assigns it to the AuthMechanism field. +func (o *ProxyConfigRead) SetAuthMechanism(v AuthMechanism) { + o.AuthMechanism = &v +} + +func (o ProxyConfigRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ProxyConfigRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["id"] = o.Id + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + toSerialize["secret"] = o.Secret + toSerialize["name"] = o.Name + if !IsNil(o.MappingRules) { + toSerialize["mapping_rules"] = o.MappingRules + } + if !IsNil(o.AuthMechanism) { + toSerialize["auth_mechanism"] = o.AuthMechanism + } + return toSerialize, nil +} + +type NullableProxyConfigRead struct { + value *ProxyConfigRead + isSet bool +} + +func (v NullableProxyConfigRead) Get() *ProxyConfigRead { + return v.value +} + +func (v *NullableProxyConfigRead) Set(val *ProxyConfigRead) { + v.value = val + v.isSet = true +} + +func (v NullableProxyConfigRead) IsSet() bool { + return v.isSet +} + +func (v *NullableProxyConfigRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProxyConfigRead(val *ProxyConfigRead) *NullableProxyConfigRead { + return &NullableProxyConfigRead{value: val, isSet: true} +} + +func (v NullableProxyConfigRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProxyConfigRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_update.go new file mode 100644 index 00000000..c107f4f3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_proxy_config_update.go @@ -0,0 +1,237 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ProxyConfigUpdate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ProxyConfigUpdate{} + +// ProxyConfigUpdate struct for ProxyConfigUpdate +type ProxyConfigUpdate struct { + Secret *string `json:"secret,omitempty"` + // The name of the proxy config, for example: 'Stripe API' + Name *string `json:"name,omitempty"` + // Proxy config mapping rules will include the rules that will be used to map the request to the backend service by a URL and a http method. + MappingRules []MappingRule `json:"mapping_rules,omitempty"` + AuthMechanism *AuthMechanism `json:"auth_mechanism,omitempty"` +} + +// NewProxyConfigUpdate instantiates a new ProxyConfigUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProxyConfigUpdate() *ProxyConfigUpdate { + this := ProxyConfigUpdate{} + + return &this +} + +// NewProxyConfigUpdateWithDefaults instantiates a new ProxyConfigUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProxyConfigUpdateWithDefaults() *ProxyConfigUpdate { + this := ProxyConfigUpdate{} + var authMechanism AuthMechanism = BEARER + this.AuthMechanism = &authMechanism + return &this +} + +// GetSecret returns the Secret field value if set, zero value otherwise. +func (o *ProxyConfigUpdate) GetSecret() string { + if o == nil || IsNil(o.Secret) { + var ret string + return ret + } + return *o.Secret +} + +// GetSecretOk returns a tuple with the Secret field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigUpdate) GetSecretOk() (*string, bool) { + if o == nil || IsNil(o.Secret) { + return nil, false + } + return o.Secret, true +} + +// HasSecret returns a boolean if a field has been set. +func (o *ProxyConfigUpdate) HasSecret() bool { + if o != nil && !IsNil(o.Secret) { + return true + } + + return false +} + +// SetSecret gets a reference to the given Secret and assigns it to the Secret field. +func (o *ProxyConfigUpdate) SetSecret(v string) { + o.Secret = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ProxyConfigUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ProxyConfigUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ProxyConfigUpdate) SetName(v string) { + o.Name = &v +} + +// GetMappingRules returns the MappingRules field value if set, zero value otherwise. +func (o *ProxyConfigUpdate) GetMappingRules() []MappingRule { + if o == nil || IsNil(o.MappingRules) { + var ret []MappingRule + return ret + } + return o.MappingRules +} + +// GetMappingRulesOk returns a tuple with the MappingRules field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigUpdate) GetMappingRulesOk() ([]MappingRule, bool) { + if o == nil || IsNil(o.MappingRules) { + return nil, false + } + return o.MappingRules, true +} + +// HasMappingRules returns a boolean if a field has been set. +func (o *ProxyConfigUpdate) HasMappingRules() bool { + if o != nil && !IsNil(o.MappingRules) { + return true + } + + return false +} + +// SetMappingRules gets a reference to the given []MappingRule and assigns it to the MappingRules field. +func (o *ProxyConfigUpdate) SetMappingRules(v []MappingRule) { + o.MappingRules = v +} + +// GetAuthMechanism returns the AuthMechanism field value if set, zero value otherwise. +func (o *ProxyConfigUpdate) GetAuthMechanism() AuthMechanism { + if o == nil || IsNil(o.AuthMechanism) { + var ret AuthMechanism + return ret + } + return *o.AuthMechanism +} + +// GetAuthMechanismOk returns a tuple with the AuthMechanism field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ProxyConfigUpdate) GetAuthMechanismOk() (*AuthMechanism, bool) { + if o == nil || IsNil(o.AuthMechanism) { + return nil, false + } + return o.AuthMechanism, true +} + +// HasAuthMechanism returns a boolean if a field has been set. +func (o *ProxyConfigUpdate) HasAuthMechanism() bool { + if o != nil && !IsNil(o.AuthMechanism) { + return true + } + + return false +} + +// SetAuthMechanism gets a reference to the given AuthMechanism and assigns it to the AuthMechanism field. +func (o *ProxyConfigUpdate) SetAuthMechanism(v AuthMechanism) { + o.AuthMechanism = &v +} + +func (o ProxyConfigUpdate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ProxyConfigUpdate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Secret) { + toSerialize["secret"] = o.Secret + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.MappingRules) { + toSerialize["mapping_rules"] = o.MappingRules + } + if !IsNil(o.AuthMechanism) { + toSerialize["auth_mechanism"] = o.AuthMechanism + } + return toSerialize, nil +} + +type NullableProxyConfigUpdate struct { + value *ProxyConfigUpdate + isSet bool +} + +func (v NullableProxyConfigUpdate) Get() *ProxyConfigUpdate { + return v.value +} + +func (v *NullableProxyConfigUpdate) Set(val *ProxyConfigUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableProxyConfigUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableProxyConfigUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProxyConfigUpdate(val *ProxyConfigUpdate) *NullableProxyConfigUpdate { + return &NullableProxyConfigUpdate{value: val, isSet: true} +} + +func (v NullableProxyConfigUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProxyConfigUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_block_read.go new file mode 100644 index 00000000..bd12cc7f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_block_read.go @@ -0,0 +1,181 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationBlockRead{} + +// RelationBlockRead struct for RelationBlockRead +type RelationBlockRead struct { + // An optional longer description of what this relation represents in your system + Description *string `json:"description,omitempty"` + // Unique id of the relation + ResourceId string `json:"resource_id"` + // The resource key + Resource string `json:"resource"` +} + +// NewRelationBlockRead instantiates a new RelationBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationBlockRead(resourceId string, resource string) *RelationBlockRead { + this := RelationBlockRead{} + this.ResourceId = resourceId + this.Resource = resource + return &this +} + +// NewRelationBlockReadWithDefaults instantiates a new RelationBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationBlockReadWithDefaults() *RelationBlockRead { + this := RelationBlockRead{} + return &this +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RelationBlockRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationBlockRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RelationBlockRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RelationBlockRead) SetDescription(v string) { + o.Description = &v +} + +// GetResourceId returns the ResourceId field value +func (o *RelationBlockRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *RelationBlockRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *RelationBlockRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetResource returns the Resource field value +func (o *RelationBlockRead) GetResource() string { + if o == nil { + var ret string + return ret + } + + return o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value +// and a boolean to check if the value has been set. +func (o *RelationBlockRead) GetResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Resource, true +} + +// SetResource sets field value +func (o *RelationBlockRead) SetResource(v string) { + o.Resource = v +} + +func (o RelationBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + toSerialize["resource_id"] = o.ResourceId + toSerialize["resource"] = o.Resource + return toSerialize, nil +} + +type NullableRelationBlockRead struct { + value *RelationBlockRead + isSet bool +} + +func (v NullableRelationBlockRead) Get() *RelationBlockRead { + return v.value +} + +func (v *NullableRelationBlockRead) Set(val *RelationBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableRelationBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationBlockRead(val *RelationBlockRead) *NullableRelationBlockRead { + return &NullableRelationBlockRead{value: val, isSet: true} +} + +func (v NullableRelationBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_create.go new file mode 100644 index 00000000..137a4cd6 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_create.go @@ -0,0 +1,209 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationCreate{} + +// RelationCreate struct for RelationCreate +type RelationCreate struct { + // A URL-friendly name of the relation (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the relation. + Key string `json:"key"` + // The name of the relation + Name string `json:"name"` + // An optional longer description of what this relation represents in your system + Description *string `json:"description,omitempty"` + // The subject resource ID or key + SubjectResource string `json:"subject_resource"` +} + +// NewRelationCreate instantiates a new RelationCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationCreate(key string, name string, subjectResource string) *RelationCreate { + this := RelationCreate{} + this.Key = key + this.Name = name + this.SubjectResource = subjectResource + return &this +} + +// NewRelationCreateWithDefaults instantiates a new RelationCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationCreateWithDefaults() *RelationCreate { + this := RelationCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *RelationCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RelationCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RelationCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *RelationCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *RelationCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *RelationCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RelationCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RelationCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RelationCreate) SetDescription(v string) { + o.Description = &v +} + +// GetSubjectResource returns the SubjectResource field value +func (o *RelationCreate) GetSubjectResource() string { + if o == nil { + var ret string + return ret + } + + return o.SubjectResource +} + +// GetSubjectResourceOk returns a tuple with the SubjectResource field value +// and a boolean to check if the value has been set. +func (o *RelationCreate) GetSubjectResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SubjectResource, true +} + +// SetSubjectResource sets field value +func (o *RelationCreate) SetSubjectResource(v string) { + o.SubjectResource = v +} + +func (o RelationCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + toSerialize["subject_resource"] = o.SubjectResource + return toSerialize, nil +} + +type NullableRelationCreate struct { + value *RelationCreate + isSet bool +} + +func (v NullableRelationCreate) Get() *RelationCreate { + return v.value +} + +func (v *NullableRelationCreate) Set(val *RelationCreate) { + v.value = val + v.isSet = true +} + +func (v NullableRelationCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationCreate(val *RelationCreate) *NullableRelationCreate { + return &NullableRelationCreate{value: val, isSet: true} +} + +func (v NullableRelationCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_read.go new file mode 100644 index 00000000..e4e34b8c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relation_read.go @@ -0,0 +1,462 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the RelationRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationRead{} + +// RelationRead struct for RelationRead +type RelationRead struct { + // An optional longer description of what this relation represents in your system + Description *string `json:"description,omitempty"` + // The subject resource ID or key + SubjectResource string `json:"subject_resource"` + // A URL-friendly name of the relation (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the relation. + Key string `json:"key"` + // The name of the relation + Name string `json:"name"` + // Unique id of the relation + Id string `json:"id"` + // Unique id of the organization that the relation belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the relation belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the relation belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the relation was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the relation was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The object resource id + ObjectResourceId string `json:"object_resource_id"` + // The object resource key + ObjectResource string `json:"object_resource"` + // The subject resource id + SubjectResourceId string `json:"subject_resource_id"` +} + +// NewRelationRead instantiates a new RelationRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationRead(subjectResource string, key string, name string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, objectResourceId string, objectResource string, subjectResourceId string) *RelationRead { + this := RelationRead{} + this.SubjectResource = subjectResource + this.Key = key + this.Name = name + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.ObjectResourceId = objectResourceId + this.ObjectResource = objectResource + this.SubjectResourceId = subjectResourceId + return &this +} + +// NewRelationReadWithDefaults instantiates a new RelationRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationReadWithDefaults() *RelationRead { + this := RelationRead{} + return &this +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RelationRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RelationRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RelationRead) SetDescription(v string) { + o.Description = &v +} + +// GetSubjectResource returns the SubjectResource field value +func (o *RelationRead) GetSubjectResource() string { + if o == nil { + var ret string + return ret + } + + return o.SubjectResource +} + +// GetSubjectResourceOk returns a tuple with the SubjectResource field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetSubjectResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SubjectResource, true +} + +// SetSubjectResource sets field value +func (o *RelationRead) SetSubjectResource(v string) { + o.SubjectResource = v +} + +// GetKey returns the Key field value +func (o *RelationRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RelationRead) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *RelationRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *RelationRead) SetName(v string) { + o.Name = v +} + +// GetId returns the Id field value +func (o *RelationRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RelationRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *RelationRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *RelationRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *RelationRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *RelationRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *RelationRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *RelationRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *RelationRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *RelationRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *RelationRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *RelationRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetObjectResourceId returns the ObjectResourceId field value +func (o *RelationRead) GetObjectResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ObjectResourceId +} + +// GetObjectResourceIdOk returns a tuple with the ObjectResourceId field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetObjectResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ObjectResourceId, true +} + +// SetObjectResourceId sets field value +func (o *RelationRead) SetObjectResourceId(v string) { + o.ObjectResourceId = v +} + +// GetObjectResource returns the ObjectResource field value +func (o *RelationRead) GetObjectResource() string { + if o == nil { + var ret string + return ret + } + + return o.ObjectResource +} + +// GetObjectResourceOk returns a tuple with the ObjectResource field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetObjectResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ObjectResource, true +} + +// SetObjectResource sets field value +func (o *RelationRead) SetObjectResource(v string) { + o.ObjectResource = v +} + +// GetSubjectResourceId returns the SubjectResourceId field value +func (o *RelationRead) GetSubjectResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.SubjectResourceId +} + +// GetSubjectResourceIdOk returns a tuple with the SubjectResourceId field value +// and a boolean to check if the value has been set. +func (o *RelationRead) GetSubjectResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SubjectResourceId, true +} + +// SetSubjectResourceId sets field value +func (o *RelationRead) SetSubjectResourceId(v string) { + o.SubjectResourceId = v +} + +func (o RelationRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + toSerialize["subject_resource"] = o.SubjectResource + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + toSerialize["id"] = o.Id + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + toSerialize["object_resource_id"] = o.ObjectResourceId + toSerialize["object_resource"] = o.ObjectResource + toSerialize["subject_resource_id"] = o.SubjectResourceId + return toSerialize, nil +} + +type NullableRelationRead struct { + value *RelationRead + isSet bool +} + +func (v NullableRelationRead) Get() *RelationRead { + return v.value +} + +func (v *NullableRelationRead) Set(val *RelationRead) { + v.value = val + v.isSet = true +} + +func (v NullableRelationRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationRead(val *RelationRead) *NullableRelationRead { + return &NullableRelationRead{value: val, isSet: true} +} + +func (v NullableRelationRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_block_read.go new file mode 100644 index 00000000..c089b196 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_block_read.go @@ -0,0 +1,172 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationshipTupleBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleBlockRead{} + +// RelationshipTupleBlockRead struct for RelationshipTupleBlockRead +type RelationshipTupleBlockRead struct { + // resource_key:resource_instance_key of the subject + Subject string `json:"subject"` + // key of the assigned relation + Relation string `json:"relation"` + // resource_key:resource_instance_key of the object + Object string `json:"object"` +} + +// NewRelationshipTupleBlockRead instantiates a new RelationshipTupleBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleBlockRead(subject string, relation string, object string) *RelationshipTupleBlockRead { + this := RelationshipTupleBlockRead{} + this.Subject = subject + this.Relation = relation + this.Object = object + return &this +} + +// NewRelationshipTupleBlockReadWithDefaults instantiates a new RelationshipTupleBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleBlockReadWithDefaults() *RelationshipTupleBlockRead { + this := RelationshipTupleBlockRead{} + return &this +} + +// GetSubject returns the Subject field value +func (o *RelationshipTupleBlockRead) GetSubject() string { + if o == nil { + var ret string + return ret + } + + return o.Subject +} + +// GetSubjectOk returns a tuple with the Subject field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleBlockRead) GetSubjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Subject, true +} + +// SetSubject sets field value +func (o *RelationshipTupleBlockRead) SetSubject(v string) { + o.Subject = v +} + +// GetRelation returns the Relation field value +func (o *RelationshipTupleBlockRead) GetRelation() string { + if o == nil { + var ret string + return ret + } + + return o.Relation +} + +// GetRelationOk returns a tuple with the Relation field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleBlockRead) GetRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Relation, true +} + +// SetRelation sets field value +func (o *RelationshipTupleBlockRead) SetRelation(v string) { + o.Relation = v +} + +// GetObject returns the Object field value +func (o *RelationshipTupleBlockRead) GetObject() string { + if o == nil { + var ret string + return ret + } + + return o.Object +} + +// GetObjectOk returns a tuple with the Object field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleBlockRead) GetObjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Object, true +} + +// SetObject sets field value +func (o *RelationshipTupleBlockRead) SetObject(v string) { + o.Object = v +} + +func (o RelationshipTupleBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["subject"] = o.Subject + toSerialize["relation"] = o.Relation + toSerialize["object"] = o.Object + return toSerialize, nil +} + +type NullableRelationshipTupleBlockRead struct { + value *RelationshipTupleBlockRead + isSet bool +} + +func (v NullableRelationshipTupleBlockRead) Get() *RelationshipTupleBlockRead { + return v.value +} + +func (v *NullableRelationshipTupleBlockRead) Set(val *RelationshipTupleBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleBlockRead(val *RelationshipTupleBlockRead) *NullableRelationshipTupleBlockRead { + return &NullableRelationshipTupleBlockRead{value: val, isSet: true} +} + +func (v NullableRelationshipTupleBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create.go new file mode 100644 index 00000000..6681be95 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create.go @@ -0,0 +1,209 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationshipTupleCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleCreate{} + +// RelationshipTupleCreate struct for RelationshipTupleCreate +type RelationshipTupleCreate struct { + // the resource instance assigned the new relation (accepts either the resource instance id or resource_key:resource_instance_key) + Subject string `json:"subject"` + // the relation to assign between the subject and object + Relation string `json:"relation"` + // the resource instance on which the new relation is assigned (accepts either the resource instance id or resource_key:resource_instance_key) + Object string `json:"object"` + // The tenant the subject and object belong to, if the resource instances don't exist yet, the tenant is required to create them. otherwise it is ignored + Tenant *string `json:"tenant,omitempty"` +} + +// NewRelationshipTupleCreate instantiates a new RelationshipTupleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleCreate(subject string, relation string, object string) *RelationshipTupleCreate { + this := RelationshipTupleCreate{} + this.Subject = subject + this.Relation = relation + this.Object = object + return &this +} + +// NewRelationshipTupleCreateWithDefaults instantiates a new RelationshipTupleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleCreateWithDefaults() *RelationshipTupleCreate { + this := RelationshipTupleCreate{} + return &this +} + +// GetSubject returns the Subject field value +func (o *RelationshipTupleCreate) GetSubject() string { + if o == nil { + var ret string + return ret + } + + return o.Subject +} + +// GetSubjectOk returns a tuple with the Subject field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleCreate) GetSubjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Subject, true +} + +// SetSubject sets field value +func (o *RelationshipTupleCreate) SetSubject(v string) { + o.Subject = v +} + +// GetRelation returns the Relation field value +func (o *RelationshipTupleCreate) GetRelation() string { + if o == nil { + var ret string + return ret + } + + return o.Relation +} + +// GetRelationOk returns a tuple with the Relation field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleCreate) GetRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Relation, true +} + +// SetRelation sets field value +func (o *RelationshipTupleCreate) SetRelation(v string) { + o.Relation = v +} + +// GetObject returns the Object field value +func (o *RelationshipTupleCreate) GetObject() string { + if o == nil { + var ret string + return ret + } + + return o.Object +} + +// GetObjectOk returns a tuple with the Object field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleCreate) GetObjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Object, true +} + +// SetObject sets field value +func (o *RelationshipTupleCreate) SetObject(v string) { + o.Object = v +} + +// GetTenant returns the Tenant field value if set, zero value otherwise. +func (o *RelationshipTupleCreate) GetTenant() string { + if o == nil || IsNil(o.Tenant) { + var ret string + return ret + } + return *o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationshipTupleCreate) GetTenantOk() (*string, bool) { + if o == nil || IsNil(o.Tenant) { + return nil, false + } + return o.Tenant, true +} + +// HasTenant returns a boolean if a field has been set. +func (o *RelationshipTupleCreate) HasTenant() bool { + if o != nil && !IsNil(o.Tenant) { + return true + } + + return false +} + +// SetTenant gets a reference to the given string and assigns it to the Tenant field. +func (o *RelationshipTupleCreate) SetTenant(v string) { + o.Tenant = &v +} + +func (o RelationshipTupleCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["subject"] = o.Subject + toSerialize["relation"] = o.Relation + toSerialize["object"] = o.Object + if !IsNil(o.Tenant) { + toSerialize["tenant"] = o.Tenant + } + return toSerialize, nil +} + +type NullableRelationshipTupleCreate struct { + value *RelationshipTupleCreate + isSet bool +} + +func (v NullableRelationshipTupleCreate) Get() *RelationshipTupleCreate { + return v.value +} + +func (v *NullableRelationshipTupleCreate) Set(val *RelationshipTupleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleCreate(val *RelationshipTupleCreate) *NullableRelationshipTupleCreate { + return &NullableRelationshipTupleCreate{value: val, isSet: true} +} + +func (v NullableRelationshipTupleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create_bulk_operation.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create_bulk_operation.go new file mode 100644 index 00000000..49f1e2b2 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_create_bulk_operation.go @@ -0,0 +1,115 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationshipTupleCreateBulkOperation type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleCreateBulkOperation{} + +// RelationshipTupleCreateBulkOperation struct for RelationshipTupleCreateBulkOperation +type RelationshipTupleCreateBulkOperation struct { + Operations []RelationshipTupleCreate `json:"operations"` +} + +// NewRelationshipTupleCreateBulkOperation instantiates a new RelationshipTupleCreateBulkOperation object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleCreateBulkOperation(operations []RelationshipTupleCreate) *RelationshipTupleCreateBulkOperation { + this := RelationshipTupleCreateBulkOperation{} + this.Operations = operations + return &this +} + +// NewRelationshipTupleCreateBulkOperationWithDefaults instantiates a new RelationshipTupleCreateBulkOperation object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleCreateBulkOperationWithDefaults() *RelationshipTupleCreateBulkOperation { + this := RelationshipTupleCreateBulkOperation{} + return &this +} + +// GetOperations returns the Operations field value +func (o *RelationshipTupleCreateBulkOperation) GetOperations() []RelationshipTupleCreate { + if o == nil { + var ret []RelationshipTupleCreate + return ret + } + + return o.Operations +} + +// GetOperationsOk returns a tuple with the Operations field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleCreateBulkOperation) GetOperationsOk() ([]RelationshipTupleCreate, bool) { + if o == nil { + return nil, false + } + return o.Operations, true +} + +// SetOperations sets field value +func (o *RelationshipTupleCreateBulkOperation) SetOperations(v []RelationshipTupleCreate) { + o.Operations = v +} + +func (o RelationshipTupleCreateBulkOperation) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleCreateBulkOperation) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["operations"] = o.Operations + return toSerialize, nil +} + +type NullableRelationshipTupleCreateBulkOperation struct { + value *RelationshipTupleCreateBulkOperation + isSet bool +} + +func (v NullableRelationshipTupleCreateBulkOperation) Get() *RelationshipTupleCreateBulkOperation { + return v.value +} + +func (v *NullableRelationshipTupleCreateBulkOperation) Set(val *RelationshipTupleCreateBulkOperation) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleCreateBulkOperation) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleCreateBulkOperation) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleCreateBulkOperation(val *RelationshipTupleCreateBulkOperation) *NullableRelationshipTupleCreateBulkOperation { + return &NullableRelationshipTupleCreateBulkOperation{value: val, isSet: true} +} + +func (v NullableRelationshipTupleCreateBulkOperation) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleCreateBulkOperation) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete.go new file mode 100644 index 00000000..8456925d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete.go @@ -0,0 +1,172 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationshipTupleDelete type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleDelete{} + +// RelationshipTupleDelete struct for RelationshipTupleDelete +type RelationshipTupleDelete struct { + // the resource instance assigned the new relation (accepts either the resource instance id or resource_key:resource_instance_key) + Subject string `json:"subject"` + // the relation to assign between the subject and object + Relation string `json:"relation"` + // the resource instance on which the new relation is assigned (accepts either the resource instance id or resource_key:resource_instance_key) + Object string `json:"object"` +} + +// NewRelationshipTupleDelete instantiates a new RelationshipTupleDelete object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleDelete(subject string, relation string, object string) *RelationshipTupleDelete { + this := RelationshipTupleDelete{} + this.Subject = subject + this.Relation = relation + this.Object = object + return &this +} + +// NewRelationshipTupleDeleteWithDefaults instantiates a new RelationshipTupleDelete object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleDeleteWithDefaults() *RelationshipTupleDelete { + this := RelationshipTupleDelete{} + return &this +} + +// GetSubject returns the Subject field value +func (o *RelationshipTupleDelete) GetSubject() string { + if o == nil { + var ret string + return ret + } + + return o.Subject +} + +// GetSubjectOk returns a tuple with the Subject field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleDelete) GetSubjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Subject, true +} + +// SetSubject sets field value +func (o *RelationshipTupleDelete) SetSubject(v string) { + o.Subject = v +} + +// GetRelation returns the Relation field value +func (o *RelationshipTupleDelete) GetRelation() string { + if o == nil { + var ret string + return ret + } + + return o.Relation +} + +// GetRelationOk returns a tuple with the Relation field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleDelete) GetRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Relation, true +} + +// SetRelation sets field value +func (o *RelationshipTupleDelete) SetRelation(v string) { + o.Relation = v +} + +// GetObject returns the Object field value +func (o *RelationshipTupleDelete) GetObject() string { + if o == nil { + var ret string + return ret + } + + return o.Object +} + +// GetObjectOk returns a tuple with the Object field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleDelete) GetObjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Object, true +} + +// SetObject sets field value +func (o *RelationshipTupleDelete) SetObject(v string) { + o.Object = v +} + +func (o RelationshipTupleDelete) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleDelete) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["subject"] = o.Subject + toSerialize["relation"] = o.Relation + toSerialize["object"] = o.Object + return toSerialize, nil +} + +type NullableRelationshipTupleDelete struct { + value *RelationshipTupleDelete + isSet bool +} + +func (v NullableRelationshipTupleDelete) Get() *RelationshipTupleDelete { + return v.value +} + +func (v *NullableRelationshipTupleDelete) Set(val *RelationshipTupleDelete) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleDelete) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleDelete) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleDelete(val *RelationshipTupleDelete) *NullableRelationshipTupleDelete { + return &NullableRelationshipTupleDelete{value: val, isSet: true} +} + +func (v NullableRelationshipTupleDelete) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleDelete) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete_bulk_operation.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete_bulk_operation.go new file mode 100644 index 00000000..2e1a46e9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_delete_bulk_operation.go @@ -0,0 +1,115 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationshipTupleDeleteBulkOperation type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleDeleteBulkOperation{} + +// RelationshipTupleDeleteBulkOperation struct for RelationshipTupleDeleteBulkOperation +type RelationshipTupleDeleteBulkOperation struct { + Idents []RelationshipTupleDelete `json:"idents"` +} + +// NewRelationshipTupleDeleteBulkOperation instantiates a new RelationshipTupleDeleteBulkOperation object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleDeleteBulkOperation(idents []RelationshipTupleDelete) *RelationshipTupleDeleteBulkOperation { + this := RelationshipTupleDeleteBulkOperation{} + this.Idents = idents + return &this +} + +// NewRelationshipTupleDeleteBulkOperationWithDefaults instantiates a new RelationshipTupleDeleteBulkOperation object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleDeleteBulkOperationWithDefaults() *RelationshipTupleDeleteBulkOperation { + this := RelationshipTupleDeleteBulkOperation{} + return &this +} + +// GetIdents returns the Idents field value +func (o *RelationshipTupleDeleteBulkOperation) GetIdents() []RelationshipTupleDelete { + if o == nil { + var ret []RelationshipTupleDelete + return ret + } + + return o.Idents +} + +// GetIdentsOk returns a tuple with the Idents field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleDeleteBulkOperation) GetIdentsOk() ([]RelationshipTupleDelete, bool) { + if o == nil { + return nil, false + } + return o.Idents, true +} + +// SetIdents sets field value +func (o *RelationshipTupleDeleteBulkOperation) SetIdents(v []RelationshipTupleDelete) { + o.Idents = v +} + +func (o RelationshipTupleDeleteBulkOperation) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleDeleteBulkOperation) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["idents"] = o.Idents + return toSerialize, nil +} + +type NullableRelationshipTupleDeleteBulkOperation struct { + value *RelationshipTupleDeleteBulkOperation + isSet bool +} + +func (v NullableRelationshipTupleDeleteBulkOperation) Get() *RelationshipTupleDeleteBulkOperation { + return v.value +} + +func (v *NullableRelationshipTupleDeleteBulkOperation) Set(val *RelationshipTupleDeleteBulkOperation) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleDeleteBulkOperation) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleDeleteBulkOperation) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleDeleteBulkOperation(val *RelationshipTupleDeleteBulkOperation) *NullableRelationshipTupleDeleteBulkOperation { + return &NullableRelationshipTupleDeleteBulkOperation{value: val, isSet: true} +} + +func (v NullableRelationshipTupleDeleteBulkOperation) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleDeleteBulkOperation) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_obj.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_obj.go new file mode 100644 index 00000000..ea7e65dc --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_obj.go @@ -0,0 +1,169 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RelationshipTupleObj type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleObj{} + +// RelationshipTupleObj struct for RelationshipTupleObj +type RelationshipTupleObj struct { + SubjectStr string `json:"subject_str"` + RelationStr string `json:"relation_str"` + ObjectStr string `json:"object_str"` +} + +// NewRelationshipTupleObj instantiates a new RelationshipTupleObj object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleObj(subjectStr string, relationStr string, objectStr string) *RelationshipTupleObj { + this := RelationshipTupleObj{} + this.SubjectStr = subjectStr + this.RelationStr = relationStr + this.ObjectStr = objectStr + return &this +} + +// NewRelationshipTupleObjWithDefaults instantiates a new RelationshipTupleObj object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleObjWithDefaults() *RelationshipTupleObj { + this := RelationshipTupleObj{} + return &this +} + +// GetSubjectStr returns the SubjectStr field value +func (o *RelationshipTupleObj) GetSubjectStr() string { + if o == nil { + var ret string + return ret + } + + return o.SubjectStr +} + +// GetSubjectStrOk returns a tuple with the SubjectStr field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleObj) GetSubjectStrOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SubjectStr, true +} + +// SetSubjectStr sets field value +func (o *RelationshipTupleObj) SetSubjectStr(v string) { + o.SubjectStr = v +} + +// GetRelationStr returns the RelationStr field value +func (o *RelationshipTupleObj) GetRelationStr() string { + if o == nil { + var ret string + return ret + } + + return o.RelationStr +} + +// GetRelationStrOk returns a tuple with the RelationStr field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleObj) GetRelationStrOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RelationStr, true +} + +// SetRelationStr sets field value +func (o *RelationshipTupleObj) SetRelationStr(v string) { + o.RelationStr = v +} + +// GetObjectStr returns the ObjectStr field value +func (o *RelationshipTupleObj) GetObjectStr() string { + if o == nil { + var ret string + return ret + } + + return o.ObjectStr +} + +// GetObjectStrOk returns a tuple with the ObjectStr field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleObj) GetObjectStrOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ObjectStr, true +} + +// SetObjectStr sets field value +func (o *RelationshipTupleObj) SetObjectStr(v string) { + o.ObjectStr = v +} + +func (o RelationshipTupleObj) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleObj) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["subject_str"] = o.SubjectStr + toSerialize["relation_str"] = o.RelationStr + toSerialize["object_str"] = o.ObjectStr + return toSerialize, nil +} + +type NullableRelationshipTupleObj struct { + value *RelationshipTupleObj + isSet bool +} + +func (v NullableRelationshipTupleObj) Get() *RelationshipTupleObj { + return v.value +} + +func (v *NullableRelationshipTupleObj) Set(val *RelationshipTupleObj) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleObj) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleObj) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleObj(val *RelationshipTupleObj) *NullableRelationshipTupleObj { + return &NullableRelationshipTupleObj{value: val, isSet: true} +} + +func (v NullableRelationshipTupleObj) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleObj) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_read.go new file mode 100644 index 00000000..2ea7503c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_relationship_tuple_read.go @@ -0,0 +1,625 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the RelationshipTupleRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RelationshipTupleRead{} + +// RelationshipTupleRead struct for RelationshipTupleRead +type RelationshipTupleRead struct { + // resource_key:resource_instance_key of the subject + Subject string `json:"subject"` + // key of the assigned relation + Relation string `json:"relation"` + // resource_key:resource_instance_key of the object + Object string `json:"object"` + // Unique id of the relationship tuple + Id string `json:"id"` + // The tenant the relationship tuple is associated with + Tenant string `json:"tenant"` + // Unique id of the subject + SubjectId string `json:"subject_id"` + // Unique id of the relation + RelationId string `json:"relation_id"` + // Unique id of the object + ObjectId string `json:"object_id"` + // Unique id of the tenant + TenantId string `json:"tenant_id"` + // Unique id of the organization that the relationship tuple belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the relationship tuple belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the relationship tuple belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the relationship tuple was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the relationship tuple was created (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + SubjectDetails *ResourceInstanceBlockRead `json:"subject_details,omitempty"` + RelationDetails *StrippedRelationBlockRead `json:"relation_details,omitempty"` + ObjectDetails *ResourceInstanceBlockRead `json:"object_details,omitempty"` + TenantDetails *TenantBlockRead `json:"tenant_details,omitempty"` +} + +// NewRelationshipTupleRead instantiates a new RelationshipTupleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRelationshipTupleRead(subject string, relation string, object string, id string, tenant string, subjectId string, relationId string, objectId string, tenantId string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time) *RelationshipTupleRead { + this := RelationshipTupleRead{} + this.Subject = subject + this.Relation = relation + this.Object = object + this.Id = id + this.Tenant = tenant + this.SubjectId = subjectId + this.RelationId = relationId + this.ObjectId = objectId + this.TenantId = tenantId + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewRelationshipTupleReadWithDefaults instantiates a new RelationshipTupleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRelationshipTupleReadWithDefaults() *RelationshipTupleRead { + this := RelationshipTupleRead{} + return &this +} + +// GetSubject returns the Subject field value +func (o *RelationshipTupleRead) GetSubject() string { + if o == nil { + var ret string + return ret + } + + return o.Subject +} + +// GetSubjectOk returns a tuple with the Subject field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetSubjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Subject, true +} + +// SetSubject sets field value +func (o *RelationshipTupleRead) SetSubject(v string) { + o.Subject = v +} + +// GetRelation returns the Relation field value +func (o *RelationshipTupleRead) GetRelation() string { + if o == nil { + var ret string + return ret + } + + return o.Relation +} + +// GetRelationOk returns a tuple with the Relation field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetRelationOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Relation, true +} + +// SetRelation sets field value +func (o *RelationshipTupleRead) SetRelation(v string) { + o.Relation = v +} + +// GetObject returns the Object field value +func (o *RelationshipTupleRead) GetObject() string { + if o == nil { + var ret string + return ret + } + + return o.Object +} + +// GetObjectOk returns a tuple with the Object field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetObjectOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Object, true +} + +// SetObject sets field value +func (o *RelationshipTupleRead) SetObject(v string) { + o.Object = v +} + +// GetId returns the Id field value +func (o *RelationshipTupleRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RelationshipTupleRead) SetId(v string) { + o.Id = v +} + +// GetTenant returns the Tenant field value +func (o *RelationshipTupleRead) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *RelationshipTupleRead) SetTenant(v string) { + o.Tenant = v +} + +// GetSubjectId returns the SubjectId field value +func (o *RelationshipTupleRead) GetSubjectId() string { + if o == nil { + var ret string + return ret + } + + return o.SubjectId +} + +// GetSubjectIdOk returns a tuple with the SubjectId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetSubjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.SubjectId, true +} + +// SetSubjectId sets field value +func (o *RelationshipTupleRead) SetSubjectId(v string) { + o.SubjectId = v +} + +// GetRelationId returns the RelationId field value +func (o *RelationshipTupleRead) GetRelationId() string { + if o == nil { + var ret string + return ret + } + + return o.RelationId +} + +// GetRelationIdOk returns a tuple with the RelationId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetRelationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RelationId, true +} + +// SetRelationId sets field value +func (o *RelationshipTupleRead) SetRelationId(v string) { + o.RelationId = v +} + +// GetObjectId returns the ObjectId field value +func (o *RelationshipTupleRead) GetObjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ObjectId +} + +// GetObjectIdOk returns a tuple with the ObjectId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetObjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ObjectId, true +} + +// SetObjectId sets field value +func (o *RelationshipTupleRead) SetObjectId(v string) { + o.ObjectId = v +} + +// GetTenantId returns the TenantId field value +func (o *RelationshipTupleRead) GetTenantId() string { + if o == nil { + var ret string + return ret + } + + return o.TenantId +} + +// GetTenantIdOk returns a tuple with the TenantId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetTenantIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.TenantId, true +} + +// SetTenantId sets field value +func (o *RelationshipTupleRead) SetTenantId(v string) { + o.TenantId = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *RelationshipTupleRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *RelationshipTupleRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *RelationshipTupleRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *RelationshipTupleRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *RelationshipTupleRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *RelationshipTupleRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *RelationshipTupleRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *RelationshipTupleRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *RelationshipTupleRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *RelationshipTupleRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetSubjectDetails returns the SubjectDetails field value if set, zero value otherwise. +func (o *RelationshipTupleRead) GetSubjectDetails() ResourceInstanceBlockRead { + if o == nil || IsNil(o.SubjectDetails) { + var ret ResourceInstanceBlockRead + return ret + } + return *o.SubjectDetails +} + +// GetSubjectDetailsOk returns a tuple with the SubjectDetails field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetSubjectDetailsOk() (*ResourceInstanceBlockRead, bool) { + if o == nil || IsNil(o.SubjectDetails) { + return nil, false + } + return o.SubjectDetails, true +} + +// HasSubjectDetails returns a boolean if a field has been set. +func (o *RelationshipTupleRead) HasSubjectDetails() bool { + if o != nil && !IsNil(o.SubjectDetails) { + return true + } + + return false +} + +// SetSubjectDetails gets a reference to the given ResourceInstanceBlockRead and assigns it to the SubjectDetails field. +func (o *RelationshipTupleRead) SetSubjectDetails(v ResourceInstanceBlockRead) { + o.SubjectDetails = &v +} + +// GetRelationDetails returns the RelationDetails field value if set, zero value otherwise. +func (o *RelationshipTupleRead) GetRelationDetails() StrippedRelationBlockRead { + if o == nil || IsNil(o.RelationDetails) { + var ret StrippedRelationBlockRead + return ret + } + return *o.RelationDetails +} + +// GetRelationDetailsOk returns a tuple with the RelationDetails field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetRelationDetailsOk() (*StrippedRelationBlockRead, bool) { + if o == nil || IsNil(o.RelationDetails) { + return nil, false + } + return o.RelationDetails, true +} + +// HasRelationDetails returns a boolean if a field has been set. +func (o *RelationshipTupleRead) HasRelationDetails() bool { + if o != nil && !IsNil(o.RelationDetails) { + return true + } + + return false +} + +// SetRelationDetails gets a reference to the given StrippedRelationBlockRead and assigns it to the RelationDetails field. +func (o *RelationshipTupleRead) SetRelationDetails(v StrippedRelationBlockRead) { + o.RelationDetails = &v +} + +// GetObjectDetails returns the ObjectDetails field value if set, zero value otherwise. +func (o *RelationshipTupleRead) GetObjectDetails() ResourceInstanceBlockRead { + if o == nil || IsNil(o.ObjectDetails) { + var ret ResourceInstanceBlockRead + return ret + } + return *o.ObjectDetails +} + +// GetObjectDetailsOk returns a tuple with the ObjectDetails field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetObjectDetailsOk() (*ResourceInstanceBlockRead, bool) { + if o == nil || IsNil(o.ObjectDetails) { + return nil, false + } + return o.ObjectDetails, true +} + +// HasObjectDetails returns a boolean if a field has been set. +func (o *RelationshipTupleRead) HasObjectDetails() bool { + if o != nil && !IsNil(o.ObjectDetails) { + return true + } + + return false +} + +// SetObjectDetails gets a reference to the given ResourceInstanceBlockRead and assigns it to the ObjectDetails field. +func (o *RelationshipTupleRead) SetObjectDetails(v ResourceInstanceBlockRead) { + o.ObjectDetails = &v +} + +// GetTenantDetails returns the TenantDetails field value if set, zero value otherwise. +func (o *RelationshipTupleRead) GetTenantDetails() TenantBlockRead { + if o == nil || IsNil(o.TenantDetails) { + var ret TenantBlockRead + return ret + } + return *o.TenantDetails +} + +// GetTenantDetailsOk returns a tuple with the TenantDetails field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RelationshipTupleRead) GetTenantDetailsOk() (*TenantBlockRead, bool) { + if o == nil || IsNil(o.TenantDetails) { + return nil, false + } + return o.TenantDetails, true +} + +// HasTenantDetails returns a boolean if a field has been set. +func (o *RelationshipTupleRead) HasTenantDetails() bool { + if o != nil && !IsNil(o.TenantDetails) { + return true + } + + return false +} + +// SetTenantDetails gets a reference to the given TenantBlockRead and assigns it to the TenantDetails field. +func (o *RelationshipTupleRead) SetTenantDetails(v TenantBlockRead) { + o.TenantDetails = &v +} + +func (o RelationshipTupleRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RelationshipTupleRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["subject"] = o.Subject + toSerialize["relation"] = o.Relation + toSerialize["object"] = o.Object + toSerialize["id"] = o.Id + toSerialize["tenant"] = o.Tenant + toSerialize["subject_id"] = o.SubjectId + toSerialize["relation_id"] = o.RelationId + toSerialize["object_id"] = o.ObjectId + toSerialize["tenant_id"] = o.TenantId + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + if !IsNil(o.SubjectDetails) { + toSerialize["subject_details"] = o.SubjectDetails + } + if !IsNil(o.RelationDetails) { + toSerialize["relation_details"] = o.RelationDetails + } + if !IsNil(o.ObjectDetails) { + toSerialize["object_details"] = o.ObjectDetails + } + if !IsNil(o.TenantDetails) { + toSerialize["tenant_details"] = o.TenantDetails + } + return toSerialize, nil +} + +type NullableRelationshipTupleRead struct { + value *RelationshipTupleRead + isSet bool +} + +func (v NullableRelationshipTupleRead) Get() *RelationshipTupleRead { + return v.value +} + +func (v *NullableRelationshipTupleRead) Set(val *RelationshipTupleRead) { + v.value = val + v.isSet = true +} + +func (v NullableRelationshipTupleRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRelationshipTupleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRelationshipTupleRead(val *RelationshipTupleRead) *NullableRelationshipTupleRead { + return &NullableRelationshipTupleRead{value: val, isSet: true} +} + +func (v NullableRelationshipTupleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRelationshipTupleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_remote_config.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_remote_config.go new file mode 100644 index 00000000..4535a267 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_remote_config.go @@ -0,0 +1,211 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// RemoteConfig struct for RemoteConfig +type RemoteConfig struct { + OpalCommon map[string]interface{} `json:"opal_common,omitempty"` + OpalClient OPALClient `json:"opal_client"` + Pdp *Pdp `json:"pdp,omitempty"` + Context PDPContext `json:"context"` +} + +// NewRemoteConfig instantiates a new RemoteConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +//func NewRemoteConfig(opalClient OPALClient, context PDPContext) *RemoteConfig { +// this := RemoteConfig{} +// this.OpalClient = opalClient +// var pdp Pdp = Pdp{} +// this.Pdp = &pdp +// this.Context = context +// return &this +//} + +// NewRemoteConfigWithDefaults instantiates a new RemoteConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +//func NewRemoteConfigWithDefaults() *RemoteConfig { +// this := RemoteConfig{} +// var pdp Pdp = {} +// this.Pdp = &pdp +// return &this +//} + +// GetOpalCommon returns the OpalCommon field value if set, zero value otherwise. +func (o *RemoteConfig) GetOpalCommon() map[string]interface{} { + if o == nil || IsNil(o.OpalCommon) { + var ret map[string]interface{} + return ret + } + return o.OpalCommon +} + +// GetOpalCommonOk returns a tuple with the OpalCommon field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RemoteConfig) GetOpalCommonOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.OpalCommon) { + return map[string]interface{}{}, false + } + return o.OpalCommon, true +} + +// HasOpalCommon returns a boolean if a field has been set. +func (o *RemoteConfig) HasOpalCommon() bool { + if o != nil && !IsNil(o.OpalCommon) { + return true + } + + return false +} + +// SetOpalCommon gets a reference to the given map[string]interface{} and assigns it to the OpalCommon field. +func (o *RemoteConfig) SetOpalCommon(v map[string]interface{}) { + o.OpalCommon = v +} + +// GetOpalClient returns the OpalClient field value +func (o *RemoteConfig) GetOpalClient() OPALClient { + if o == nil { + var ret OPALClient + return ret + } + + return o.OpalClient +} + +// GetOpalClientOk returns a tuple with the OpalClient field value +// and a boolean to check if the value has been set. +func (o *RemoteConfig) GetOpalClientOk() (*OPALClient, bool) { + if o == nil { + return nil, false + } + return &o.OpalClient, true +} + +// SetOpalClient sets field value +func (o *RemoteConfig) SetOpalClient(v OPALClient) { + o.OpalClient = v +} + +// GetPdp returns the Pdp field value if set, zero value otherwise. +func (o *RemoteConfig) GetPdp() Pdp { + if o == nil || IsNil(o.Pdp) { + var ret Pdp + return ret + } + return *o.Pdp +} + +// GetPdpOk returns a tuple with the Pdp field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RemoteConfig) GetPdpOk() (*Pdp, bool) { + if o == nil || IsNil(o.Pdp) { + return nil, false + } + return o.Pdp, true +} + +// HasPdp returns a boolean if a field has been set. +func (o *RemoteConfig) HasPdp() bool { + if o != nil && !IsNil(o.Pdp) { + return true + } + + return false +} + +// SetPdp gets a reference to the given Pdp and assigns it to the Pdp field. +func (o *RemoteConfig) SetPdp(v Pdp) { + o.Pdp = &v +} + +// GetContext returns the Context field value +func (o *RemoteConfig) GetContext() PDPContext { + if o == nil { + var ret PDPContext + return ret + } + + return o.Context +} + +// GetContextOk returns a tuple with the Context field value +// and a boolean to check if the value has been set. +func (o *RemoteConfig) GetContextOk() (*PDPContext, bool) { + if o == nil { + return nil, false + } + return &o.Context, true +} + +// SetContext sets field value +func (o *RemoteConfig) SetContext(v PDPContext) { + o.Context = v +} + +func (o RemoteConfig) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.OpalCommon) { + toSerialize["opal_common"] = o.OpalCommon + } + if true { + toSerialize["opal_client"] = o.OpalClient + } + if !IsNil(o.Pdp) { + toSerialize["pdp"] = o.Pdp + } + if true { + toSerialize["context"] = o.Context + } + return json.Marshal(toSerialize) +} + +type NullableRemoteConfig struct { + value *RemoteConfig + isSet bool +} + +func (v NullableRemoteConfig) Get() *RemoteConfig { + return v.value +} + +func (v *NullableRemoteConfig) Set(val *RemoteConfig) { + v.value = val + v.isSet = true +} + +func (v NullableRemoteConfig) IsSet() bool { + return v.isSet +} + +func (v *NullableRemoteConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRemoteConfig(val *RemoteConfig) *NullableRemoteConfig { + return &NullableRemoteConfig{value: val, isSet: true} +} + +func (v NullableRemoteConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRemoteConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_remove_role_permissions.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_remove_role_permissions.go new file mode 100644 index 00000000..dd64d832 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_remove_role_permissions.go @@ -0,0 +1,107 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// RemoveRolePermissions struct for RemoveRolePermissions +type RemoveRolePermissions struct { + // List of permissions to remove from the role. If a permission is not found it is skipped. Each permission can be either a resource action id, or `{resource_key}:{action_key}`,i.e: the \"permission name\". + Permissions []string `json:"permissions"` +} + +// NewRemoveRolePermissions instantiates a new RemoveRolePermissions object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRemoveRolePermissions(permissions []string) *RemoveRolePermissions { + this := RemoveRolePermissions{} + this.Permissions = permissions + return &this +} + +// NewRemoveRolePermissionsWithDefaults instantiates a new RemoveRolePermissions object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRemoveRolePermissionsWithDefaults() *RemoveRolePermissions { + this := RemoveRolePermissions{} + return &this +} + +// GetPermissions returns the Permissions field value +func (o *RemoveRolePermissions) GetPermissions() []string { + if o == nil { + var ret []string + return ret + } + + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value +// and a boolean to check if the value has been set. +func (o *RemoveRolePermissions) GetPermissionsOk() ([]string, bool) { + if o == nil { + return nil, false + } + return o.Permissions, true +} + +// SetPermissions sets field value +func (o *RemoveRolePermissions) SetPermissions(v []string) { + o.Permissions = v +} + +func (o RemoveRolePermissions) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["permissions"] = o.Permissions + } + return json.Marshal(toSerialize) +} + +type NullableRemoveRolePermissions struct { + value *RemoveRolePermissions + isSet bool +} + +func (v NullableRemoveRolePermissions) Get() *RemoveRolePermissions { + return v.value +} + +func (v *NullableRemoveRolePermissions) Set(val *RemoveRolePermissions) { + v.value = val + v.isSet = true +} + +func (v NullableRemoveRolePermissions) IsSet() bool { + return v.isSet +} + +func (v *NullableRemoveRolePermissions) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRemoveRolePermissions(val *RemoveRolePermissions) *NullableRemoveRolePermissions { + return &NullableRemoveRolePermissions{value: val, isSet: true} +} + +func (v NullableRemoveRolePermissions) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRemoveRolePermissions) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_create.go new file mode 100644 index 00000000..94f7101b --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_create.go @@ -0,0 +1,218 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ResourceActionCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceActionCreate{} + +// ResourceActionCreate struct for ResourceActionCreate +type ResourceActionCreate struct { + // A URL-friendly name of the action (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the action. + Key string `json:"key"` + // The name of the action + Name string `json:"name"` + // An optional longer description of what this action respresents in your system + Description *string `json:"description,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this action. This metadata can be used to filter actions using query parameters with attr_ prefix + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewResourceActionCreate instantiates a new ResourceActionCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceActionCreate(key string, name string) *ResourceActionCreate { + this := ResourceActionCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewResourceActionCreateWithDefaults instantiates a new ResourceActionCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceActionCreateWithDefaults() *ResourceActionCreate { + this := ResourceActionCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceActionCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceActionCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceActionCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *ResourceActionCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceActionCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceActionCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceActionCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceActionCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceActionCreate) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceActionCreate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionCreate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceActionCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceActionCreate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ResourceActionCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceActionCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableResourceActionCreate struct { + value *ResourceActionCreate + isSet bool +} + +func (v NullableResourceActionCreate) Get() *ResourceActionCreate { + return v.value +} + +func (v *NullableResourceActionCreate) Set(val *ResourceActionCreate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceActionCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceActionCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceActionCreate(val *ResourceActionCreate) *NullableResourceActionCreate { + return &NullableResourceActionCreate{value: val, isSet: true} +} + +func (v NullableResourceActionCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceActionCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_create.go new file mode 100644 index 00000000..6d48a091 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_create.go @@ -0,0 +1,254 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ResourceActionGroupCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceActionGroupCreate{} + +// ResourceActionGroupCreate struct for ResourceActionGroupCreate +type ResourceActionGroupCreate struct { + // A URL-friendly name of the action group (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the action group. + Key string `json:"key"` + // The name of the action group + Name string `json:"name"` + // An optional longer description of what this action group represents in your system + Description *string `json:"description,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this action group. This metadata can be used to filter action groups using query parameters with attr_ prefix + Attributes map[string]interface{} `json:"attributes,omitempty"` + Actions []string `json:"actions,omitempty"` +} + +// NewResourceActionGroupCreate instantiates a new ResourceActionGroupCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceActionGroupCreate(key string, name string) *ResourceActionGroupCreate { + this := ResourceActionGroupCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewResourceActionGroupCreateWithDefaults instantiates a new ResourceActionGroupCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceActionGroupCreateWithDefaults() *ResourceActionGroupCreate { + this := ResourceActionGroupCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceActionGroupCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceActionGroupCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *ResourceActionGroupCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceActionGroupCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceActionGroupCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceActionGroupCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceActionGroupCreate) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceActionGroupCreate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupCreate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceActionGroupCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceActionGroupCreate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +// GetActions returns the Actions field value if set, zero value otherwise. +func (o *ResourceActionGroupCreate) GetActions() []string { + if o == nil || IsNil(o.Actions) { + var ret []string + return ret + } + return o.Actions +} + +// GetActionsOk returns a tuple with the Actions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupCreate) GetActionsOk() ([]string, bool) { + if o == nil || IsNil(o.Actions) { + return nil, false + } + return o.Actions, true +} + +// HasActions returns a boolean if a field has been set. +func (o *ResourceActionGroupCreate) HasActions() bool { + if o != nil && !IsNil(o.Actions) { + return true + } + + return false +} + +// SetActions gets a reference to the given []string and assigns it to the Actions field. +func (o *ResourceActionGroupCreate) SetActions(v []string) { + o.Actions = v +} + +func (o ResourceActionGroupCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceActionGroupCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + if !IsNil(o.Actions) { + toSerialize["actions"] = o.Actions + } + return toSerialize, nil +} + +type NullableResourceActionGroupCreate struct { + value *ResourceActionGroupCreate + isSet bool +} + +func (v NullableResourceActionGroupCreate) Get() *ResourceActionGroupCreate { + return v.value +} + +func (v *NullableResourceActionGroupCreate) Set(val *ResourceActionGroupCreate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceActionGroupCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceActionGroupCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceActionGroupCreate(val *ResourceActionGroupCreate) *NullableResourceActionGroupCreate { + return &NullableResourceActionGroupCreate{value: val, isSet: true} +} + +func (v NullableResourceActionGroupCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceActionGroupCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_read.go new file mode 100644 index 00000000..e9accd3b --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_group_read.go @@ -0,0 +1,451 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the ResourceActionGroupRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceActionGroupRead{} + +// ResourceActionGroupRead struct for ResourceActionGroupRead +type ResourceActionGroupRead struct { + // The name of the action group + Name string `json:"name"` + // An optional longer description of what this action group represents in your system + Description *string `json:"description,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this action group. This metadata can be used to filter action groups using query parameters with attr_ prefix + Attributes map[string]interface{} `json:"attributes,omitempty"` + Actions []string `json:"actions,omitempty"` + // A URL-friendly name of the action group (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the action group. + Key string `json:"key"` + // Unique id of the action group + Id string `json:"id"` + // Unique id of the organization that the action group belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the action group belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the action group belongs to. + EnvironmentId string `json:"environment_id"` + // Unique id of the resource that the action group belongs to. + ResourceId string `json:"resource_id"` + // Date and time when the action group was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the action group was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` +} + +// NewResourceActionGroupRead instantiates a new ResourceActionGroupRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceActionGroupRead(name string, key string, id string, organizationId string, projectId string, environmentId string, resourceId string, createdAt time.Time, updatedAt time.Time) *ResourceActionGroupRead { + this := ResourceActionGroupRead{} + this.Name = name + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.ResourceId = resourceId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewResourceActionGroupReadWithDefaults instantiates a new ResourceActionGroupRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceActionGroupReadWithDefaults() *ResourceActionGroupRead { + this := ResourceActionGroupRead{} + return &this +} + +// GetName returns the Name field value +func (o *ResourceActionGroupRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceActionGroupRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceActionGroupRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceActionGroupRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceActionGroupRead) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceActionGroupRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceActionGroupRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceActionGroupRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +// GetActions returns the Actions field value if set, zero value otherwise. +func (o *ResourceActionGroupRead) GetActions() []string { + if o == nil || IsNil(o.Actions) { + var ret []string + return ret + } + return o.Actions +} + +// GetActionsOk returns a tuple with the Actions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetActionsOk() ([]string, bool) { + if o == nil || IsNil(o.Actions) { + return nil, false + } + return o.Actions, true +} + +// HasActions returns a boolean if a field has been set. +func (o *ResourceActionGroupRead) HasActions() bool { + if o != nil && !IsNil(o.Actions) { + return true + } + + return false +} + +// SetActions gets a reference to the given []string and assigns it to the Actions field. +func (o *ResourceActionGroupRead) SetActions(v []string) { + o.Actions = v +} + +// GetKey returns the Key field value +func (o *ResourceActionGroupRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceActionGroupRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ResourceActionGroupRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ResourceActionGroupRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ResourceActionGroupRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ResourceActionGroupRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ResourceActionGroupRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ResourceActionGroupRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ResourceActionGroupRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ResourceActionGroupRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetResourceId returns the ResourceId field value +func (o *ResourceActionGroupRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *ResourceActionGroupRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ResourceActionGroupRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ResourceActionGroupRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ResourceActionGroupRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceActionGroupRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ResourceActionGroupRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +func (o ResourceActionGroupRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceActionGroupRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + if !IsNil(o.Actions) { + toSerialize["actions"] = o.Actions + } + toSerialize["key"] = o.Key + toSerialize["id"] = o.Id + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["resource_id"] = o.ResourceId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + return toSerialize, nil +} + +type NullableResourceActionGroupRead struct { + value *ResourceActionGroupRead + isSet bool +} + +func (v NullableResourceActionGroupRead) Get() *ResourceActionGroupRead { + return v.value +} + +func (v *NullableResourceActionGroupRead) Set(val *ResourceActionGroupRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceActionGroupRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceActionGroupRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceActionGroupRead(val *ResourceActionGroupRead) *NullableResourceActionGroupRead { + return &NullableResourceActionGroupRead{value: val, isSet: true} +} + +func (v NullableResourceActionGroupRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceActionGroupRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_read.go new file mode 100644 index 00000000..95e88399 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_read.go @@ -0,0 +1,443 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// checks if the ResourceActionRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceActionRead{} + +// ResourceActionRead struct for ResourceActionRead +type ResourceActionRead struct { + // The name of the action + Name string `json:"name"` + // An optional longer description of what this action respresents in your system + Description *string `json:"description,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this action. This metadata can be used to filter actions using query parameters with attr_ prefix + Attributes map[string]interface{} `json:"attributes,omitempty"` + // A URL-friendly name of the action (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the action. + Key string `json:"key"` + // Unique id of the action + Id string `json:"id"` + // The name of the action, prefixed by the resource the action is acting upon. + PermissionName string `json:"permission_name"` + // Unique id of the organization that the action belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the action belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the action belongs to. + EnvironmentId string `json:"environment_id"` + // Unique id of the resource that the action belongs to. + ResourceId string `json:"resource_id"` + // Date and time when the action was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the action was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` +} + +// NewResourceActionRead instantiates a new ResourceActionRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceActionRead(name string, key string, id string, permissionName string, organizationId string, projectId string, environmentId string, resourceId string, createdAt time.Time, updatedAt time.Time) *ResourceActionRead { + this := ResourceActionRead{} + this.Name = name + this.Key = key + this.Id = id + this.PermissionName = permissionName + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.ResourceId = resourceId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewResourceActionReadWithDefaults instantiates a new ResourceActionRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceActionReadWithDefaults() *ResourceActionRead { + this := ResourceActionRead{} + return &this +} + +// GetName returns the Name field value +func (o *ResourceActionRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceActionRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceActionRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceActionRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceActionRead) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceActionRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceActionRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceActionRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +// GetKey returns the Key field value +func (o *ResourceActionRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceActionRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ResourceActionRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ResourceActionRead) SetId(v string) { + o.Id = v +} + +// GetPermissionName returns the PermissionName field value +func (o *ResourceActionRead) GetPermissionName() string { + if o == nil { + var ret string + return ret + } + + return o.PermissionName +} + +// GetPermissionNameOk returns a tuple with the PermissionName field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetPermissionNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PermissionName, true +} + +// SetPermissionName sets field value +func (o *ResourceActionRead) SetPermissionName(v string) { + o.PermissionName = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ResourceActionRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ResourceActionRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ResourceActionRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ResourceActionRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ResourceActionRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ResourceActionRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetResourceId returns the ResourceId field value +func (o *ResourceActionRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *ResourceActionRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ResourceActionRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ResourceActionRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ResourceActionRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceActionRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ResourceActionRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +func (o ResourceActionRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceActionRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + toSerialize["key"] = o.Key + toSerialize["id"] = o.Id + toSerialize["permission_name"] = o.PermissionName + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["resource_id"] = o.ResourceId + toSerialize["created_at"] = o.CreatedAt + toSerialize["updated_at"] = o.UpdatedAt + return toSerialize, nil +} + +type NullableResourceActionRead struct { + value *ResourceActionRead + isSet bool +} + +func (v NullableResourceActionRead) Get() *ResourceActionRead { + return v.value +} + +func (v *NullableResourceActionRead) Set(val *ResourceActionRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceActionRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceActionRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceActionRead(val *ResourceActionRead) *NullableResourceActionRead { + return &NullableResourceActionRead{value: val, isSet: true} +} + +func (v NullableResourceActionRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceActionRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_update.go new file mode 100644 index 00000000..d71164a0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_action_update.go @@ -0,0 +1,199 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ResourceActionUpdate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceActionUpdate{} + +// ResourceActionUpdate struct for ResourceActionUpdate +type ResourceActionUpdate struct { + // The name of the action + Name *string `json:"name,omitempty"` + // An optional longer description of what this action respresents in your system + Description *string `json:"description,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this action. This metadata can be used to filter actions using query parameters with attr_ prefix + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewResourceActionUpdate instantiates a new ResourceActionUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceActionUpdate() *ResourceActionUpdate { + this := ResourceActionUpdate{} + return &this +} + +// NewResourceActionUpdateWithDefaults instantiates a new ResourceActionUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceActionUpdateWithDefaults() *ResourceActionUpdate { + this := ResourceActionUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ResourceActionUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ResourceActionUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ResourceActionUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceActionUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceActionUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceActionUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceActionUpdate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceActionUpdate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceActionUpdate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceActionUpdate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ResourceActionUpdate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceActionUpdate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableResourceActionUpdate struct { + value *ResourceActionUpdate + isSet bool +} + +func (v NullableResourceActionUpdate) Get() *ResourceActionUpdate { + return v.value +} + +func (v *NullableResourceActionUpdate) Set(val *ResourceActionUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceActionUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceActionUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceActionUpdate(val *ResourceActionUpdate) *NullableResourceActionUpdate { + return &NullableResourceActionUpdate{value: val, isSet: true} +} + +func (v NullableResourceActionUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceActionUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_create.go new file mode 100644 index 00000000..cf0bc221 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_create.go @@ -0,0 +1,174 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceAttributeCreate struct for ResourceAttributeCreate +type ResourceAttributeCreate struct { + // A URL-friendly name of the attribute (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the attribute. + Key string `json:"key"` + // The type of the attribute, we currently support: `bool`, `number` (ints, floats), `time` (a timestamp), `string`, and `json`. + Type AttributeType `json:"type"` + // An optional longer description of what this attribute respresents in your system + Description *string `json:"description,omitempty"` +} + +// NewResourceAttributeCreate instantiates a new ResourceAttributeCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceAttributeCreate(key string, type_ AttributeType) *ResourceAttributeCreate { + this := ResourceAttributeCreate{} + this.Key = key + this.Type = type_ + return &this +} + +// NewResourceAttributeCreateWithDefaults instantiates a new ResourceAttributeCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceAttributeCreateWithDefaults() *ResourceAttributeCreate { + this := ResourceAttributeCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceAttributeCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceAttributeCreate) SetKey(v string) { + o.Key = v +} + +// GetType returns the Type field value +func (o *ResourceAttributeCreate) GetType() AttributeType { + if o == nil { + var ret AttributeType + return ret + } + + return o.Type +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeCreate) GetTypeOk() (*AttributeType, bool) { + if o == nil { + return nil, false + } + return &o.Type, true +} + +// SetType sets field value +func (o *ResourceAttributeCreate) SetType(v AttributeType) { + o.Type = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceAttributeCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceAttributeCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceAttributeCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceAttributeCreate) SetDescription(v string) { + o.Description = &v +} + +func (o ResourceAttributeCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["type"] = o.Type + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + return json.Marshal(toSerialize) +} + +type NullableResourceAttributeCreate struct { + value *ResourceAttributeCreate + isSet bool +} + +func (v NullableResourceAttributeCreate) Get() *ResourceAttributeCreate { + return v.value +} + +func (v *NullableResourceAttributeCreate) Set(val *ResourceAttributeCreate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceAttributeCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceAttributeCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceAttributeCreate(val *ResourceAttributeCreate) *NullableResourceAttributeCreate { + return &NullableResourceAttributeCreate{value: val, isSet: true} +} + +func (v NullableResourceAttributeCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceAttributeCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_read.go new file mode 100644 index 00000000..66ea542f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_read.go @@ -0,0 +1,415 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ResourceAttributeRead struct for ResourceAttributeRead +type ResourceAttributeRead struct { + // The type of the attribute, we currently support: `bool`, `number` (ints, floats), `time` (a timestamp), `string`, and `json`. + Type AttributeType `json:"type"` + // An optional longer description of what this attribute respresents in your system + Description *string `json:"description,omitempty"` + // A URL-friendly name of the attribute (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the attribute. + Key string `json:"key"` + // Unique id of the attribute + Id string `json:"id"` + // Unique id of the resource that the attribute belongs to. + ResourceId string `json:"resource_id"` + // A URL-friendly name of the resource (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the resource. + ResourceKey string `json:"resource_key"` + // Unique id of the organization that the attribute belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the attribute belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the attribute belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the attribute was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the attribute was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` +} + +// NewResourceAttributeRead instantiates a new ResourceAttributeRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceAttributeRead(type_ AttributeType, key string, id string, resourceId string, resourceKey string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time) *ResourceAttributeRead { + this := ResourceAttributeRead{} + this.Type = type_ + this.Key = key + this.Id = id + this.ResourceId = resourceId + this.ResourceKey = resourceKey + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewResourceAttributeReadWithDefaults instantiates a new ResourceAttributeRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceAttributeReadWithDefaults() *ResourceAttributeRead { + this := ResourceAttributeRead{} + return &this +} + +// GetType returns the Type field value +func (o *ResourceAttributeRead) GetType() AttributeType { + if o == nil { + var ret AttributeType + return ret + } + + return o.Type +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetTypeOk() (*AttributeType, bool) { + if o == nil { + return nil, false + } + return &o.Type, true +} + +// SetType sets field value +func (o *ResourceAttributeRead) SetType(v AttributeType) { + o.Type = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceAttributeRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceAttributeRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceAttributeRead) SetDescription(v string) { + o.Description = &v +} + +// GetKey returns the Key field value +func (o *ResourceAttributeRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceAttributeRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ResourceAttributeRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ResourceAttributeRead) SetId(v string) { + o.Id = v +} + +// GetResourceId returns the ResourceId field value +func (o *ResourceAttributeRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *ResourceAttributeRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetResourceKey returns the ResourceKey field value +func (o *ResourceAttributeRead) GetResourceKey() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceKey +} + +// GetResourceKeyOk returns a tuple with the ResourceKey field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetResourceKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceKey, true +} + +// SetResourceKey sets field value +func (o *ResourceAttributeRead) SetResourceKey(v string) { + o.ResourceKey = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ResourceAttributeRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ResourceAttributeRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ResourceAttributeRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ResourceAttributeRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ResourceAttributeRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ResourceAttributeRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ResourceAttributeRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ResourceAttributeRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ResourceAttributeRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceAttributeRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ResourceAttributeRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +func (o ResourceAttributeRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["type"] = o.Type + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["resource_id"] = o.ResourceId + } + if true { + toSerialize["resource_key"] = o.ResourceKey + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + return json.Marshal(toSerialize) +} + +type NullableResourceAttributeRead struct { + value *ResourceAttributeRead + isSet bool +} + +func (v NullableResourceAttributeRead) Get() *ResourceAttributeRead { + return v.value +} + +func (v *NullableResourceAttributeRead) Set(val *ResourceAttributeRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceAttributeRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceAttributeRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceAttributeRead(val *ResourceAttributeRead) *NullableResourceAttributeRead { + return &NullableResourceAttributeRead{value: val, isSet: true} +} + +func (v NullableResourceAttributeRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceAttributeRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_update.go new file mode 100644 index 00000000..c03a60d1 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_attribute_update.go @@ -0,0 +1,151 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceAttributeUpdate struct for ResourceAttributeUpdate +type ResourceAttributeUpdate struct { + // The type of the attribute, we currently support: `bool`, `number` (ints, floats), `time` (a timestamp), `string`, and `json`. + Type *AttributeType `json:"type,omitempty"` + // An optional longer description of what this attribute respresents in your system + Description *string `json:"description,omitempty"` +} + +// NewResourceAttributeUpdate instantiates a new ResourceAttributeUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceAttributeUpdate() *ResourceAttributeUpdate { + this := ResourceAttributeUpdate{} + return &this +} + +// NewResourceAttributeUpdateWithDefaults instantiates a new ResourceAttributeUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceAttributeUpdateWithDefaults() *ResourceAttributeUpdate { + this := ResourceAttributeUpdate{} + return &this +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *ResourceAttributeUpdate) GetType() AttributeType { + if o == nil || IsNil(o.Type) { + var ret AttributeType + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceAttributeUpdate) GetTypeOk() (*AttributeType, bool) { + if o == nil || IsNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *ResourceAttributeUpdate) HasType() bool { + if o != nil && !IsNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given AttributeType and assigns it to the Type field. +func (o *ResourceAttributeUpdate) SetType(v AttributeType) { + o.Type = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceAttributeUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceAttributeUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceAttributeUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceAttributeUpdate) SetDescription(v string) { + o.Description = &v +} + +func (o ResourceAttributeUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Type) { + toSerialize["type"] = o.Type + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + return json.Marshal(toSerialize) +} + +type NullableResourceAttributeUpdate struct { + value *ResourceAttributeUpdate + isSet bool +} + +func (v NullableResourceAttributeUpdate) Get() *ResourceAttributeUpdate { + return v.value +} + +func (v *NullableResourceAttributeUpdate) Set(val *ResourceAttributeUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceAttributeUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceAttributeUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceAttributeUpdate(val *ResourceAttributeUpdate) *NullableResourceAttributeUpdate { + return &NullableResourceAttributeUpdate{value: val, isSet: true} +} + +func (v NullableResourceAttributeUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceAttributeUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_create.go new file mode 100644 index 00000000..37bb9b89 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_create.go @@ -0,0 +1,278 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceCreate struct for ResourceCreate +type ResourceCreate struct { + // A URL-friendly name of the resource (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the resource. + Key string `json:"key"` + // The name of the resource + Name string `json:"name"` + // The [URN](https://en.wikipedia.org/wiki/Uniform_Resource_Name) (Uniform Resource Name) of the resource + Urn *string `json:"urn,omitempty"` + // An optional longer description of what this resource respresents in your system + Description *string `json:"description,omitempty"` + // A actions definition block, typically contained within a resource type definition block. The actions represents the ways you can interact with a protected resource. + Actions map[string]ActionBlockEditable `json:"actions"` + // Attributes that each resource of this type defines, and can be used in your ABAC policies. + Attributes *map[string]AttributeBlockEditable `json:"attributes,omitempty"` +} + +// NewResourceCreate instantiates a new ResourceCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceCreate(key string, name string, actions map[string]ActionBlockEditable) *ResourceCreate { + this := ResourceCreate{} + this.Key = key + this.Name = name + this.Actions = actions + return &this +} + +// NewResourceCreateWithDefaults instantiates a new ResourceCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceCreateWithDefaults() *ResourceCreate { + this := ResourceCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *ResourceCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceCreate) SetName(v string) { + o.Name = v +} + +// GetUrn returns the Urn field value if set, zero value otherwise. +func (o *ResourceCreate) GetUrn() string { + if o == nil || IsNil(o.Urn) { + var ret string + return ret + } + return *o.Urn +} + +// GetUrnOk returns a tuple with the Urn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceCreate) GetUrnOk() (*string, bool) { + if o == nil || IsNil(o.Urn) { + return nil, false + } + return o.Urn, true +} + +// HasUrn returns a boolean if a field has been set. +func (o *ResourceCreate) HasUrn() bool { + if o != nil && !IsNil(o.Urn) { + return true + } + + return false +} + +// SetUrn gets a reference to the given string and assigns it to the Urn field. +func (o *ResourceCreate) SetUrn(v string) { + o.Urn = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceCreate) SetDescription(v string) { + o.Description = &v +} + +// GetActions returns the Actions field value +func (o *ResourceCreate) GetActions() map[string]ActionBlockEditable { + if o == nil { + var ret map[string]ActionBlockEditable + return ret + } + + return o.Actions +} + +// GetActionsOk returns a tuple with the Actions field value +// and a boolean to check if the value has been set. +func (o *ResourceCreate) GetActionsOk() (*map[string]ActionBlockEditable, bool) { + if o == nil { + return nil, false + } + return &o.Actions, true +} + +// SetActions sets field value +func (o *ResourceCreate) SetActions(v map[string]ActionBlockEditable) { + o.Actions = v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceCreate) GetAttributes() map[string]AttributeBlockEditable { + if o == nil || IsNil(o.Attributes) { + var ret map[string]AttributeBlockEditable + return ret + } + return *o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceCreate) GetAttributesOk() (*map[string]AttributeBlockEditable, bool) { + if o == nil || IsNil(o.Attributes) { + return nil, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]AttributeBlockEditable and assigns it to the Attributes field. +func (o *ResourceCreate) SetAttributes(v map[string]AttributeBlockEditable) { + o.Attributes = &v +} + +func (o ResourceCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Urn) { + toSerialize["urn"] = o.Urn + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if true { + toSerialize["actions"] = o.Actions + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceCreate struct { + value *ResourceCreate + isSet bool +} + +func (v NullableResourceCreate) Get() *ResourceCreate { + return v.value +} + +func (v *NullableResourceCreate) Set(val *ResourceCreate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceCreate(val *ResourceCreate) *NullableResourceCreate { + return &NullableResourceCreate{value: val, isSet: true} +} + +func (v NullableResourceCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_id.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_id.go new file mode 100644 index 00000000..3a0ab18a --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_id.go @@ -0,0 +1,85 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ResourceId For ResourceSets, the id of the base resource. +type ResourceId struct { + String *string +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *ResourceId) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into string + err = json.Unmarshal(data, &dst.String) + if err == nil { + jsonstring, _ := json.Marshal(dst.String) + if string(jsonstring) == "{}" { // empty struct + dst.String = nil + } else { + return nil // data stored in dst.string, return on the first match + } + } else { + dst.String = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(ResourceId)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *ResourceId) MarshalJSON() ([]byte, error) { + if src.String != nil { + return json.Marshal(&src.String) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableResourceId struct { + value *ResourceId + isSet bool +} + +func (v NullableResourceId) Get() *ResourceId { + return v.value +} + +func (v *NullableResourceId) Set(val *ResourceId) { + v.value = val + v.isSet = true +} + +func (v NullableResourceId) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceId) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceId(val *ResourceId) *NullableResourceId { + return &NullableResourceId{value: val, isSet: true} +} + +func (v NullableResourceId) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceId) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_block_read.go new file mode 100644 index 00000000..80fb8700 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_block_read.go @@ -0,0 +1,209 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ResourceInstanceBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceInstanceBlockRead{} + +// ResourceInstanceBlockRead struct for ResourceInstanceBlockRead +type ResourceInstanceBlockRead struct { + // A unique identifier by which Permit will identify the resource instance for permission checks. You will later pass this identifier to the `permit.check()` API. A key can be anything: for example the resource db id, a url slug, a UUID or anything else as long as it's unique on your end. The resource instance key must be url-friendly. + Key string `json:"key"` + // the *key* of the tenant that this resource belongs to, used to enforce tenant boundaries in multi-tenant apps. + Tenant string `json:"tenant"` + // the *key* of the resource (type) of this resource instance. For example: if this resource instance is the annual budget document, the key of the resource might be `document`. + Resource string `json:"resource"` + // Arbitrary resource attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewResourceInstanceBlockRead instantiates a new ResourceInstanceBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceInstanceBlockRead(key string, tenant string, resource string) *ResourceInstanceBlockRead { + this := ResourceInstanceBlockRead{} + this.Key = key + this.Tenant = tenant + this.Resource = resource + return &this +} + +// NewResourceInstanceBlockReadWithDefaults instantiates a new ResourceInstanceBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceInstanceBlockReadWithDefaults() *ResourceInstanceBlockRead { + this := ResourceInstanceBlockRead{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceInstanceBlockRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceBlockRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceInstanceBlockRead) SetKey(v string) { + o.Key = v +} + +// GetTenant returns the Tenant field value +func (o *ResourceInstanceBlockRead) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceBlockRead) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *ResourceInstanceBlockRead) SetTenant(v string) { + o.Tenant = v +} + +// GetResource returns the Resource field value +func (o *ResourceInstanceBlockRead) GetResource() string { + if o == nil { + var ret string + return ret + } + + return o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceBlockRead) GetResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Resource, true +} + +// SetResource sets field value +func (o *ResourceInstanceBlockRead) SetResource(v string) { + o.Resource = v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceInstanceBlockRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceBlockRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceInstanceBlockRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceInstanceBlockRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ResourceInstanceBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceInstanceBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["tenant"] = o.Tenant + toSerialize["resource"] = o.Resource + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableResourceInstanceBlockRead struct { + value *ResourceInstanceBlockRead + isSet bool +} + +func (v NullableResourceInstanceBlockRead) Get() *ResourceInstanceBlockRead { + return v.value +} + +func (v *NullableResourceInstanceBlockRead) Set(val *ResourceInstanceBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceInstanceBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceInstanceBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceInstanceBlockRead(val *ResourceInstanceBlockRead) *NullableResourceInstanceBlockRead { + return &NullableResourceInstanceBlockRead{value: val, isSet: true} +} + +func (v NullableResourceInstanceBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceInstanceBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_create.go new file mode 100644 index 00000000..9a5847e5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_create.go @@ -0,0 +1,211 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceInstanceCreate struct for ResourceInstanceCreate +type ResourceInstanceCreate struct { + // A unique identifier by which Permit will identify the resource instance for permission checks. You will later pass this identifier to the `permit.check()` API. A key can be anything: for example the resource db id, a url slug, a UUID or anything else as long as it's unique on your end. The resource instance key must be url-friendly. + Key string `json:"key"` + // the *key* of the tenant that this resource belongs to, used to enforce tenant boundaries in multi-tenant apps. + Tenant *string `json:"tenant,omitempty"` + // the *key* of the resource (type) of this resource instance. For example: if this resource instance is the annual budget document, the key of the resource might be `document`. + Resource string `json:"resource"` + // Arbitraty resource attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewResourceInstanceCreate instantiates a new ResourceInstanceCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceInstanceCreate(key string, resource string) *ResourceInstanceCreate { + this := ResourceInstanceCreate{} + this.Key = key + this.Resource = resource + return &this +} + +// NewResourceInstanceCreateWithDefaults instantiates a new ResourceInstanceCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceInstanceCreateWithDefaults() *ResourceInstanceCreate { + this := ResourceInstanceCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceInstanceCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceInstanceCreate) SetKey(v string) { + o.Key = v +} + +// GetTenant returns the Tenant field value if set, zero value otherwise. +func (o *ResourceInstanceCreate) GetTenant() string { + if o == nil || IsNil(o.Tenant) { + var ret string + return ret + } + return *o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceCreate) GetTenantOk() (*string, bool) { + if o == nil || IsNil(o.Tenant) { + return nil, false + } + return o.Tenant, true +} + +// HasTenant returns a boolean if a field has been set. +func (o *ResourceInstanceCreate) HasTenant() bool { + if o != nil && !IsNil(o.Tenant) { + return true + } + + return false +} + +// SetTenant gets a reference to the given string and assigns it to the Tenant field. +func (o *ResourceInstanceCreate) SetTenant(v string) { + o.Tenant = &v +} + +// GetResource returns the Resource field value +func (o *ResourceInstanceCreate) GetResource() string { + if o == nil { + var ret string + return ret + } + + return o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceCreate) GetResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Resource, true +} + +// SetResource sets field value +func (o *ResourceInstanceCreate) SetResource(v string) { + o.Resource = v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceInstanceCreate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceCreate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceInstanceCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceInstanceCreate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ResourceInstanceCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if !IsNil(o.Tenant) { + toSerialize["tenant"] = o.Tenant + } + if true { + toSerialize["resource"] = o.Resource + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceInstanceCreate struct { + value *ResourceInstanceCreate + isSet bool +} + +func (v NullableResourceInstanceCreate) Get() *ResourceInstanceCreate { + return v.value +} + +func (v *NullableResourceInstanceCreate) Set(val *ResourceInstanceCreate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceInstanceCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceInstanceCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceInstanceCreate(val *ResourceInstanceCreate) *NullableResourceInstanceCreate { + return &NullableResourceInstanceCreate{value: val, isSet: true} +} + +func (v NullableResourceInstanceCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceInstanceCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_read.go new file mode 100644 index 00000000..4d11c3af --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_read.go @@ -0,0 +1,459 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ResourceInstanceRead struct for ResourceInstanceRead +type ResourceInstanceRead struct { + // A unique identifier by which Permit will identify the resource instance for permission checks. You will later pass this identifier to the `permit.check()` API. A key can be anything: for example the resource db id, a url slug, a UUID or anything else as long as it's unique on your end. The resource instance key must be url-friendly. + Key string `json:"key"` + // the *key* of the tenant that this resource belongs to, used to enforce tenant boundaries in multi-tenant apps. + Tenant *string `json:"tenant,omitempty"` + // the *key* of the resource (type) of this resource instance. For example: if this resource instance is the annual budget document, the key of the resource might be `document`. + Resource string `json:"resource"` + // Unique id of the resource instance + Id string `json:"id"` + // Unique id of the organization that the resource instance belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the resource instance belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the resource instance belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the resource instance was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the resource instance was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // the id of the resource (type) of this resource instance. + ResourceId string `json:"resource_id"` + // the id of the tenant of this resource instance. + TenantId *string `json:"tenant_id,omitempty"` + // Arbitraty resource attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewResourceInstanceRead instantiates a new ResourceInstanceRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceInstanceRead(key string, resource string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, resourceId string) *ResourceInstanceRead { + this := ResourceInstanceRead{} + this.Key = key + this.Resource = resource + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.ResourceId = resourceId + return &this +} + +// NewResourceInstanceReadWithDefaults instantiates a new ResourceInstanceRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceInstanceReadWithDefaults() *ResourceInstanceRead { + this := ResourceInstanceRead{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceInstanceRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceInstanceRead) SetKey(v string) { + o.Key = v +} + +// GetTenant returns the Tenant field value if set, zero value otherwise. +func (o *ResourceInstanceRead) GetTenant() string { + if o == nil || IsNil(o.Tenant) { + var ret string + return ret + } + return *o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetTenantOk() (*string, bool) { + if o == nil || IsNil(o.Tenant) { + return nil, false + } + return o.Tenant, true +} + +// HasTenant returns a boolean if a field has been set. +func (o *ResourceInstanceRead) HasTenant() bool { + if o != nil && !IsNil(o.Tenant) { + return true + } + + return false +} + +// SetTenant gets a reference to the given string and assigns it to the Tenant field. +func (o *ResourceInstanceRead) SetTenant(v string) { + o.Tenant = &v +} + +// GetResource returns the Resource field value +func (o *ResourceInstanceRead) GetResource() string { + if o == nil { + var ret string + return ret + } + + return o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Resource, true +} + +// SetResource sets field value +func (o *ResourceInstanceRead) SetResource(v string) { + o.Resource = v +} + +// GetId returns the Id field value +func (o *ResourceInstanceRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ResourceInstanceRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ResourceInstanceRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ResourceInstanceRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ResourceInstanceRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ResourceInstanceRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ResourceInstanceRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ResourceInstanceRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ResourceInstanceRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ResourceInstanceRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ResourceInstanceRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ResourceInstanceRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetResourceId returns the ResourceId field value +func (o *ResourceInstanceRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *ResourceInstanceRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetTenantId returns the TenantId field value if set, zero value otherwise. +func (o *ResourceInstanceRead) GetTenantId() string { + if o == nil || IsNil(o.TenantId) { + var ret string + return ret + } + return *o.TenantId +} + +// GetTenantIdOk returns a tuple with the TenantId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetTenantIdOk() (*string, bool) { + if o == nil || IsNil(o.TenantId) { + return nil, false + } + return o.TenantId, true +} + +// HasTenantId returns a boolean if a field has been set. +func (o *ResourceInstanceRead) HasTenantId() bool { + if o != nil && !IsNil(o.TenantId) { + return true + } + + return false +} + +// SetTenantId gets a reference to the given string and assigns it to the TenantId field. +func (o *ResourceInstanceRead) SetTenantId(v string) { + o.TenantId = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceInstanceRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceInstanceRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceInstanceRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ResourceInstanceRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if !IsNil(o.Tenant) { + toSerialize["tenant"] = o.Tenant + } + if true { + toSerialize["resource"] = o.Resource + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["resource_id"] = o.ResourceId + } + if !IsNil(o.TenantId) { + toSerialize["tenant_id"] = o.TenantId + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceInstanceRead struct { + value *ResourceInstanceRead + isSet bool +} + +func (v NullableResourceInstanceRead) Get() *ResourceInstanceRead { + return v.value +} + +func (v *NullableResourceInstanceRead) Set(val *ResourceInstanceRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceInstanceRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceInstanceRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceInstanceRead(val *ResourceInstanceRead) *NullableResourceInstanceRead { + return &NullableResourceInstanceRead{value: val, isSet: true} +} + +func (v NullableResourceInstanceRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceInstanceRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_update.go new file mode 100644 index 00000000..beaf89a5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_instance_update.go @@ -0,0 +1,114 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceInstanceUpdate struct for ResourceInstanceUpdate +type ResourceInstanceUpdate struct { + // Arbitraty resource attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewResourceInstanceUpdate instantiates a new ResourceInstanceUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceInstanceUpdate() *ResourceInstanceUpdate { + this := ResourceInstanceUpdate{} + return &this +} + +// NewResourceInstanceUpdateWithDefaults instantiates a new ResourceInstanceUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceInstanceUpdateWithDefaults() *ResourceInstanceUpdate { + this := ResourceInstanceUpdate{} + return &this +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceInstanceUpdate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceInstanceUpdate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceInstanceUpdate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *ResourceInstanceUpdate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o ResourceInstanceUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceInstanceUpdate struct { + value *ResourceInstanceUpdate + isSet bool +} + +func (v NullableResourceInstanceUpdate) Get() *ResourceInstanceUpdate { + return v.value +} + +func (v *NullableResourceInstanceUpdate) Set(val *ResourceInstanceUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceInstanceUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceInstanceUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceInstanceUpdate(val *ResourceInstanceUpdate) *NullableResourceInstanceUpdate { + return &NullableResourceInstanceUpdate{value: val, isSet: true} +} + +func (v NullableResourceInstanceUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceInstanceUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_read.go new file mode 100644 index 00000000..7b15eb3b --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_read.go @@ -0,0 +1,466 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ResourceRead struct for ResourceRead +type ResourceRead struct { + // A URL-friendly name of the resource (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the resource. + Key string `json:"key"` + // Unique id of the resource + Id string `json:"id"` + // Unique id of the organization that the resource belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the resource belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the resource belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the resource was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the resource was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The name of the resource + Name string `json:"name"` + // The [URN](https://en.wikipedia.org/wiki/Uniform_Resource_Name) (Uniform Resource Name) of the resource + Urn *string `json:"urn,omitempty"` + // An optional longer description of what this resource respresents in your system + Description *string `json:"description,omitempty"` + // A actions definition block, typically contained within a resource type definition block. The actions represents the ways you can interact with a protected resource. + Actions *map[string]ActionBlockRead `json:"actions,omitempty"` + // Attributes that each resource of this type defines, and can be used in your ABAC policies. + Attributes *map[string]AttributeBlockRead `json:"attributes,omitempty"` +} + +// NewResourceRead instantiates a new ResourceRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceRead(key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, name string) *ResourceRead { + this := ResourceRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Name = name + return &this +} + +// NewResourceReadWithDefaults instantiates a new ResourceRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceReadWithDefaults() *ResourceRead { + this := ResourceRead{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ResourceRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ResourceRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ResourceRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ResourceRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ResourceRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ResourceRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ResourceRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ResourceRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ResourceRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ResourceRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ResourceRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ResourceRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetName returns the Name field value +func (o *ResourceRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceRead) SetName(v string) { + o.Name = v +} + +// GetUrn returns the Urn field value if set, zero value otherwise. +func (o *ResourceRead) GetUrn() string { + if o == nil || IsNil(o.Urn) { + var ret string + return ret + } + return *o.Urn +} + +// GetUrnOk returns a tuple with the Urn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetUrnOk() (*string, bool) { + if o == nil || IsNil(o.Urn) { + return nil, false + } + return o.Urn, true +} + +// HasUrn returns a boolean if a field has been set. +func (o *ResourceRead) HasUrn() bool { + if o != nil && !IsNil(o.Urn) { + return true + } + + return false +} + +// SetUrn gets a reference to the given string and assigns it to the Urn field. +func (o *ResourceRead) SetUrn(v string) { + o.Urn = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceRead) SetDescription(v string) { + o.Description = &v +} + +// GetActions returns the Actions field value if set, zero value otherwise. +func (o *ResourceRead) GetActions() map[string]ActionBlockRead { + if o == nil || IsNil(o.Actions) { + var ret map[string]ActionBlockRead + return ret + } + return *o.Actions +} + +// GetActionsOk returns a tuple with the Actions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetActionsOk() (*map[string]ActionBlockRead, bool) { + if o == nil || IsNil(o.Actions) { + return nil, false + } + return o.Actions, true +} + +// HasActions returns a boolean if a field has been set. +func (o *ResourceRead) HasActions() bool { + if o != nil && !IsNil(o.Actions) { + return true + } + + return false +} + +// SetActions gets a reference to the given map[string]ActionBlockRead and assigns it to the Actions field. +func (o *ResourceRead) SetActions(v map[string]ActionBlockRead) { + o.Actions = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceRead) GetAttributes() map[string]AttributeBlockRead { + if o == nil || IsNil(o.Attributes) { + var ret map[string]AttributeBlockRead + return ret + } + return *o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRead) GetAttributesOk() (*map[string]AttributeBlockRead, bool) { + if o == nil || IsNil(o.Attributes) { + return nil, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]AttributeBlockRead and assigns it to the Attributes field. +func (o *ResourceRead) SetAttributes(v map[string]AttributeBlockRead) { + o.Attributes = &v +} + +func (o ResourceRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Urn) { + toSerialize["urn"] = o.Urn + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Actions) { + toSerialize["actions"] = o.Actions + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceRead struct { + value *ResourceRead + isSet bool +} + +func (v NullableResourceRead) Get() *ResourceRead { + return v.value +} + +func (v *NullableResourceRead) Set(val *ResourceRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceRead(val *ResourceRead) *NullableResourceRead { + return &NullableResourceRead{value: val, isSet: true} +} + +func (v NullableResourceRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_replace.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_replace.go new file mode 100644 index 00000000..ee95168c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_replace.go @@ -0,0 +1,248 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceReplace struct for ResourceReplace +type ResourceReplace struct { + // The name of the resource + Name string `json:"name"` + // The [URN](https://en.wikipedia.org/wiki/Uniform_Resource_Name) (Uniform Resource Name) of the resource + Urn *string `json:"urn,omitempty"` + // An optional longer description of what this resource respresents in your system + Description *string `json:"description,omitempty"` + // A actions definition block, typically contained within a resource type definition block. The actions represents the ways you can interact with a protected resource. + Actions map[string]ActionBlockEditable `json:"actions"` + // Attributes that each resource of this type defines, and can be used in your ABAC policies. + Attributes *map[string]AttributeBlockEditable `json:"attributes,omitempty"` +} + +// NewResourceReplace instantiates a new ResourceReplace object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceReplace(name string, actions map[string]ActionBlockEditable) *ResourceReplace { + this := ResourceReplace{} + this.Name = name + this.Actions = actions + return &this +} + +// NewResourceReplaceWithDefaults instantiates a new ResourceReplace object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceReplaceWithDefaults() *ResourceReplace { + this := ResourceReplace{} + return &this +} + +// GetName returns the Name field value +func (o *ResourceReplace) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceReplace) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceReplace) SetName(v string) { + o.Name = v +} + +// GetUrn returns the Urn field value if set, zero value otherwise. +func (o *ResourceReplace) GetUrn() string { + if o == nil || IsNil(o.Urn) { + var ret string + return ret + } + return *o.Urn +} + +// GetUrnOk returns a tuple with the Urn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceReplace) GetUrnOk() (*string, bool) { + if o == nil || IsNil(o.Urn) { + return nil, false + } + return o.Urn, true +} + +// HasUrn returns a boolean if a field has been set. +func (o *ResourceReplace) HasUrn() bool { + if o != nil && !IsNil(o.Urn) { + return true + } + + return false +} + +// SetUrn gets a reference to the given string and assigns it to the Urn field. +func (o *ResourceReplace) SetUrn(v string) { + o.Urn = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceReplace) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceReplace) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceReplace) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceReplace) SetDescription(v string) { + o.Description = &v +} + +// GetActions returns the Actions field value +func (o *ResourceReplace) GetActions() map[string]ActionBlockEditable { + if o == nil { + var ret map[string]ActionBlockEditable + return ret + } + + return o.Actions +} + +// GetActionsOk returns a tuple with the Actions field value +// and a boolean to check if the value has been set. +func (o *ResourceReplace) GetActionsOk() (*map[string]ActionBlockEditable, bool) { + if o == nil { + return nil, false + } + return &o.Actions, true +} + +// SetActions sets field value +func (o *ResourceReplace) SetActions(v map[string]ActionBlockEditable) { + o.Actions = v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceReplace) GetAttributes() map[string]AttributeBlockEditable { + if o == nil || IsNil(o.Attributes) { + var ret map[string]AttributeBlockEditable + return ret + } + return *o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceReplace) GetAttributesOk() (*map[string]AttributeBlockEditable, bool) { + if o == nil || IsNil(o.Attributes) { + return nil, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceReplace) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]AttributeBlockEditable and assigns it to the Attributes field. +func (o *ResourceReplace) SetAttributes(v map[string]AttributeBlockEditable) { + o.Attributes = &v +} + +func (o ResourceReplace) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Urn) { + toSerialize["urn"] = o.Urn + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if true { + toSerialize["actions"] = o.Actions + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceReplace struct { + value *ResourceReplace + isSet bool +} + +func (v NullableResourceReplace) Get() *ResourceReplace { + return v.value +} + +func (v *NullableResourceReplace) Set(val *ResourceReplace) { + v.value = val + v.isSet = true +} + +func (v NullableResourceReplace) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceReplace) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceReplace(val *ResourceReplace) *NullableResourceReplace { + return &NullableResourceReplace{value: val, isSet: true} +} + +func (v NullableResourceReplace) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceReplace) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_create.go new file mode 100644 index 00000000..d93c22ee --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_create.go @@ -0,0 +1,248 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceRoleCreate struct for ResourceRoleCreate +type ResourceRoleCreate struct { + // A URL-friendly name of the role (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the role. + Key string `json:"key"` + // The name of the role + Name string `json:"name"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` +} + +// NewResourceRoleCreate instantiates a new ResourceRoleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceRoleCreate(key string, name string) *ResourceRoleCreate { + this := ResourceRoleCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewResourceRoleCreateWithDefaults instantiates a new ResourceRoleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceRoleCreateWithDefaults() *ResourceRoleCreate { + this := ResourceRoleCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *ResourceRoleCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceRoleCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *ResourceRoleCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceRoleCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceRoleCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceRoleCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceRoleCreate) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *ResourceRoleCreate) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleCreate) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *ResourceRoleCreate) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *ResourceRoleCreate) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *ResourceRoleCreate) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleCreate) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *ResourceRoleCreate) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *ResourceRoleCreate) SetExtends(v []string) { + o.Extends = v +} + +func (o ResourceRoleCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + return json.Marshal(toSerialize) +} + +type NullableResourceRoleCreate struct { + value *ResourceRoleCreate + isSet bool +} + +func (v NullableResourceRoleCreate) Get() *ResourceRoleCreate { + return v.value +} + +func (v *NullableResourceRoleCreate) Set(val *ResourceRoleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceRoleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceRoleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceRoleCreate(val *ResourceRoleCreate) *NullableResourceRoleCreate { + return &NullableResourceRoleCreate{value: val, isSet: true} +} + +func (v NullableResourceRoleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceRoleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_list.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_list.go new file mode 100644 index 00000000..33b27b3d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_list.go @@ -0,0 +1,115 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ResourceRoleList type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceRoleList{} + +// ResourceRoleList struct for ResourceRoleList +type ResourceRoleList struct { + Roles Roles `json:"roles"` +} + +// NewResourceRoleList instantiates a new ResourceRoleList object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceRoleList(roles Roles) *ResourceRoleList { + this := ResourceRoleList{} + this.Roles = roles + return &this +} + +// NewResourceRoleListWithDefaults instantiates a new ResourceRoleList object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceRoleListWithDefaults() *ResourceRoleList { + this := ResourceRoleList{} + return &this +} + +// GetRoles returns the Roles field value +func (o *ResourceRoleList) GetRoles() Roles { + if o == nil { + var ret Roles + return ret + } + + return o.Roles +} + +// GetRolesOk returns a tuple with the Roles field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleList) GetRolesOk() (*Roles, bool) { + if o == nil { + return nil, false + } + return &o.Roles, true +} + +// SetRoles sets field value +func (o *ResourceRoleList) SetRoles(v Roles) { + o.Roles = v +} + +func (o ResourceRoleList) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceRoleList) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["roles"] = o.Roles + return toSerialize, nil +} + +type NullableResourceRoleList struct { + value *ResourceRoleList + isSet bool +} + +func (v NullableResourceRoleList) Get() *ResourceRoleList { + return v.value +} + +func (v *NullableResourceRoleList) Set(val *ResourceRoleList) { + v.value = val + v.isSet = true +} + +func (v NullableResourceRoleList) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceRoleList) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceRoleList(val *ResourceRoleList) *NullableResourceRoleList { + return &NullableResourceRoleList{value: val, isSet: true} +} + +func (v NullableResourceRoleList) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceRoleList) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_read.go new file mode 100644 index 00000000..1d6563b9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_read.go @@ -0,0 +1,495 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// ResourceRoleRead struct for ResourceRoleRead +type ResourceRoleRead struct { + // The name of the role + Name string `json:"name"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` + GrantedTo *DerivedRoleBlockRead `json:"granted_to,omitempty"` + // A URL-friendly name of the role (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the role. + Key string `json:"key"` + // Unique id of the role + Id string `json:"id"` + // Unique id of the organization that the role belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the role belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the role belongs to. + EnvironmentId string `json:"environment_id"` + // Unique id of the resource that the role belongs to. + ResourceId string `json:"resource_id"` + // Date and time when the role was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the role was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` +} + +// NewResourceRoleRead instantiates a new ResourceRoleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceRoleRead(name string, key string, id string, organizationId string, projectId string, environmentId string, resourceId string, createdAt time.Time, updatedAt time.Time) *ResourceRoleRead { + this := ResourceRoleRead{} + this.Name = name + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.ResourceId = resourceId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewResourceRoleReadWithDefaults instantiates a new ResourceRoleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceRoleReadWithDefaults() *ResourceRoleRead { + this := ResourceRoleRead{} + return &this +} + +// GetName returns the Name field value +func (o *ResourceRoleRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *ResourceRoleRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceRoleRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceRoleRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceRoleRead) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *ResourceRoleRead) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *ResourceRoleRead) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *ResourceRoleRead) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *ResourceRoleRead) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *ResourceRoleRead) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *ResourceRoleRead) SetExtends(v []string) { + o.Extends = v +} + +// GetKey returns the Key field value +func (o *ResourceRoleRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *ResourceRoleRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *ResourceRoleRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *ResourceRoleRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *ResourceRoleRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *ResourceRoleRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *ResourceRoleRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *ResourceRoleRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *ResourceRoleRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *ResourceRoleRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetResourceId returns the ResourceId field value +func (o *ResourceRoleRead) GetResourceId() string { + if o == nil { + var ret string + return ret + } + + return o.ResourceId +} + +// GetResourceIdOk returns a tuple with the ResourceId field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetResourceIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ResourceId, true +} + +// SetResourceId sets field value +func (o *ResourceRoleRead) SetResourceId(v string) { + o.ResourceId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *ResourceRoleRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *ResourceRoleRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *ResourceRoleRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *ResourceRoleRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +func (o ResourceRoleRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + if !IsNil(o.GrantedTo) { + toSerialize["granted_to"] = o.GrantedTo + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["resource_id"] = o.ResourceId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + return json.Marshal(toSerialize) +} + +type NullableResourceRoleRead struct { + value *ResourceRoleRead + isSet bool +} + +func (v NullableResourceRoleRead) Get() *ResourceRoleRead { + return v.value +} + +func (v *NullableResourceRoleRead) Set(val *ResourceRoleRead) { + v.value = val + v.isSet = true +} + +func (v NullableResourceRoleRead) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceRoleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceRoleRead(val *ResourceRoleRead) *NullableResourceRoleRead { + return &NullableResourceRoleRead{value: val, isSet: true} +} + +func (v NullableResourceRoleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceRoleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +// GetGrantedTo returns the GrantedTo field value if set, zero value otherwise. +func (o *ResourceRoleRead) GetGrantedTo() DerivedRoleBlockRead { + if o == nil || IsNil(o.GrantedTo) { + var ret DerivedRoleBlockRead + return ret + } + return *o.GrantedTo +} + +// GetGrantedToOk returns a tuple with the GrantedTo field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleRead) GetGrantedToOk() (*DerivedRoleBlockRead, bool) { + if o == nil || IsNil(o.GrantedTo) { + return nil, false + } + return o.GrantedTo, true +} + +// HasGrantedTo returns a boolean if a field has been set. +func (o *ResourceRoleRead) HasGrantedTo() bool { + if o != nil && !IsNil(o.GrantedTo) { + return true + } + + return false +} + +// SetGrantedTo gets a reference to the given DerivedRoleBlockRead and assigns it to the GrantedTo field. +func (o *ResourceRoleRead) SetGrantedTo(v DerivedRoleBlockRead) { + o.GrantedTo = &v +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_update.go new file mode 100644 index 00000000..5ca8d840 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_role_update.go @@ -0,0 +1,225 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceRoleUpdate struct for ResourceRoleUpdate +type ResourceRoleUpdate struct { + // The name of the role + Name *string `json:"name,omitempty"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` +} + +// NewResourceRoleUpdate instantiates a new ResourceRoleUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceRoleUpdate() *ResourceRoleUpdate { + this := ResourceRoleUpdate{} + return &this +} + +// NewResourceRoleUpdateWithDefaults instantiates a new ResourceRoleUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceRoleUpdateWithDefaults() *ResourceRoleUpdate { + this := ResourceRoleUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ResourceRoleUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ResourceRoleUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ResourceRoleUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceRoleUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceRoleUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceRoleUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *ResourceRoleUpdate) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleUpdate) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *ResourceRoleUpdate) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *ResourceRoleUpdate) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *ResourceRoleUpdate) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRoleUpdate) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *ResourceRoleUpdate) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *ResourceRoleUpdate) SetExtends(v []string) { + o.Extends = v +} + +func (o ResourceRoleUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + return json.Marshal(toSerialize) +} + +type NullableResourceRoleUpdate struct { + value *ResourceRoleUpdate + isSet bool +} + +func (v NullableResourceRoleUpdate) Get() *ResourceRoleUpdate { + return v.value +} + +func (v *NullableResourceRoleUpdate) Set(val *ResourceRoleUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceRoleUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceRoleUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceRoleUpdate(val *ResourceRoleUpdate) *NullableResourceRoleUpdate { + return &NullableResourceRoleUpdate{value: val, isSet: true} +} + +func (v NullableResourceRoleUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceRoleUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_sets.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_sets.go new file mode 100644 index 00000000..7eceee2b --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_sets.go @@ -0,0 +1,162 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the ResourceSets type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceSets{} + +// ResourceSets Resource sets to copy +type ResourceSets struct { + // Objects to include (use * as wildcard) + Include []string `json:"include,omitempty"` + // Object to exclude (use * as wildcard) + Exclude []string `json:"exclude,omitempty"` +} + +// NewResourceSets instantiates a new ResourceSets object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceSets() *ResourceSets { + this := ResourceSets{} + return &this +} + +// NewResourceSetsWithDefaults instantiates a new ResourceSets object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceSetsWithDefaults() *ResourceSets { + this := ResourceSets{} + return &this +} + +// GetInclude returns the Include field value if set, zero value otherwise. +func (o *ResourceSets) GetInclude() []string { + if o == nil || IsNil(o.Include) { + var ret []string + return ret + } + return o.Include +} + +// GetIncludeOk returns a tuple with the Include field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceSets) GetIncludeOk() ([]string, bool) { + if o == nil || IsNil(o.Include) { + return nil, false + } + return o.Include, true +} + +// HasInclude returns a boolean if a field has been set. +func (o *ResourceSets) HasInclude() bool { + if o != nil && !IsNil(o.Include) { + return true + } + + return false +} + +// SetInclude gets a reference to the given []string and assigns it to the Include field. +func (o *ResourceSets) SetInclude(v []string) { + o.Include = v +} + +// GetExclude returns the Exclude field value if set, zero value otherwise. +func (o *ResourceSets) GetExclude() []string { + if o == nil || IsNil(o.Exclude) { + var ret []string + return ret + } + return o.Exclude +} + +// GetExcludeOk returns a tuple with the Exclude field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceSets) GetExcludeOk() ([]string, bool) { + if o == nil || IsNil(o.Exclude) { + return nil, false + } + return o.Exclude, true +} + +// HasExclude returns a boolean if a field has been set. +func (o *ResourceSets) HasExclude() bool { + if o != nil && !IsNil(o.Exclude) { + return true + } + + return false +} + +// SetExclude gets a reference to the given []string and assigns it to the Exclude field. +func (o *ResourceSets) SetExclude(v []string) { + o.Exclude = v +} + +func (o ResourceSets) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceSets) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Include) { + toSerialize["include"] = o.Include + } + if !IsNil(o.Exclude) { + toSerialize["exclude"] = o.Exclude + } + return toSerialize, nil +} + +type NullableResourceSets struct { + value *ResourceSets + isSet bool +} + +func (v NullableResourceSets) Get() *ResourceSets { + return v.value +} + +func (v *NullableResourceSets) Set(val *ResourceSets) { + v.value = val + v.isSet = true +} + +func (v NullableResourceSets) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceSets) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceSets(val *ResourceSets) *NullableResourceSets { + return &NullableResourceSets{value: val, isSet: true} +} + +func (v NullableResourceSets) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceSets) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_update.go new file mode 100644 index 00000000..30429bb5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resource_update.go @@ -0,0 +1,262 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ResourceUpdate struct for ResourceUpdate +type ResourceUpdate struct { + // The name of the resource + Name *string `json:"name,omitempty"` + // The [URN](https://en.wikipedia.org/wiki/Uniform_Resource_Name) (Uniform Resource Name) of the resource + Urn *string `json:"urn,omitempty"` + // An optional longer description of what this resource respresents in your system + Description *string `json:"description,omitempty"` + // A actions definition block, typically contained within a resource type definition block. The actions represents the ways you can interact with a protected resource. + Actions *map[string]ActionBlockEditable `json:"actions,omitempty"` + // Attributes that each resource of this type defines, and can be used in your ABAC policies. + Attributes *map[string]AttributeBlockEditable `json:"attributes,omitempty"` +} + +// NewResourceUpdate instantiates a new ResourceUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceUpdate() *ResourceUpdate { + this := ResourceUpdate{} + return &this +} + +// NewResourceUpdateWithDefaults instantiates a new ResourceUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceUpdateWithDefaults() *ResourceUpdate { + this := ResourceUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *ResourceUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *ResourceUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *ResourceUpdate) SetName(v string) { + o.Name = &v +} + +// GetUrn returns the Urn field value if set, zero value otherwise. +func (o *ResourceUpdate) GetUrn() string { + if o == nil || IsNil(o.Urn) { + var ret string + return ret + } + return *o.Urn +} + +// GetUrnOk returns a tuple with the Urn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceUpdate) GetUrnOk() (*string, bool) { + if o == nil || IsNil(o.Urn) { + return nil, false + } + return o.Urn, true +} + +// HasUrn returns a boolean if a field has been set. +func (o *ResourceUpdate) HasUrn() bool { + if o != nil && !IsNil(o.Urn) { + return true + } + + return false +} + +// SetUrn gets a reference to the given string and assigns it to the Urn field. +func (o *ResourceUpdate) SetUrn(v string) { + o.Urn = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *ResourceUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *ResourceUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *ResourceUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetActions returns the Actions field value if set, zero value otherwise. +func (o *ResourceUpdate) GetActions() map[string]ActionBlockEditable { + if o == nil || IsNil(o.Actions) { + var ret map[string]ActionBlockEditable + return ret + } + return *o.Actions +} + +// GetActionsOk returns a tuple with the Actions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceUpdate) GetActionsOk() (*map[string]ActionBlockEditable, bool) { + if o == nil || IsNil(o.Actions) { + return nil, false + } + return o.Actions, true +} + +// HasActions returns a boolean if a field has been set. +func (o *ResourceUpdate) HasActions() bool { + if o != nil && !IsNil(o.Actions) { + return true + } + + return false +} + +// SetActions gets a reference to the given map[string]ActionBlockEditable and assigns it to the Actions field. +func (o *ResourceUpdate) SetActions(v map[string]ActionBlockEditable) { + o.Actions = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *ResourceUpdate) GetAttributes() map[string]AttributeBlockEditable { + if o == nil || IsNil(o.Attributes) { + var ret map[string]AttributeBlockEditable + return ret + } + return *o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceUpdate) GetAttributesOk() (*map[string]AttributeBlockEditable, bool) { + if o == nil || IsNil(o.Attributes) { + return nil, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *ResourceUpdate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]AttributeBlockEditable and assigns it to the Attributes field. +func (o *ResourceUpdate) SetAttributes(v map[string]AttributeBlockEditable) { + o.Attributes = &v +} + +func (o ResourceUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Urn) { + toSerialize["urn"] = o.Urn + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Actions) { + toSerialize["actions"] = o.Actions + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableResourceUpdate struct { + value *ResourceUpdate + isSet bool +} + +func (v NullableResourceUpdate) Get() *ResourceUpdate { + return v.value +} + +func (v *NullableResourceUpdate) Set(val *ResourceUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableResourceUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceUpdate(val *ResourceUpdate) *NullableResourceUpdate { + return &NullableResourceUpdate{value: val, isSet: true} +} + +func (v NullableResourceUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_resources.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_resources.go new file mode 100644 index 00000000..bafe2088 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_resources.go @@ -0,0 +1,162 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the Resources type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Resources{} + +// Resources Resources to copy +type Resources struct { + // Objects to include (use * as wildcard) + Include []string `json:"include,omitempty"` + // Object to exclude (use * as wildcard) + Exclude []string `json:"exclude,omitempty"` +} + +// NewResources instantiates a new Resources object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResources() *Resources { + this := Resources{} + return &this +} + +// NewResourcesWithDefaults instantiates a new Resources object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourcesWithDefaults() *Resources { + this := Resources{} + return &this +} + +// GetInclude returns the Include field value if set, zero value otherwise. +func (o *Resources) GetInclude() []string { + if o == nil || IsNil(o.Include) { + var ret []string + return ret + } + return o.Include +} + +// GetIncludeOk returns a tuple with the Include field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Resources) GetIncludeOk() ([]string, bool) { + if o == nil || IsNil(o.Include) { + return nil, false + } + return o.Include, true +} + +// HasInclude returns a boolean if a field has been set. +func (o *Resources) HasInclude() bool { + if o != nil && !IsNil(o.Include) { + return true + } + + return false +} + +// SetInclude gets a reference to the given []string and assigns it to the Include field. +func (o *Resources) SetInclude(v []string) { + o.Include = v +} + +// GetExclude returns the Exclude field value if set, zero value otherwise. +func (o *Resources) GetExclude() []string { + if o == nil || IsNil(o.Exclude) { + var ret []string + return ret + } + return o.Exclude +} + +// GetExcludeOk returns a tuple with the Exclude field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Resources) GetExcludeOk() ([]string, bool) { + if o == nil || IsNil(o.Exclude) { + return nil, false + } + return o.Exclude, true +} + +// HasExclude returns a boolean if a field has been set. +func (o *Resources) HasExclude() bool { + if o != nil && !IsNil(o.Exclude) { + return true + } + + return false +} + +// SetExclude gets a reference to the given []string and assigns it to the Exclude field. +func (o *Resources) SetExclude(v []string) { + o.Exclude = v +} + +func (o Resources) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Resources) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Include) { + toSerialize["include"] = o.Include + } + if !IsNil(o.Exclude) { + toSerialize["exclude"] = o.Exclude + } + return toSerialize, nil +} + +type NullableResources struct { + value *Resources + isSet bool +} + +func (v NullableResources) Get() *Resources { + return v.value +} + +func (v *NullableResources) Set(val *Resources) { + v.value = val + v.isSet = true +} + +func (v NullableResources) IsSet() bool { + return v.isSet +} + +func (v *NullableResources) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResources(val *Resources) *NullableResources { + return &NullableResources{value: val, isSet: true} +} + +func (v NullableResources) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResources) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_condition_sets_v2_schema__proj_id___env_id__condition_sets_get.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_condition_sets_v2_schema__proj_id___env_id__condition_sets_get.go new file mode 100644 index 00000000..9ceebd95 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_condition_sets_v2_schema__proj_id___env_id__condition_sets_get.go @@ -0,0 +1,103 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet struct for ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet +type ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet struct { + PaginatedResultConditionSetRead *PaginatedResultConditionSetRead + ConditionSetRead *[]ConditionSetRead +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into PaginatedResultConditionSetRead + err = json.Unmarshal(data, &dst.PaginatedResultConditionSetRead) + if err == nil { + jsonPaginatedResultConditionSetRead, _ := json.Marshal(dst.PaginatedResultConditionSetRead) + if string(jsonPaginatedResultConditionSetRead) == "{}" { // empty struct + dst.PaginatedResultConditionSetRead = nil + } else { + return nil // data stored in dst.PaginatedResultConditionSetRead, return on the first match + } + } else { + dst.PaginatedResultConditionSetRead = nil + } + + // try to unmarshal JSON data into []ConditionSetRead + err = json.Unmarshal(data, &dst.ConditionSetRead) + if err == nil { + jsonConditionSetRead, _ := json.Marshal(dst.ConditionSetRead) + if string(jsonConditionSetRead) == "{}" { // empty struct + dst.ConditionSetRead = nil + } else { + return nil // data stored in dst.[]ConditionSetRead, return on the first match + } + } else { + dst.ConditionSetRead = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) MarshalJSON() ([]byte, error) { + if src.PaginatedResultConditionSetRead != nil { + return json.Marshal(&src.PaginatedResultConditionSetRead) + } + + if src.ConditionSetRead != nil { + return json.Marshal(&src.ConditionSetRead) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet struct { + value *ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet + isSet bool +} + +func (v NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) Get() *ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet { + return v.value +} + +func (v *NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) Set(val *ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) { + v.value = val + v.isSet = true +} + +func (v NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) IsSet() bool { + return v.isSet +} + +func (v *NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet(val *ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) *NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet { + return &NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet{value: val, isSet: true} +} + +func (v NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_role_assignments_v2_facts__proj_id___env_id__role_assignments_get.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_role_assignments_v2_facts__proj_id___env_id__role_assignments_get.go new file mode 100644 index 00000000..b831b89c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_response_list_role_assignments_v2_facts__proj_id___env_id__role_assignments_get.go @@ -0,0 +1,103 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet struct for ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet +type ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet struct { + RoleAssignmentDetailedRead *[]RoleAssignmentDetailedRead + RoleAssignmentRead *[]RoleAssignmentRead +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into []RoleAssignmentDetailedRead + err = json.Unmarshal(data, &dst.RoleAssignmentDetailedRead) + if err == nil { + jsonRoleAssignmentDetailedRead, _ := json.Marshal(dst.RoleAssignmentDetailedRead) + if string(jsonRoleAssignmentDetailedRead) == "{}" { // empty struct + dst.RoleAssignmentDetailedRead = nil + } else { + return nil // data stored in dst.RoleAssignmentDetailedRead, return on the first match + } + } else { + dst.RoleAssignmentDetailedRead = nil + } + + // try to unmarshal JSON data into []RoleAssignmentRead + err = json.Unmarshal(data, &dst.RoleAssignmentRead) + if err == nil { + jsonRoleAssignmentRead, _ := json.Marshal(dst.RoleAssignmentRead) + if string(jsonRoleAssignmentRead) == "{}" { // empty struct + dst.RoleAssignmentRead = nil + } else { + return nil // data stored in dst.RoleAssignmentRead, return on the first match + } + } else { + dst.RoleAssignmentRead = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) MarshalJSON() ([]byte, error) { + if src.RoleAssignmentDetailedRead != nil { + return json.Marshal(&src.RoleAssignmentDetailedRead) + } + + if src.RoleAssignmentRead != nil { + return json.Marshal(&src.RoleAssignmentRead) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet struct { + value *ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet + isSet bool +} + +func (v NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) Get() *ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet { + return v.value +} + +func (v *NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) Set(val *ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) { + v.value = val + v.isSet = true +} + +func (v NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) IsSet() bool { + return v.isSet +} + +func (v *NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet(val *ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) *NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet { + return &NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet{value: val, isSet: true} +} + +func (v NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_create.go new file mode 100644 index 00000000..9c3a10db --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_create.go @@ -0,0 +1,253 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// checks if the RoleAssignmentCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentCreate{} + +// RoleAssignmentCreate struct for RoleAssignmentCreate +type RoleAssignmentCreate struct { + // the role that will be assigned (accepts either the role id or the role key) + Role string `json:"role"` + // the tenant the role is associated with (accepts either the tenant id or the tenant key) + Tenant string `json:"tenant"` + // the resource instance the role is associated with (accepts either the resource instance id or key using this format resource_type:resource_instance) + ResourceInstance *string `json:"resource_instance,omitempty"` + // the user the role will be assigned to (accepts either the user id or the user key) + User string `json:"user"` +} + +type _RoleAssignmentCreate RoleAssignmentCreate + +// NewRoleAssignmentCreate instantiates a new RoleAssignmentCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentCreate(role string, tenant string, user string) *RoleAssignmentCreate { + this := RoleAssignmentCreate{} + this.Role = role + this.Tenant = tenant + this.User = user + return &this +} + +// NewRoleAssignmentCreateWithDefaults instantiates a new RoleAssignmentCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentCreateWithDefaults() *RoleAssignmentCreate { + this := RoleAssignmentCreate{} + return &this +} + +// GetRole returns the Role field value +func (o *RoleAssignmentCreate) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentCreate) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *RoleAssignmentCreate) SetRole(v string) { + o.Role = v +} + +// GetTenant returns the Tenant field value +func (o *RoleAssignmentCreate) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentCreate) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *RoleAssignmentCreate) SetTenant(v string) { + o.Tenant = v +} + +// GetResourceInstance returns the ResourceInstance field value if set, zero value otherwise. +func (o *RoleAssignmentCreate) GetResourceInstance() string { + if o == nil || IsNil(o.ResourceInstance) { + var ret string + return ret + } + return *o.ResourceInstance +} + +// GetResourceInstanceOk returns a tuple with the ResourceInstance field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentCreate) GetResourceInstanceOk() (*string, bool) { + if o == nil || IsNil(o.ResourceInstance) { + return nil, false + } + return o.ResourceInstance, true +} + +// HasResourceInstance returns a boolean if a field has been set. +func (o *RoleAssignmentCreate) HasResourceInstance() bool { + if o != nil && !IsNil(o.ResourceInstance) { + return true + } + + return false +} + +// SetResourceInstance gets a reference to the given string and assigns it to the ResourceInstance field. +func (o *RoleAssignmentCreate) SetResourceInstance(v string) { + o.ResourceInstance = &v +} + +// GetUser returns the User field value +func (o *RoleAssignmentCreate) GetUser() string { + if o == nil { + var ret string + return ret + } + + return o.User +} + +// GetUserOk returns a tuple with the User field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentCreate) GetUserOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.User, true +} + +// SetUser sets field value +func (o *RoleAssignmentCreate) SetUser(v string) { + o.User = v +} + +func (o RoleAssignmentCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["role"] = o.Role + if !IsNil(o.Tenant) { + toSerialize["tenant"] = o.Tenant + } + if !IsNil(o.ResourceInstance) { + toSerialize["resource_instance"] = o.ResourceInstance + } + toSerialize["user"] = o.User + return toSerialize, nil +} + +func (o *RoleAssignmentCreate) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "role", + "user", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRoleAssignmentCreate := _RoleAssignmentCreate{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varRoleAssignmentCreate) + + if err != nil { + return err + } + + *o = RoleAssignmentCreate(varRoleAssignmentCreate) + + return err +} + +type NullableRoleAssignmentCreate struct { + value *RoleAssignmentCreate + isSet bool +} + +func (v NullableRoleAssignmentCreate) Get() *RoleAssignmentCreate { + return v.value +} + +func (v *NullableRoleAssignmentCreate) Set(val *RoleAssignmentCreate) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentCreate(val *RoleAssignmentCreate) *NullableRoleAssignmentCreate { + return &NullableRoleAssignmentCreate{value: val, isSet: true} +} + +func (v NullableRoleAssignmentCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_detailed_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_detailed_read.go new file mode 100644 index 00000000..a8635ef5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_detailed_read.go @@ -0,0 +1,397 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "bytes" + "encoding/json" + "fmt" + "time" +) + +// checks if the RoleAssignmentDetailedRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentDetailedRead{} + +// RoleAssignmentDetailedRead struct for RoleAssignmentDetailedRead +type RoleAssignmentDetailedRead struct { + // Unique id of the role assignment + Id string `json:"id"` + // the role that is assigned + Role RoleAssignmentRole `json:"role"` + // the user the role is assigned to + User RoleAssignmentUser `json:"user"` + // the tenant the role is associated with + Tenant RoleAssignmentTenant `json:"tenant"` + ResourceInstance *RoleAssignmentResourceInstance `json:"resource_instance,omitempty"` + // Unique id of the organization that the role assignment belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the role assignment belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the role assignment belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the role assignment was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` +} + +type _RoleAssignmentDetailedRead RoleAssignmentDetailedRead + +// NewRoleAssignmentDetailedRead instantiates a new RoleAssignmentDetailedRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentDetailedRead(id string, role RoleAssignmentRole, user RoleAssignmentUser, tenant RoleAssignmentTenant, organizationId string, projectId string, environmentId string, createdAt time.Time) *RoleAssignmentDetailedRead { + this := RoleAssignmentDetailedRead{} + this.Id = id + this.Role = role + this.User = user + this.Tenant = tenant + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + return &this +} + +// NewRoleAssignmentDetailedReadWithDefaults instantiates a new RoleAssignmentDetailedRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentDetailedReadWithDefaults() *RoleAssignmentDetailedRead { + this := RoleAssignmentDetailedRead{} + return &this +} + +// GetId returns the Id field value +func (o *RoleAssignmentDetailedRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleAssignmentDetailedRead) SetId(v string) { + o.Id = v +} + +// GetRole returns the Role field value +func (o *RoleAssignmentDetailedRead) GetRole() RoleAssignmentRole { + if o == nil { + var ret RoleAssignmentRole + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetRoleOk() (*RoleAssignmentRole, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *RoleAssignmentDetailedRead) SetRole(v RoleAssignmentRole) { + o.Role = v +} + +// GetUser returns the User field value +func (o *RoleAssignmentDetailedRead) GetUser() RoleAssignmentUser { + if o == nil { + var ret RoleAssignmentUser + return ret + } + + return o.User +} + +// GetUserOk returns a tuple with the User field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetUserOk() (*RoleAssignmentUser, bool) { + if o == nil { + return nil, false + } + return &o.User, true +} + +// SetUser sets field value +func (o *RoleAssignmentDetailedRead) SetUser(v RoleAssignmentUser) { + o.User = v +} + +// GetTenant returns the Tenant field value +func (o *RoleAssignmentDetailedRead) GetTenant() RoleAssignmentTenant { + if o == nil { + var ret RoleAssignmentTenant + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetTenantOk() (*RoleAssignmentTenant, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *RoleAssignmentDetailedRead) SetTenant(v RoleAssignmentTenant) { + o.Tenant = v +} + +// GetResourceInstance returns the ResourceInstance field value if set, zero value otherwise. +func (o *RoleAssignmentDetailedRead) GetResourceInstance() RoleAssignmentResourceInstance { + if o == nil || IsNil(o.ResourceInstance) { + var ret RoleAssignmentResourceInstance + return ret + } + return *o.ResourceInstance +} + +// GetResourceInstanceOk returns a tuple with the ResourceInstance field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetResourceInstanceOk() (*RoleAssignmentResourceInstance, bool) { + if o == nil || IsNil(o.ResourceInstance) { + return nil, false + } + return o.ResourceInstance, true +} + +// HasResourceInstance returns a boolean if a field has been set. +func (o *RoleAssignmentDetailedRead) HasResourceInstance() bool { + if o != nil && !IsNil(o.ResourceInstance) { + return true + } + + return false +} + +// SetResourceInstance gets a reference to the given RoleAssignmentResourceInstance and assigns it to the ResourceInstance field. +func (o *RoleAssignmentDetailedRead) SetResourceInstance(v RoleAssignmentResourceInstance) { + o.ResourceInstance = &v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *RoleAssignmentDetailedRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *RoleAssignmentDetailedRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *RoleAssignmentDetailedRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *RoleAssignmentDetailedRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *RoleAssignmentDetailedRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *RoleAssignmentDetailedRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *RoleAssignmentDetailedRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentDetailedRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *RoleAssignmentDetailedRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +func (o RoleAssignmentDetailedRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentDetailedRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["role"] = o.Role + toSerialize["user"] = o.User + toSerialize["tenant"] = o.Tenant + if !IsNil(o.ResourceInstance) { + toSerialize["resource_instance"] = o.ResourceInstance + } + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + return toSerialize, nil +} + +func (o *RoleAssignmentDetailedRead) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "id", + "role", + "user", + "tenant", + "organization_id", + "project_id", + "environment_id", + "created_at", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRoleAssignmentDetailedRead := _RoleAssignmentDetailedRead{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varRoleAssignmentDetailedRead) + + if err != nil { + return err + } + + *o = RoleAssignmentDetailedRead(varRoleAssignmentDetailedRead) + + return err +} + +type NullableRoleAssignmentDetailedRead struct { + value *RoleAssignmentDetailedRead + isSet bool +} + +func (v NullableRoleAssignmentDetailedRead) Get() *RoleAssignmentDetailedRead { + return v.value +} + +func (v *NullableRoleAssignmentDetailedRead) Set(val *RoleAssignmentDetailedRead) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentDetailedRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentDetailedRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentDetailedRead(val *RoleAssignmentDetailedRead) *NullableRoleAssignmentDetailedRead { + return &NullableRoleAssignmentDetailedRead{value: val, isSet: true} +} + +func (v NullableRoleAssignmentDetailedRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentDetailedRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_read.go new file mode 100644 index 00000000..7e80f674 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_read.go @@ -0,0 +1,522 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "bytes" + "encoding/json" + "fmt" + "time" +) + +// checks if the RoleAssignmentRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentRead{} + +// RoleAssignmentRead struct for RoleAssignmentRead +type RoleAssignmentRead struct { + // Unique id of the role assignment + Id string `json:"id"` + // the user the role is assigned to + User string `json:"user"` + // the role that is assigned + Role string `json:"role"` + // the tenant the role is associated with + Tenant string `json:"tenant"` + // the resource instance the role is associated with + ResourceInstance *string `json:"resource_instance,omitempty"` + // Unique id of the resource instance + ResourceInstanceId *string `json:"resource_instance_id,omitempty"` + // Unique id of the user + UserId string `json:"user_id"` + // Unique id of the role + RoleId string `json:"role_id"` + // Unique id of the tenant + TenantId string `json:"tenant_id"` + // Unique id of the organization that the role assignment belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the role assignment belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the role assignment belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the role assignment was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` +} + +type _RoleAssignmentRead RoleAssignmentRead + +// NewRoleAssignmentRead instantiates a new RoleAssignmentRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentRead(id string, user string, role string, tenant string, userId string, roleId string, tenantId string, organizationId string, projectId string, environmentId string, createdAt time.Time) *RoleAssignmentRead { + this := RoleAssignmentRead{} + this.Id = id + this.User = user + this.Role = role + this.Tenant = tenant + this.UserId = userId + this.RoleId = roleId + this.TenantId = tenantId + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + return &this +} + +// NewRoleAssignmentReadWithDefaults instantiates a new RoleAssignmentRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentReadWithDefaults() *RoleAssignmentRead { + this := RoleAssignmentRead{} + return &this +} + +// GetId returns the Id field value +func (o *RoleAssignmentRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleAssignmentRead) SetId(v string) { + o.Id = v +} + +// GetUser returns the User field value +func (o *RoleAssignmentRead) GetUser() string { + if o == nil { + var ret string + return ret + } + + return o.User +} + +// GetUserOk returns a tuple with the User field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetUserOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.User, true +} + +// SetUser sets field value +func (o *RoleAssignmentRead) SetUser(v string) { + o.User = v +} + +// GetRole returns the Role field value +func (o *RoleAssignmentRead) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *RoleAssignmentRead) SetRole(v string) { + o.Role = v +} + +// GetTenant returns the Tenant field value +func (o *RoleAssignmentRead) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *RoleAssignmentRead) SetTenant(v string) { + o.Tenant = v +} + +// GetResourceInstance returns the ResourceInstance field value if set, zero value otherwise. +func (o *RoleAssignmentRead) GetResourceInstance() string { + if o == nil || IsNil(o.ResourceInstance) { + var ret string + return ret + } + return *o.ResourceInstance +} + +// GetResourceInstanceOk returns a tuple with the ResourceInstance field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetResourceInstanceOk() (*string, bool) { + if o == nil || IsNil(o.ResourceInstance) { + return nil, false + } + return o.ResourceInstance, true +} + +// HasResourceInstance returns a boolean if a field has been set. +func (o *RoleAssignmentRead) HasResourceInstance() bool { + if o != nil && !IsNil(o.ResourceInstance) { + return true + } + + return false +} + +// SetResourceInstance gets a reference to the given string and assigns it to the ResourceInstance field. +func (o *RoleAssignmentRead) SetResourceInstance(v string) { + o.ResourceInstance = &v +} + +// GetResourceInstanceId returns the ResourceInstanceId field value if set, zero value otherwise. +func (o *RoleAssignmentRead) GetResourceInstanceId() string { + if o == nil || IsNil(o.ResourceInstanceId) { + var ret string + return ret + } + return *o.ResourceInstanceId +} + +// GetResourceInstanceIdOk returns a tuple with the ResourceInstanceId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetResourceInstanceIdOk() (*string, bool) { + if o == nil || IsNil(o.ResourceInstanceId) { + return nil, false + } + return o.ResourceInstanceId, true +} + +// HasResourceInstanceId returns a boolean if a field has been set. +func (o *RoleAssignmentRead) HasResourceInstanceId() bool { + if o != nil && !IsNil(o.ResourceInstanceId) { + return true + } + + return false +} + +// SetResourceInstanceId gets a reference to the given string and assigns it to the ResourceInstanceId field. +func (o *RoleAssignmentRead) SetResourceInstanceId(v string) { + o.ResourceInstanceId = &v +} + +// GetUserId returns the UserId field value +func (o *RoleAssignmentRead) GetUserId() string { + if o == nil { + var ret string + return ret + } + + return o.UserId +} + +// GetUserIdOk returns a tuple with the UserId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetUserIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.UserId, true +} + +// SetUserId sets field value +func (o *RoleAssignmentRead) SetUserId(v string) { + o.UserId = v +} + +// GetRoleId returns the RoleId field value +func (o *RoleAssignmentRead) GetRoleId() string { + if o == nil { + var ret string + return ret + } + + return o.RoleId +} + +// GetRoleIdOk returns a tuple with the RoleId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetRoleIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RoleId, true +} + +// SetRoleId sets field value +func (o *RoleAssignmentRead) SetRoleId(v string) { + o.RoleId = v +} + +// GetTenantId returns the TenantId field value +func (o *RoleAssignmentRead) GetTenantId() string { + if o == nil { + var ret string + return ret + } + + return o.TenantId +} + +// GetTenantIdOk returns a tuple with the TenantId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetTenantIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.TenantId, true +} + +// SetTenantId sets field value +func (o *RoleAssignmentRead) SetTenantId(v string) { + o.TenantId = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *RoleAssignmentRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *RoleAssignmentRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *RoleAssignmentRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *RoleAssignmentRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *RoleAssignmentRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *RoleAssignmentRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *RoleAssignmentRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *RoleAssignmentRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +func (o RoleAssignmentRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["user"] = o.User + toSerialize["role"] = o.Role + toSerialize["tenant"] = o.Tenant + + if !IsNil(o.ResourceInstance) { + toSerialize["resource_instance"] = o.ResourceInstance + } + if !IsNil(o.ResourceInstanceId) { + toSerialize["resource_instance_id"] = o.ResourceInstanceId + } + toSerialize["user_id"] = o.UserId + toSerialize["role_id"] = o.RoleId + toSerialize["tenant_id"] = o.TenantId + toSerialize["organization_id"] = o.OrganizationId + toSerialize["project_id"] = o.ProjectId + toSerialize["environment_id"] = o.EnvironmentId + toSerialize["created_at"] = o.CreatedAt + return toSerialize, nil +} + +func (o *RoleAssignmentRead) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "id", + "user", + "role", + "user_id", + "role_id", + "tenant_id", + "organization_id", + "project_id", + "environment_id", + "created_at", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRoleAssignmentRead := _RoleAssignmentRead{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varRoleAssignmentRead) + + if err != nil { + return err + } + + *o = RoleAssignmentRead(varRoleAssignmentRead) + + return err +} + +type NullableRoleAssignmentRead struct { + value *RoleAssignmentRead + isSet bool +} + +func (v NullableRoleAssignmentRead) Get() *RoleAssignmentRead { + return v.value +} + +func (v *NullableRoleAssignmentRead) Set(val *RoleAssignmentRead) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentRead(val *RoleAssignmentRead) *NullableRoleAssignmentRead { + return &NullableRoleAssignmentRead{value: val, isSet: true} +} + +func (v NullableRoleAssignmentRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_remove.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_remove.go new file mode 100644 index 00000000..92241e3c --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_remove.go @@ -0,0 +1,252 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// checks if the RoleAssignmentRemove type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentRemove{} + +// RoleAssignmentRemove struct for RoleAssignmentRemove +type RoleAssignmentRemove struct { + // the role that will be unassigned (accepts either the role id or the role key) + Role string `json:"role"` + // the tenant the role is associated with (accepts either the tenant id or the tenant key) + Tenant string `json:"tenant"` + // the resource instance the role is associated with (accepts either the resource instance id or key using this format resource_type:resource_instance) + ResourceInstance *string `json:"resource_instance,omitempty"` + // the user the role will be unassigned from (accepts either the user id or the user key) + User string `json:"user"` +} + +type _RoleAssignmentRemove RoleAssignmentRemove + +// NewRoleAssignmentRemove instantiates a new RoleAssignmentRemove object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentRemove(role string, tenant string, user string) *RoleAssignmentRemove { + this := RoleAssignmentRemove{} + this.Role = role + this.Tenant = tenant + this.User = user + return &this +} + +// NewRoleAssignmentRemoveWithDefaults instantiates a new RoleAssignmentRemove object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentRemoveWithDefaults() *RoleAssignmentRemove { + this := RoleAssignmentRemove{} + return &this +} + +// GetRole returns the Role field value +func (o *RoleAssignmentRemove) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRemove) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *RoleAssignmentRemove) SetRole(v string) { + o.Role = v +} + +// GetTenant returns the Tenant field value +func (o *RoleAssignmentRemove) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRemove) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *RoleAssignmentRemove) SetTenant(v string) { + o.Tenant = v +} + +// GetResourceInstance returns the ResourceInstance field value if set, zero value otherwise. +func (o *RoleAssignmentRemove) GetResourceInstance() string { + if o == nil || IsNil(o.ResourceInstance) { + var ret string + return ret + } + return *o.ResourceInstance +} + +// GetResourceInstanceOk returns a tuple with the ResourceInstance field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRemove) GetResourceInstanceOk() (*string, bool) { + if o == nil || IsNil(o.ResourceInstance) { + return nil, false + } + return o.ResourceInstance, true +} + +// HasResourceInstance returns a boolean if a field has been set. +func (o *RoleAssignmentRemove) HasResourceInstance() bool { + if o != nil && !IsNil(o.ResourceInstance) { + return true + } + + return false +} + +// SetResourceInstance gets a reference to the given string and assigns it to the ResourceInstance field. +func (o *RoleAssignmentRemove) SetResourceInstance(v string) { + o.ResourceInstance = &v +} + +// GetUser returns the User field value +func (o *RoleAssignmentRemove) GetUser() string { + if o == nil { + var ret string + return ret + } + + return o.User +} + +// GetUserOk returns a tuple with the User field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRemove) GetUserOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.User, true +} + +// SetUser sets field value +func (o *RoleAssignmentRemove) SetUser(v string) { + o.User = v +} + +func (o RoleAssignmentRemove) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentRemove) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["role"] = o.Role + toSerialize["tenant"] = o.Tenant + if !IsNil(o.ResourceInstance) { + toSerialize["resource_instance"] = o.ResourceInstance + } + toSerialize["user"] = o.User + return toSerialize, nil +} + +func (o *RoleAssignmentRemove) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "role", + "tenant", + "user", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRoleAssignmentRemove := _RoleAssignmentRemove{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varRoleAssignmentRemove) + + if err != nil { + return err + } + + *o = RoleAssignmentRemove(varRoleAssignmentRemove) + + return err +} + +type NullableRoleAssignmentRemove struct { + value *RoleAssignmentRemove + isSet bool +} + +func (v NullableRoleAssignmentRemove) Get() *RoleAssignmentRemove { + return v.value +} + +func (v *NullableRoleAssignmentRemove) Set(val *RoleAssignmentRemove) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentRemove) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentRemove) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentRemove(val *RoleAssignmentRemove) *NullableRoleAssignmentRemove { + return &NullableRoleAssignmentRemove{value: val, isSet: true} +} + +func (v NullableRoleAssignmentRemove) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentRemove) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_resource_instance.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_resource_instance.go new file mode 100644 index 00000000..a71c5347 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_resource_instance.go @@ -0,0 +1,248 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// checks if the RoleAssignmentResourceInstance type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentResourceInstance{} + +// RoleAssignmentResourceInstance struct for RoleAssignmentResourceInstance +type RoleAssignmentResourceInstance struct { + Id string `json:"id"` + Key string `json:"key"` + Resource string `json:"resource"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +type _RoleAssignmentResourceInstance RoleAssignmentResourceInstance + +// NewRoleAssignmentResourceInstance instantiates a new RoleAssignmentResourceInstance object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentResourceInstance(id string, key string, resource string) *RoleAssignmentResourceInstance { + this := RoleAssignmentResourceInstance{} + this.Id = id + this.Key = key + this.Resource = resource + return &this +} + +// NewRoleAssignmentResourceInstanceWithDefaults instantiates a new RoleAssignmentResourceInstance object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentResourceInstanceWithDefaults() *RoleAssignmentResourceInstance { + this := RoleAssignmentResourceInstance{} + return &this +} + +// GetId returns the Id field value +func (o *RoleAssignmentResourceInstance) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentResourceInstance) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleAssignmentResourceInstance) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *RoleAssignmentResourceInstance) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentResourceInstance) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RoleAssignmentResourceInstance) SetKey(v string) { + o.Key = v +} + +// GetResource returns the Resource field value +func (o *RoleAssignmentResourceInstance) GetResource() string { + if o == nil { + var ret string + return ret + } + + return o.Resource +} + +// GetResourceOk returns a tuple with the Resource field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentResourceInstance) GetResourceOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Resource, true +} + +// SetResource sets field value +func (o *RoleAssignmentResourceInstance) SetResource(v string) { + o.Resource = v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *RoleAssignmentResourceInstance) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentResourceInstance) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *RoleAssignmentResourceInstance) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *RoleAssignmentResourceInstance) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o RoleAssignmentResourceInstance) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentResourceInstance) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["key"] = o.Key + toSerialize["resource"] = o.Resource + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +func (o *RoleAssignmentResourceInstance) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "id", + "key", + "resource", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRoleAssignmentResourceInstance := _RoleAssignmentResourceInstance{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varRoleAssignmentResourceInstance) + + if err != nil { + return err + } + + *o = RoleAssignmentResourceInstance(varRoleAssignmentResourceInstance) + + return err +} + +type NullableRoleAssignmentResourceInstance struct { + value *RoleAssignmentResourceInstance + isSet bool +} + +func (v NullableRoleAssignmentResourceInstance) Get() *RoleAssignmentResourceInstance { + return v.value +} + +func (v *NullableRoleAssignmentResourceInstance) Set(val *RoleAssignmentResourceInstance) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentResourceInstance) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentResourceInstance) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentResourceInstance(val *RoleAssignmentResourceInstance) *NullableRoleAssignmentResourceInstance { + return &NullableRoleAssignmentResourceInstance{value: val, isSet: true} +} + +func (v NullableRoleAssignmentResourceInstance) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentResourceInstance) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_role.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_role.go new file mode 100644 index 00000000..c7187b7f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_role.go @@ -0,0 +1,142 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RoleAssignmentRole type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentRole{} + +// RoleAssignmentRole struct for RoleAssignmentRole +type RoleAssignmentRole struct { + Id string `json:"id"` + Key string `json:"key"` +} + +// NewRoleAssignmentRole instantiates a new RoleAssignmentRole object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentRole(id string, key string) *RoleAssignmentRole { + this := RoleAssignmentRole{} + this.Id = id + this.Key = key + return &this +} + +// NewRoleAssignmentRoleWithDefaults instantiates a new RoleAssignmentRole object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentRoleWithDefaults() *RoleAssignmentRole { + this := RoleAssignmentRole{} + return &this +} + +// GetId returns the Id field value +func (o *RoleAssignmentRole) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRole) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleAssignmentRole) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *RoleAssignmentRole) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentRole) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RoleAssignmentRole) SetKey(v string) { + o.Key = v +} + +func (o RoleAssignmentRole) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentRole) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["key"] = o.Key + return toSerialize, nil +} + +type NullableRoleAssignmentRole struct { + value *RoleAssignmentRole + isSet bool +} + +func (v NullableRoleAssignmentRole) Get() *RoleAssignmentRole { + return v.value +} + +func (v *NullableRoleAssignmentRole) Set(val *RoleAssignmentRole) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentRole) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentRole) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentRole(val *RoleAssignmentRole) *NullableRoleAssignmentRole { + return &NullableRoleAssignmentRole{value: val, isSet: true} +} + +func (v NullableRoleAssignmentRole) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentRole) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_tenant.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_tenant.go new file mode 100644 index 00000000..e793a7b7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_tenant.go @@ -0,0 +1,205 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RoleAssignmentTenant type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentTenant{} + +// RoleAssignmentTenant struct for RoleAssignmentTenant +type RoleAssignmentTenant struct { + Id string `json:"id"` + Key string `json:"key"` + Name string `json:"name"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewRoleAssignmentTenant instantiates a new RoleAssignmentTenant object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentTenant(id string, key string, name string) *RoleAssignmentTenant { + this := RoleAssignmentTenant{} + this.Id = id + this.Key = key + this.Name = name + return &this +} + +// NewRoleAssignmentTenantWithDefaults instantiates a new RoleAssignmentTenant object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentTenantWithDefaults() *RoleAssignmentTenant { + this := RoleAssignmentTenant{} + return &this +} + +// GetId returns the Id field value +func (o *RoleAssignmentTenant) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentTenant) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleAssignmentTenant) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *RoleAssignmentTenant) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentTenant) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RoleAssignmentTenant) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *RoleAssignmentTenant) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentTenant) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *RoleAssignmentTenant) SetName(v string) { + o.Name = v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *RoleAssignmentTenant) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentTenant) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *RoleAssignmentTenant) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *RoleAssignmentTenant) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o RoleAssignmentTenant) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentTenant) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableRoleAssignmentTenant struct { + value *RoleAssignmentTenant + isSet bool +} + +func (v NullableRoleAssignmentTenant) Get() *RoleAssignmentTenant { + return v.value +} + +func (v *NullableRoleAssignmentTenant) Set(val *RoleAssignmentTenant) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentTenant) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentTenant) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentTenant(val *RoleAssignmentTenant) *NullableRoleAssignmentTenant { + return &NullableRoleAssignmentTenant{value: val, isSet: true} +} + +func (v NullableRoleAssignmentTenant) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentTenant) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_user.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_user.go new file mode 100644 index 00000000..49ae3a9f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_assignment_user.go @@ -0,0 +1,286 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the RoleAssignmentUser type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RoleAssignmentUser{} + +// RoleAssignmentUser struct for RoleAssignmentUser +type RoleAssignmentUser struct { + Id string `json:"id"` + Key string `json:"key"` + Email *string `json:"email,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewRoleAssignmentUser instantiates a new RoleAssignmentUser object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleAssignmentUser(id string, key string) *RoleAssignmentUser { + this := RoleAssignmentUser{} + this.Id = id + this.Key = key + return &this +} + +// NewRoleAssignmentUserWithDefaults instantiates a new RoleAssignmentUser object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleAssignmentUserWithDefaults() *RoleAssignmentUser { + this := RoleAssignmentUser{} + return &this +} + +// GetId returns the Id field value +func (o *RoleAssignmentUser) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentUser) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleAssignmentUser) SetId(v string) { + o.Id = v +} + +// GetKey returns the Key field value +func (o *RoleAssignmentUser) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RoleAssignmentUser) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RoleAssignmentUser) SetKey(v string) { + o.Key = v +} + +// GetEmail returns the Email field value if set, zero value otherwise. +func (o *RoleAssignmentUser) GetEmail() string { + if o == nil || IsNil(o.Email) { + var ret string + return ret + } + return *o.Email +} + +// GetEmailOk returns a tuple with the Email field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentUser) GetEmailOk() (*string, bool) { + if o == nil || IsNil(o.Email) { + return nil, false + } + return o.Email, true +} + +// HasEmail returns a boolean if a field has been set. +func (o *RoleAssignmentUser) HasEmail() bool { + if o != nil && !IsNil(o.Email) { + return true + } + + return false +} + +// SetEmail gets a reference to the given string and assigns it to the Email field. +func (o *RoleAssignmentUser) SetEmail(v string) { + o.Email = &v +} + +// GetFirstName returns the FirstName field value if set, zero value otherwise. +func (o *RoleAssignmentUser) GetFirstName() string { + if o == nil || IsNil(o.FirstName) { + var ret string + return ret + } + return *o.FirstName +} + +// GetFirstNameOk returns a tuple with the FirstName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentUser) GetFirstNameOk() (*string, bool) { + if o == nil || IsNil(o.FirstName) { + return nil, false + } + return o.FirstName, true +} + +// HasFirstName returns a boolean if a field has been set. +func (o *RoleAssignmentUser) HasFirstName() bool { + if o != nil && !IsNil(o.FirstName) { + return true + } + + return false +} + +// SetFirstName gets a reference to the given string and assigns it to the FirstName field. +func (o *RoleAssignmentUser) SetFirstName(v string) { + o.FirstName = &v +} + +// GetLastName returns the LastName field value if set, zero value otherwise. +func (o *RoleAssignmentUser) GetLastName() string { + if o == nil || IsNil(o.LastName) { + var ret string + return ret + } + return *o.LastName +} + +// GetLastNameOk returns a tuple with the LastName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentUser) GetLastNameOk() (*string, bool) { + if o == nil || IsNil(o.LastName) { + return nil, false + } + return o.LastName, true +} + +// HasLastName returns a boolean if a field has been set. +func (o *RoleAssignmentUser) HasLastName() bool { + if o != nil && !IsNil(o.LastName) { + return true + } + + return false +} + +// SetLastName gets a reference to the given string and assigns it to the LastName field. +func (o *RoleAssignmentUser) SetLastName(v string) { + o.LastName = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *RoleAssignmentUser) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleAssignmentUser) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *RoleAssignmentUser) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *RoleAssignmentUser) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o RoleAssignmentUser) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RoleAssignmentUser) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["key"] = o.Key + if !IsNil(o.Email) { + toSerialize["email"] = o.Email + } + if !IsNil(o.FirstName) { + toSerialize["first_name"] = o.FirstName + } + if !IsNil(o.LastName) { + toSerialize["last_name"] = o.LastName + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableRoleAssignmentUser struct { + value *RoleAssignmentUser + isSet bool +} + +func (v NullableRoleAssignmentUser) Get() *RoleAssignmentUser { + return v.value +} + +func (v *NullableRoleAssignmentUser) Set(val *RoleAssignmentUser) { + v.value = val + v.isSet = true +} + +func (v NullableRoleAssignmentUser) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleAssignmentUser) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleAssignmentUser(val *RoleAssignmentUser) *NullableRoleAssignmentUser { + return &NullableRoleAssignmentUser{value: val, isSet: true} +} + +func (v NullableRoleAssignmentUser) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleAssignmentUser) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_block.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_block.go new file mode 100644 index 00000000..74fe3f59 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_block.go @@ -0,0 +1,188 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// RoleBlock struct for RoleBlock +type RoleBlock struct { + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` +} + +// NewRoleBlock instantiates a new RoleBlock object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleBlock() *RoleBlock { + this := RoleBlock{} + return &this +} + +// NewRoleBlockWithDefaults instantiates a new RoleBlock object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleBlockWithDefaults() *RoleBlock { + this := RoleBlock{} + return &this +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RoleBlock) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleBlock) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RoleBlock) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RoleBlock) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *RoleBlock) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleBlock) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *RoleBlock) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *RoleBlock) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *RoleBlock) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleBlock) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *RoleBlock) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *RoleBlock) SetExtends(v []string) { + o.Extends = v +} + +func (o RoleBlock) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + return json.Marshal(toSerialize) +} + +type NullableRoleBlock struct { + value *RoleBlock + isSet bool +} + +func (v NullableRoleBlock) Get() *RoleBlock { + return v.value +} + +func (v *NullableRoleBlock) Set(val *RoleBlock) { + v.value = val + v.isSet = true +} + +func (v NullableRoleBlock) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleBlock) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleBlock(val *RoleBlock) *NullableRoleBlock { + return &NullableRoleBlock{value: val, isSet: true} +} + +func (v NullableRoleBlock) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleBlock) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_create.go new file mode 100644 index 00000000..af44aee3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_create.go @@ -0,0 +1,267 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// RoleCreate struct for RoleCreate +type RoleCreate struct { + // A URL-friendly name of the role (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the role. + Key string `json:"key"` + // The name of the role + Name string `json:"name"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this role. This metadata can be used to filter role using query parameters with attr_ prefix, currently supports only 'equals' operator + Attributes map[string]string `json:"attributes,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` +} + +// NewRoleCreate instantiates a new RoleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleCreate(key string, name string) *RoleCreate { + this := RoleCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewRoleCreateWithDefaults instantiates a new RoleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleCreateWithDefaults() *RoleCreate { + this := RoleCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *RoleCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RoleCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RoleCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *RoleCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *RoleCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *RoleCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RoleCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RoleCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RoleCreate) SetDescription(v string) { + o.Description = &v +} + +// SetAttributes gets a reference to the given map and assigns it to the Attributes field. +func (o *RoleCreate) SetAttributes(v map[string]string) { + o.Attributes = v +} + +// GetAttributes returns the Attributes field value. +func (o *RoleCreate) GetAttributes() map[string]string { + if o == nil || IsNil(o.Attributes) { + var ret map[string]string + return ret + } + return o.Attributes +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *RoleCreate) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleCreate) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *RoleCreate) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *RoleCreate) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *RoleCreate) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleCreate) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *RoleCreate) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *RoleCreate) SetExtends(v []string) { + o.Extends = v +} + +func (o RoleCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableRoleCreate struct { + value *RoleCreate + isSet bool +} + +func (v NullableRoleCreate) Get() *RoleCreate { + return v.value +} + +func (v *NullableRoleCreate) Set(val *RoleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableRoleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleCreate(val *RoleCreate) *NullableRoleCreate { + return &NullableRoleCreate{value: val, isSet: true} +} + +func (v NullableRoleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_data.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_data.go new file mode 100644 index 00000000..10b7a80f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_data.go @@ -0,0 +1,113 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// RoleData struct for RoleData +type RoleData struct { + Grants *map[string][]string `json:"grants,omitempty"` +} + +// NewRoleData instantiates a new RoleData object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleData() *RoleData { + this := RoleData{} + return &this +} + +// NewRoleDataWithDefaults instantiates a new RoleData object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleDataWithDefaults() *RoleData { + this := RoleData{} + return &this +} + +// GetGrants returns the Grants field value if set, zero value otherwise. +func (o *RoleData) GetGrants() map[string][]string { + if o == nil || IsNil(o.Grants) { + var ret map[string][]string + return ret + } + return *o.Grants +} + +// GetGrantsOk returns a tuple with the Grants field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleData) GetGrantsOk() (*map[string][]string, bool) { + if o == nil || IsNil(o.Grants) { + return nil, false + } + return o.Grants, true +} + +// HasGrants returns a boolean if a field has been set. +func (o *RoleData) HasGrants() bool { + if o != nil && !IsNil(o.Grants) { + return true + } + + return false +} + +// SetGrants gets a reference to the given map[string][]string and assigns it to the Grants field. +func (o *RoleData) SetGrants(v map[string][]string) { + o.Grants = &v +} + +func (o RoleData) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Grants) { + toSerialize["grants"] = o.Grants + } + return json.Marshal(toSerialize) +} + +type NullableRoleData struct { + value *RoleData + isSet bool +} + +func (v NullableRoleData) Get() *RoleData { + return v.value +} + +func (v *NullableRoleData) Set(val *RoleData) { + v.value = val + v.isSet = true +} + +func (v NullableRoleData) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleData) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleData(val *RoleData) *NullableRoleData { + return &NullableRoleData{value: val, isSet: true} +} + +func (v NullableRoleData) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleData) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_read.go new file mode 100644 index 00000000..413faf21 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_read.go @@ -0,0 +1,438 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// RoleRead struct for RoleRead +type RoleRead struct { + // The name of the role + Name string `json:"name"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this role. This metadata can be used to filter role using query parameters with attr_ prefix, currently supports only 'equals' operator + Attributes map[string]string `json:"attributes,omitempty"` + // A URL-friendly name of the role (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the role. + Key string `json:"key"` + // Unique id of the role + Id string `json:"id"` + // Unique id of the organization that the role belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the role belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the role belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the role was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the role was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` +} + +// NewRoleRead instantiates a new RoleRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleRead(name string, key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time) *RoleRead { + this := RoleRead{} + this.Name = name + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + return &this +} + +// NewRoleReadWithDefaults instantiates a new RoleRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleReadWithDefaults() *RoleRead { + this := RoleRead{} + return &this +} + +// GetName returns the Name field value +func (o *RoleRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *RoleRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RoleRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} +func (o *RoleRead) GetAttributes() map[string]string { + if o == nil || IsNil(o.Attributes) { + var ret map[string]string + return ret + } + return o.Attributes +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RoleRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RoleRead) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *RoleRead) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleRead) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *RoleRead) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *RoleRead) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *RoleRead) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleRead) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *RoleRead) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *RoleRead) SetExtends(v []string) { + o.Extends = v +} + +// GetKey returns the Key field value +func (o *RoleRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *RoleRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *RoleRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *RoleRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *RoleRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *RoleRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *RoleRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *RoleRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *RoleRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *RoleRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *RoleRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *RoleRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *RoleRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *RoleRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *RoleRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +func (o RoleRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + return json.Marshal(toSerialize) +} + +type NullableRoleRead struct { + value *RoleRead + isSet bool +} + +func (v NullableRoleRead) Get() *RoleRead { + return v.value +} + +func (v *NullableRoleRead) Set(val *RoleRead) { + v.value = val + v.isSet = true +} + +func (v NullableRoleRead) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleRead(val *RoleRead) *NullableRoleRead { + return &NullableRoleRead{value: val, isSet: true} +} + +func (v NullableRoleRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_role_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_update.go new file mode 100644 index 00000000..f6e03f46 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_role_update.go @@ -0,0 +1,244 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// RoleUpdate struct for RoleUpdate +type RoleUpdate struct { + // The name of the role + Name *string `json:"name,omitempty"` + // optional description string explaining what this role represents, or what permissions are granted to it. + Description *string `json:"description,omitempty"` + // list of action keys that define what actions this resource role is permitted to do + Permissions []string `json:"permissions,omitempty"` + // optional dictionary of key-value pairs that can be used to store arbitrary metadata about this role. This metadata can be used to filter role using query parameters with attr_ prefix, currently supports only 'equals' operator + Attributes map[string]string `json:"attributes,omitempty"` + // list of role keys that define what roles this role extends. In other words: this role will automatically inherit all the permissions of the given roles in this list. + Extends []string `json:"extends,omitempty"` +} + +// NewRoleUpdate instantiates a new RoleUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRoleUpdate() *RoleUpdate { + this := RoleUpdate{} + return &this +} + +// NewRoleUpdateWithDefaults instantiates a new RoleUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRoleUpdateWithDefaults() *RoleUpdate { + this := RoleUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *RoleUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *RoleUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *RoleUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *RoleUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *RoleUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *RoleUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetPermissions returns the Permissions field value if set, zero value otherwise. +func (o *RoleUpdate) GetPermissions() []string { + if o == nil || IsNil(o.Permissions) { + var ret []string + return ret + } + return o.Permissions +} + +// SetAttributes gets a reference to the given map and assigns it to the Attributes field. +func (o *RoleUpdate) SetAttributes(v map[string]string) { + o.Attributes = v +} + +// GetAttributes returns the Attributes field value. +func (o *RoleUpdate) GetAttributes() map[string]string { + if o == nil || IsNil(o.Attributes) { + var ret map[string]string + return ret + } + return o.Attributes +} + +// GetPermissionsOk returns a tuple with the Permissions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleUpdate) GetPermissionsOk() ([]string, bool) { + if o == nil || IsNil(o.Permissions) { + return nil, false + } + return o.Permissions, true +} + +// HasPermissions returns a boolean if a field has been set. +func (o *RoleUpdate) HasPermissions() bool { + if o != nil && !IsNil(o.Permissions) { + return true + } + + return false +} + +// SetPermissions gets a reference to the given []string and assigns it to the Permissions field. +func (o *RoleUpdate) SetPermissions(v []string) { + o.Permissions = v +} + +// GetExtends returns the Extends field value if set, zero value otherwise. +func (o *RoleUpdate) GetExtends() []string { + if o == nil || IsNil(o.Extends) { + var ret []string + return ret + } + return o.Extends +} + +// GetExtendsOk returns a tuple with the Extends field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RoleUpdate) GetExtendsOk() ([]string, bool) { + if o == nil || IsNil(o.Extends) { + return nil, false + } + return o.Extends, true +} + +// HasExtends returns a boolean if a field has been set. +func (o *RoleUpdate) HasExtends() bool { + if o != nil && !IsNil(o.Extends) { + return true + } + + return false +} + +// SetExtends gets a reference to the given []string and assigns it to the Extends field. +func (o *RoleUpdate) SetExtends(v []string) { + o.Extends = v +} + +func (o RoleUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Permissions) { + toSerialize["permissions"] = o.Permissions + } + if !IsNil(o.Extends) { + toSerialize["extends"] = o.Extends + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableRoleUpdate struct { + value *RoleUpdate + isSet bool +} + +func (v NullableRoleUpdate) Get() *RoleUpdate { + return v.value +} + +func (v *NullableRoleUpdate) Set(val *RoleUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableRoleUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableRoleUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoleUpdate(val *RoleUpdate) *NullableRoleUpdate { + return &NullableRoleUpdate{value: val, isSet: true} +} + +func (v NullableRoleUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoleUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_roles.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_roles.go new file mode 100644 index 00000000..ae653889 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_roles.go @@ -0,0 +1,103 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// CopyEnvironmentScopeRoles struct for CopyEnvironmentScopeRoles +type Roles struct { + PaginatedResultResourceRoleRead *PaginatedResultResourceRoleRead + ResourceRoleRead *[]ResourceRoleRead +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *Roles) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into PaginatedResultResourceRoleRead + err = json.Unmarshal(data, &dst.PaginatedResultResourceRoleRead) + if err == nil { + jsonPaginatedResultResourceRoleRead, _ := json.Marshal(dst.PaginatedResultResourceRoleRead) + if string(jsonPaginatedResultResourceRoleRead) == "{}" { // empty struct + dst.PaginatedResultResourceRoleRead = nil + } else { + return nil // data stored in dst.PaginatedResultResourceRoleRead, return on the first match + } + } else { + dst.PaginatedResultResourceRoleRead = nil + } + + // try to unmarshal JSON data into []ResourceRoleRead + err = json.Unmarshal(data, &dst.ResourceRoleRead) + if err == nil { + jsonResourceRoleRead, _ := json.Marshal(dst.ResourceRoleRead) + if string(jsonResourceRoleRead) == "{}" { // empty struct + dst.ResourceRoleRead = nil + } else { + return nil // data stored in dst.[]ResourceRoleRead, return on the first match + } + } else { + dst.ResourceRoleRead = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(CopyEnvironmentScopeRoles)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *Roles) MarshalJSON() ([]byte, error) { + if src.PaginatedResultResourceRoleRead != nil { + return json.Marshal(&src.PaginatedResultResourceRoleRead) + } + + if src.ResourceRoleRead != nil { + return json.Marshal(&src.ResourceRoleRead) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableRoles struct { + value *Roles + isSet bool +} + +func (v NullableRoles) Get() *Roles { + return v.value +} + +func (v *NullableRoles) Set(val *Roles) { + v.value = val + v.isSet = true +} + +func (v NullableRoles) IsSet() bool { + return v.isSet +} + +func (v *NullableRoles) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRoles(val *Roles) *NullableRoles { + return &NullableRoles{value: val, isSet: true} +} + +func (v NullableRoles) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRoles) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_scope.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_scope.go new file mode 100644 index 00000000..6b0274ac --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_scope.go @@ -0,0 +1,232 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the Scope type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Scope{} + +// Scope Filters to include and exclude copied objects +type Scope struct { + Resources *Resources `json:"resources,omitempty"` + Roles *Roles `json:"roles,omitempty"` + UserSets *UserSets `json:"user_sets,omitempty"` + ResourceSets *ResourceSets `json:"resource_sets,omitempty"` +} + +// NewScope instantiates a new Scope object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewScope() *Scope { + this := Scope{} + return &this +} + +// NewScopeWithDefaults instantiates a new Scope object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewScopeWithDefaults() *Scope { + this := Scope{} + return &this +} + +// GetResources returns the Resources field value if set, zero value otherwise. +func (o *Scope) GetResources() Resources { + if o == nil || IsNil(o.Resources) { + var ret Resources + return ret + } + return *o.Resources +} + +// GetResourcesOk returns a tuple with the Resources field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Scope) GetResourcesOk() (*Resources, bool) { + if o == nil || IsNil(o.Resources) { + return nil, false + } + return o.Resources, true +} + +// HasResources returns a boolean if a field has been set. +func (o *Scope) HasResources() bool { + if o != nil && !IsNil(o.Resources) { + return true + } + + return false +} + +// SetResources gets a reference to the given Resources and assigns it to the Resources field. +func (o *Scope) SetResources(v Resources) { + o.Resources = &v +} + +// GetRoles returns the Roles field value if set, zero value otherwise. +func (o *Scope) GetRoles() Roles { + if o == nil || IsNil(o.Roles) { + var ret Roles + return ret + } + return *o.Roles +} + +// GetRolesOk returns a tuple with the Roles field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Scope) GetRolesOk() (*Roles, bool) { + if o == nil || IsNil(o.Roles) { + return nil, false + } + return o.Roles, true +} + +// HasRoles returns a boolean if a field has been set. +func (o *Scope) HasRoles() bool { + if o != nil && !IsNil(o.Roles) { + return true + } + + return false +} + +// SetRoles gets a reference to the given Roles and assigns it to the Roles field. +func (o *Scope) SetRoles(v Roles) { + o.Roles = &v +} + +// GetUserSets returns the UserSets field value if set, zero value otherwise. +func (o *Scope) GetUserSets() UserSets { + if o == nil || IsNil(o.UserSets) { + var ret UserSets + return ret + } + return *o.UserSets +} + +// GetUserSetsOk returns a tuple with the UserSets field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Scope) GetUserSetsOk() (*UserSets, bool) { + if o == nil || IsNil(o.UserSets) { + return nil, false + } + return o.UserSets, true +} + +// HasUserSets returns a boolean if a field has been set. +func (o *Scope) HasUserSets() bool { + if o != nil && !IsNil(o.UserSets) { + return true + } + + return false +} + +// SetUserSets gets a reference to the given UserSets and assigns it to the UserSets field. +func (o *Scope) SetUserSets(v UserSets) { + o.UserSets = &v +} + +// GetResourceSets returns the ResourceSets field value if set, zero value otherwise. +func (o *Scope) GetResourceSets() ResourceSets { + if o == nil || IsNil(o.ResourceSets) { + var ret ResourceSets + return ret + } + return *o.ResourceSets +} + +// GetResourceSetsOk returns a tuple with the ResourceSets field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Scope) GetResourceSetsOk() (*ResourceSets, bool) { + if o == nil || IsNil(o.ResourceSets) { + return nil, false + } + return o.ResourceSets, true +} + +// HasResourceSets returns a boolean if a field has been set. +func (o *Scope) HasResourceSets() bool { + if o != nil && !IsNil(o.ResourceSets) { + return true + } + + return false +} + +// SetResourceSets gets a reference to the given ResourceSets and assigns it to the ResourceSets field. +func (o *Scope) SetResourceSets(v ResourceSets) { + o.ResourceSets = &v +} + +func (o Scope) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Scope) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Resources) { + toSerialize["resources"] = o.Resources + } + if !IsNil(o.Roles) { + toSerialize["roles"] = o.Roles + } + if !IsNil(o.UserSets) { + toSerialize["user_sets"] = o.UserSets + } + if !IsNil(o.ResourceSets) { + toSerialize["resource_sets"] = o.ResourceSets + } + return toSerialize, nil +} + +type NullableScope struct { + value *Scope + isSet bool +} + +func (v NullableScope) Get() *Scope { + return v.value +} + +func (v *NullableScope) Set(val *Scope) { + v.value = val + v.isSet = true +} + +func (v NullableScope) IsSet() bool { + return v.isSet +} + +func (v *NullableScope) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableScope(val *Scope) *NullableScope { + return &NullableScope{value: val, isSet: true} +} + +func (v NullableScope) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableScope) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_settings.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_settings.go new file mode 100644 index 00000000..3e89e009 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_settings.go @@ -0,0 +1,121 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" +) + +// Settings struct for Settings +type Settings struct { + bool *bool + int32 *int32 + string *string +} + +// Unmarshal JSON data into any of the pointers in the struct +func (dst *Settings) UnmarshalJSON(data []byte) error { + var err error + // try to unmarshal JSON data into bool + err = json.Unmarshal(data, &dst.bool) + if err == nil { + jsonbool, _ := json.Marshal(dst.bool) + if string(jsonbool) == "{}" { // empty struct + dst.bool = nil + } else { + return nil // data stored in dst.bool, return on the first match + } + } else { + dst.bool = nil + } + + // try to unmarshal JSON data into int32 + err = json.Unmarshal(data, &dst.int32) + if err == nil { + jsonint32, _ := json.Marshal(dst.int32) + if string(jsonint32) == "{}" { // empty struct + dst.int32 = nil + } else { + return nil // data stored in dst.int32, return on the first match + } + } else { + dst.int32 = nil + } + + // try to unmarshal JSON data into string + err = json.Unmarshal(data, &dst.string) + if err == nil { + jsonstring, _ := json.Marshal(dst.string) + if string(jsonstring) == "{}" { // empty struct + dst.string = nil + } else { + return nil // data stored in dst.string, return on the first match + } + } else { + dst.string = nil + } + + return fmt.Errorf("data failed to match schemas in anyOf(Settings)") +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src *Settings) MarshalJSON() ([]byte, error) { + if src.bool != nil { + return json.Marshal(&src.bool) + } + + if src.int32 != nil { + return json.Marshal(&src.int32) + } + + if src.string != nil { + return json.Marshal(&src.string) + } + + return nil, nil // no data in anyOf schemas +} + +type NullableSettings struct { + value *Settings + isSet bool +} + +func (v NullableSettings) Get() *Settings { + return v.value +} + +func (v *NullableSettings) Set(val *Settings) { + v.value = val + v.isSet = true +} + +func (v NullableSettings) IsSet() bool { + return v.isSet +} + +func (v *NullableSettings) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableSettings(val *Settings) *NullableSettings { + return &NullableSettings{value: val, isSet: true} +} + +func (v NullableSettings) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableSettings) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_ssh_auth_data.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_ssh_auth_data.go new file mode 100644 index 00000000..157fd151 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_ssh_auth_data.go @@ -0,0 +1,214 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// SSHAuthData struct for SSHAuthData +type SSHAuthData struct { + AuthType *string `json:"auth_type,omitempty"` + // SSH username + Username string `json:"username"` + // SSH public key + PublicKey *string `json:"public_key,omitempty"` + // SSH private key + PrivateKey string `json:"private_key"` +} + +// NewSSHAuthData instantiates a new SSHAuthData object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewSSHAuthData(username string, privateKey string) *SSHAuthData { + this := SSHAuthData{} + var authType string = "ssh" + this.AuthType = &authType + this.Username = username + this.PrivateKey = privateKey + return &this +} + +// NewSSHAuthDataWithDefaults instantiates a new SSHAuthData object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewSSHAuthDataWithDefaults() *SSHAuthData { + this := SSHAuthData{} + var authType string = "ssh" + this.AuthType = &authType + return &this +} + +// GetAuthType returns the AuthType field value if set, zero value otherwise. +func (o *SSHAuthData) GetAuthType() string { + if o == nil || IsNil(o.AuthType) { + var ret string + return ret + } + return *o.AuthType +} + +// GetAuthTypeOk returns a tuple with the AuthType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *SSHAuthData) GetAuthTypeOk() (*string, bool) { + if o == nil || IsNil(o.AuthType) { + return nil, false + } + return o.AuthType, true +} + +// HasAuthType returns a boolean if a field has been set. +func (o *SSHAuthData) HasAuthType() bool { + if o != nil && !IsNil(o.AuthType) { + return true + } + + return false +} + +// SetAuthType gets a reference to the given string and assigns it to the AuthType field. +func (o *SSHAuthData) SetAuthType(v string) { + o.AuthType = &v +} + +// GetUsername returns the Username field value +func (o *SSHAuthData) GetUsername() string { + if o == nil { + var ret string + return ret + } + + return o.Username +} + +// GetUsernameOk returns a tuple with the Username field value +// and a boolean to check if the value has been set. +func (o *SSHAuthData) GetUsernameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Username, true +} + +// SetUsername sets field value +func (o *SSHAuthData) SetUsername(v string) { + o.Username = v +} + +// GetPublicKey returns the PublicKey field value if set, zero value otherwise. +func (o *SSHAuthData) GetPublicKey() string { + if o == nil || IsNil(o.PublicKey) { + var ret string + return ret + } + return *o.PublicKey +} + +// GetPublicKeyOk returns a tuple with the PublicKey field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *SSHAuthData) GetPublicKeyOk() (*string, bool) { + if o == nil || IsNil(o.PublicKey) { + return nil, false + } + return o.PublicKey, true +} + +// HasPublicKey returns a boolean if a field has been set. +func (o *SSHAuthData) HasPublicKey() bool { + if o != nil && !IsNil(o.PublicKey) { + return true + } + + return false +} + +// SetPublicKey gets a reference to the given string and assigns it to the PublicKey field. +func (o *SSHAuthData) SetPublicKey(v string) { + o.PublicKey = &v +} + +// GetPrivateKey returns the PrivateKey field value +func (o *SSHAuthData) GetPrivateKey() string { + if o == nil { + var ret string + return ret + } + + return o.PrivateKey +} + +// GetPrivateKeyOk returns a tuple with the PrivateKey field value +// and a boolean to check if the value has been set. +func (o *SSHAuthData) GetPrivateKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PrivateKey, true +} + +// SetPrivateKey sets field value +func (o *SSHAuthData) SetPrivateKey(v string) { + o.PrivateKey = v +} + +func (o SSHAuthData) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.AuthType) { + toSerialize["auth_type"] = o.AuthType + } + if true { + toSerialize["username"] = o.Username + } + if !IsNil(o.PublicKey) { + toSerialize["public_key"] = o.PublicKey + } + if true { + toSerialize["private_key"] = o.PrivateKey + } + return json.Marshal(toSerialize) +} + +type NullableSSHAuthData struct { + value *SSHAuthData + isSet bool +} + +func (v NullableSSHAuthData) Get() *SSHAuthData { + return v.value +} + +func (v *NullableSSHAuthData) Set(val *SSHAuthData) { + v.value = val + v.isSet = true +} + +func (v NullableSSHAuthData) IsSet() bool { + return v.isSet +} + +func (v *NullableSSHAuthData) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableSSHAuthData(val *SSHAuthData) *NullableSSHAuthData { + return &NullableSSHAuthData{value: val, isSet: true} +} + +func (v NullableSSHAuthData) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableSSHAuthData) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_statistics.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_statistics.go new file mode 100644 index 00000000..ad4ddcd2 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_statistics.go @@ -0,0 +1,251 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// Statistics struct for Statistics +type Statistics struct { + Roles int32 `json:"roles"` + Users int32 `json:"users"` + Policies int32 `json:"policies"` + Resources int32 `json:"resources"` + Tenants int32 `json:"tenants"` + HasDecisionLogs bool `json:"has_decision_logs"` +} + +// NewStatistics instantiates a new Statistics object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewStatistics(roles int32, users int32, policies int32, resources int32, tenants int32, hasDecisionLogs bool) *Statistics { + this := Statistics{} + this.Roles = roles + this.Users = users + this.Policies = policies + this.Resources = resources + this.Tenants = tenants + this.HasDecisionLogs = hasDecisionLogs + return &this +} + +// NewStatisticsWithDefaults instantiates a new Statistics object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewStatisticsWithDefaults() *Statistics { + this := Statistics{} + return &this +} + +// GetRoles returns the Roles field value +func (o *Statistics) GetRoles() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.Roles +} + +// GetRolesOk returns a tuple with the Roles field value +// and a boolean to check if the value has been set. +func (o *Statistics) GetRolesOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.Roles, true +} + +// SetRoles sets field value +func (o *Statistics) SetRoles(v int32) { + o.Roles = v +} + +// GetUsers returns the Users field value +func (o *Statistics) GetUsers() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.Users +} + +// GetUsersOk returns a tuple with the Users field value +// and a boolean to check if the value has been set. +func (o *Statistics) GetUsersOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.Users, true +} + +// SetUsers sets field value +func (o *Statistics) SetUsers(v int32) { + o.Users = v +} + +// GetPolicies returns the Policies field value +func (o *Statistics) GetPolicies() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.Policies +} + +// GetPoliciesOk returns a tuple with the Policies field value +// and a boolean to check if the value has been set. +func (o *Statistics) GetPoliciesOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.Policies, true +} + +// SetPolicies sets field value +func (o *Statistics) SetPolicies(v int32) { + o.Policies = v +} + +// GetResources returns the Resources field value +func (o *Statistics) GetResources() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.Resources +} + +// GetResourcesOk returns a tuple with the Resources field value +// and a boolean to check if the value has been set. +func (o *Statistics) GetResourcesOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.Resources, true +} + +// SetResources sets field value +func (o *Statistics) SetResources(v int32) { + o.Resources = v +} + +// GetTenants returns the Tenants field value +func (o *Statistics) GetTenants() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.Tenants +} + +// GetTenantsOk returns a tuple with the Tenants field value +// and a boolean to check if the value has been set. +func (o *Statistics) GetTenantsOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.Tenants, true +} + +// SetTenants sets field value +func (o *Statistics) SetTenants(v int32) { + o.Tenants = v +} + +// GetHasDecisionLogs returns the HasDecisionLogs field value +func (o *Statistics) GetHasDecisionLogs() bool { + if o == nil { + var ret bool + return ret + } + + return o.HasDecisionLogs +} + +// GetHasDecisionLogsOk returns a tuple with the HasDecisionLogs field value +// and a boolean to check if the value has been set. +func (o *Statistics) GetHasDecisionLogsOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.HasDecisionLogs, true +} + +// SetHasDecisionLogs sets field value +func (o *Statistics) SetHasDecisionLogs(v bool) { + o.HasDecisionLogs = v +} + +func (o Statistics) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["roles"] = o.Roles + } + if true { + toSerialize["users"] = o.Users + } + if true { + toSerialize["policies"] = o.Policies + } + if true { + toSerialize["resources"] = o.Resources + } + if true { + toSerialize["tenants"] = o.Tenants + } + if true { + toSerialize["has_decision_logs"] = o.HasDecisionLogs + } + return json.Marshal(toSerialize) +} + +type NullableStatistics struct { + value *Statistics + isSet bool +} + +func (v NullableStatistics) Get() *Statistics { + return v.value +} + +func (v *NullableStatistics) Set(val *Statistics) { + v.value = val + v.isSet = true +} + +func (v NullableStatistics) IsSet() bool { + return v.isSet +} + +func (v *NullableStatistics) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableStatistics(val *Statistics) *NullableStatistics { + return &NullableStatistics{value: val, isSet: true} +} + +func (v NullableStatistics) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableStatistics) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_stripped_relation_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_stripped_relation_block_read.go new file mode 100644 index 00000000..6f59ff15 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_stripped_relation_block_read.go @@ -0,0 +1,181 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the StrippedRelationBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &StrippedRelationBlockRead{} + +// StrippedRelationBlockRead struct for StrippedRelationBlockRead +type StrippedRelationBlockRead struct { + // A URL-friendly name of the relation (i.e: slug). You will be able to query later using this key instead of the id (UUID) of the relation. + Key string `json:"key"` + // The name of the relation + Name string `json:"name"` + // An optional longer description of what this relation represents in your system + Description *string `json:"description,omitempty"` +} + +// NewStrippedRelationBlockRead instantiates a new StrippedRelationBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewStrippedRelationBlockRead(key string, name string) *StrippedRelationBlockRead { + this := StrippedRelationBlockRead{} + this.Key = key + this.Name = name + return &this +} + +// NewStrippedRelationBlockReadWithDefaults instantiates a new StrippedRelationBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewStrippedRelationBlockReadWithDefaults() *StrippedRelationBlockRead { + this := StrippedRelationBlockRead{} + return &this +} + +// GetKey returns the Key field value +func (o *StrippedRelationBlockRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *StrippedRelationBlockRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *StrippedRelationBlockRead) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *StrippedRelationBlockRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *StrippedRelationBlockRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *StrippedRelationBlockRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *StrippedRelationBlockRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StrippedRelationBlockRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *StrippedRelationBlockRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *StrippedRelationBlockRead) SetDescription(v string) { + o.Description = &v +} + +func (o StrippedRelationBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o StrippedRelationBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + return toSerialize, nil +} + +type NullableStrippedRelationBlockRead struct { + value *StrippedRelationBlockRead + isSet bool +} + +func (v NullableStrippedRelationBlockRead) Get() *StrippedRelationBlockRead { + return v.value +} + +func (v *NullableStrippedRelationBlockRead) Set(val *StrippedRelationBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableStrippedRelationBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableStrippedRelationBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableStrippedRelationBlockRead(val *StrippedRelationBlockRead) *NullableStrippedRelationBlockRead { + return &NullableStrippedRelationBlockRead{value: val, isSet: true} +} + +func (v NullableStrippedRelationBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableStrippedRelationBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_target_env.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_target_env.go new file mode 100644 index 00000000..07583a74 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_target_env.go @@ -0,0 +1,161 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the TargetEnv type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &TargetEnv{} + +// TargetEnv If copying a new environment, the environment configuration. If copying to an existing environment, the environment identifier +type TargetEnv struct { + // Identifier of an existing environment to copy into + Existing *string `json:"existing,omitempty"` + New *New `json:"new,omitempty"` +} + +// NewTargetEnv instantiates a new TargetEnv object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTargetEnv() *TargetEnv { + this := TargetEnv{} + return &this +} + +// NewTargetEnvWithDefaults instantiates a new TargetEnv object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTargetEnvWithDefaults() *TargetEnv { + this := TargetEnv{} + return &this +} + +// GetExisting returns the Existing field value if set, zero value otherwise. +func (o *TargetEnv) GetExisting() string { + if o == nil || IsNil(o.Existing) { + var ret string + return ret + } + return *o.Existing +} + +// GetExistingOk returns a tuple with the Existing field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TargetEnv) GetExistingOk() (*string, bool) { + if o == nil || IsNil(o.Existing) { + return nil, false + } + return o.Existing, true +} + +// HasExisting returns a boolean if a field has been set. +func (o *TargetEnv) HasExisting() bool { + if o != nil && !IsNil(o.Existing) { + return true + } + + return false +} + +// SetExisting gets a reference to the given string and assigns it to the Existing field. +func (o *TargetEnv) SetExisting(v string) { + o.Existing = &v +} + +// GetNew returns the New field value if set, zero value otherwise. +func (o *TargetEnv) GetNew() New { + if o == nil || IsNil(o.New) { + var ret New + return ret + } + return *o.New +} + +// GetNewOk returns a tuple with the New field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TargetEnv) GetNewOk() (*New, bool) { + if o == nil || IsNil(o.New) { + return nil, false + } + return o.New, true +} + +// HasNew returns a boolean if a field has been set. +func (o *TargetEnv) HasNew() bool { + if o != nil && !IsNil(o.New) { + return true + } + + return false +} + +// SetNew gets a reference to the given New and assigns it to the New field. +func (o *TargetEnv) SetNew(v New) { + o.New = &v +} + +func (o TargetEnv) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o TargetEnv) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Existing) { + toSerialize["existing"] = o.Existing + } + if !IsNil(o.New) { + toSerialize["new"] = o.New + } + return toSerialize, nil +} + +type NullableTargetEnv struct { + value *TargetEnv + isSet bool +} + +func (v NullableTargetEnv) Get() *TargetEnv { + return v.value +} + +func (v *NullableTargetEnv) Set(val *TargetEnv) { + v.value = val + v.isSet = true +} + +func (v NullableTargetEnv) IsSet() bool { + return v.isSet +} + +func (v *NullableTargetEnv) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTargetEnv(val *TargetEnv) *NullableTargetEnv { + return &NullableTargetEnv{value: val, isSet: true} +} + +func (v NullableTargetEnv) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTargetEnv) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_block_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_block_read.go new file mode 100644 index 00000000..3a8c96d0 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_block_read.go @@ -0,0 +1,218 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the TenantBlockRead type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &TenantBlockRead{} + +// TenantBlockRead struct for TenantBlockRead +type TenantBlockRead struct { + // A unique id by which Permit will identify the tenant. The tenant key must be url-friendly (slugified). + Key string `json:"key"` + // A descriptive name for the tenant + Name string `json:"name"` + // an optional longer description of the tenant + Description *string `json:"description,omitempty"` + // Arbitraty tenant attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewTenantBlockRead instantiates a new TenantBlockRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTenantBlockRead(key string, name string) *TenantBlockRead { + this := TenantBlockRead{} + this.Key = key + this.Name = name + return &this +} + +// NewTenantBlockReadWithDefaults instantiates a new TenantBlockRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTenantBlockReadWithDefaults() *TenantBlockRead { + this := TenantBlockRead{} + return &this +} + +// GetKey returns the Key field value +func (o *TenantBlockRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *TenantBlockRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *TenantBlockRead) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *TenantBlockRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *TenantBlockRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *TenantBlockRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *TenantBlockRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantBlockRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *TenantBlockRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *TenantBlockRead) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *TenantBlockRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantBlockRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *TenantBlockRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *TenantBlockRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o TenantBlockRead) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o TenantBlockRead) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["key"] = o.Key + toSerialize["name"] = o.Name + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return toSerialize, nil +} + +type NullableTenantBlockRead struct { + value *TenantBlockRead + isSet bool +} + +func (v NullableTenantBlockRead) Get() *TenantBlockRead { + return v.value +} + +func (v *NullableTenantBlockRead) Set(val *TenantBlockRead) { + v.value = val + v.isSet = true +} + +func (v NullableTenantBlockRead) IsSet() bool { + return v.isSet +} + +func (v *NullableTenantBlockRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTenantBlockRead(val *TenantBlockRead) *NullableTenantBlockRead { + return &NullableTenantBlockRead{value: val, isSet: true} +} + +func (v NullableTenantBlockRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTenantBlockRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_create.go new file mode 100644 index 00000000..99232f8d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_create.go @@ -0,0 +1,211 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// TenantCreate struct for TenantCreate +type TenantCreate struct { + // A unique id by which Permit will identify the tenant. The tenant key must be url-friendly (slugified). + Key string `json:"key"` + // A descriptive name for the tenant + Name string `json:"name"` + // an optional longer description of the tenant + Description *string `json:"description,omitempty"` + // Arbitraty tenant attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewTenantCreate instantiates a new TenantCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTenantCreate(key string, name string) *TenantCreate { + this := TenantCreate{} + this.Key = key + this.Name = name + return &this +} + +// NewTenantCreateWithDefaults instantiates a new TenantCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTenantCreateWithDefaults() *TenantCreate { + this := TenantCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *TenantCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *TenantCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *TenantCreate) SetKey(v string) { + o.Key = v +} + +// GetName returns the Name field value +func (o *TenantCreate) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *TenantCreate) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *TenantCreate) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *TenantCreate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantCreate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *TenantCreate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *TenantCreate) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *TenantCreate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantCreate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *TenantCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *TenantCreate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o TenantCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableTenantCreate struct { + value *TenantCreate + isSet bool +} + +func (v NullableTenantCreate) Get() *TenantCreate { + return v.value +} + +func (v *NullableTenantCreate) Set(val *TenantCreate) { + v.value = val + v.isSet = true +} + +func (v NullableTenantCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableTenantCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTenantCreate(val *TenantCreate) *NullableTenantCreate { + return &NullableTenantCreate{value: val, isSet: true} +} + +func (v NullableTenantCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTenantCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_read.go new file mode 100644 index 00000000..db7d5505 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_read.go @@ -0,0 +1,422 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// TenantRead struct for TenantRead +type TenantRead struct { + // A unique id by which Permit will identify the tenant. The tenant key must be url-friendly (slugified). + Key string `json:"key"` + // Unique id of the tenant + Id string `json:"id"` + // Unique id of the organization that the tenant belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the tenant belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the tenant belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the tenant was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the tenant was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // Date and time when the tenant was last active (ISO_8601 format). In other words, this is the last time a permission check was done on a resource belonging to this tenant. + LastActionAt time.Time `json:"last_action_at"` + // A descriptive name for the tenant + Name string `json:"name"` + // an optional longer description of the tenant + Description *string `json:"description,omitempty"` + // Arbitraty tenant attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewTenantRead instantiates a new TenantRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTenantRead(key string, id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, lastActionAt time.Time, name string) *TenantRead { + this := TenantRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.LastActionAt = lastActionAt + this.Name = name + return &this +} + +// NewTenantReadWithDefaults instantiates a new TenantRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTenantReadWithDefaults() *TenantRead { + this := TenantRead{} + return &this +} + +// GetKey returns the Key field value +func (o *TenantRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *TenantRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *TenantRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *TenantRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *TenantRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *TenantRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *TenantRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *TenantRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *TenantRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *TenantRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *TenantRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *TenantRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *TenantRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *TenantRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetLastActionAt returns the LastActionAt field value +func (o *TenantRead) GetLastActionAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.LastActionAt +} + +// GetLastActionAtOk returns a tuple with the LastActionAt field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetLastActionAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.LastActionAt, true +} + +// SetLastActionAt sets field value +func (o *TenantRead) SetLastActionAt(v time.Time) { + o.LastActionAt = v +} + +// GetName returns the Name field value +func (o *TenantRead) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *TenantRead) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *TenantRead) SetName(v string) { + o.Name = v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *TenantRead) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantRead) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *TenantRead) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *TenantRead) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *TenantRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *TenantRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *TenantRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o TenantRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["last_action_at"] = o.LastActionAt + } + if true { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableTenantRead struct { + value *TenantRead + isSet bool +} + +func (v NullableTenantRead) Get() *TenantRead { + return v.value +} + +func (v *NullableTenantRead) Set(val *TenantRead) { + v.value = val + v.isSet = true +} + +func (v NullableTenantRead) IsSet() bool { + return v.isSet +} + +func (v *NullableTenantRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTenantRead(val *TenantRead) *NullableTenantRead { + return &NullableTenantRead{value: val, isSet: true} +} + +func (v NullableTenantRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTenantRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_update.go new file mode 100644 index 00000000..fdfbd397 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_tenant_update.go @@ -0,0 +1,188 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// TenantUpdate struct for TenantUpdate +type TenantUpdate struct { + // A descriptive name for the tenant + Name *string `json:"name,omitempty"` + // an optional longer description of the tenant + Description *string `json:"description,omitempty"` + // Arbitraty tenant attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewTenantUpdate instantiates a new TenantUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTenantUpdate() *TenantUpdate { + this := TenantUpdate{} + return &this +} + +// NewTenantUpdateWithDefaults instantiates a new TenantUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTenantUpdateWithDefaults() *TenantUpdate { + this := TenantUpdate{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *TenantUpdate) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantUpdate) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *TenantUpdate) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *TenantUpdate) SetName(v string) { + o.Name = &v +} + +// GetDescription returns the Description field value if set, zero value otherwise. +func (o *TenantUpdate) GetDescription() string { + if o == nil || IsNil(o.Description) { + var ret string + return ret + } + return *o.Description +} + +// GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantUpdate) GetDescriptionOk() (*string, bool) { + if o == nil || IsNil(o.Description) { + return nil, false + } + return o.Description, true +} + +// HasDescription returns a boolean if a field has been set. +func (o *TenantUpdate) HasDescription() bool { + if o != nil && !IsNil(o.Description) { + return true + } + + return false +} + +// SetDescription gets a reference to the given string and assigns it to the Description field. +func (o *TenantUpdate) SetDescription(v string) { + o.Description = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *TenantUpdate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *TenantUpdate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *TenantUpdate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *TenantUpdate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o TenantUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Description) { + toSerialize["description"] = o.Description + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableTenantUpdate struct { + value *TenantUpdate + isSet bool +} + +func (v NullableTenantUpdate) Get() *TenantUpdate { + return v.value +} + +func (v *NullableTenantUpdate) Set(val *TenantUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableTenantUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableTenantUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTenantUpdate(val *TenantUpdate) *NullableTenantUpdate { + return &NullableTenantUpdate{value: val, isSet: true} +} + +func (v NullableTenantUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTenantUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_create.go new file mode 100644 index 00000000..1ce3b9cb --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_create.go @@ -0,0 +1,255 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserCreate struct for UserCreate +type UserCreate struct { + // A unique id by which Permit will identify the user for permission checks. + Key string `json:"key"` + // The email of the user. If synced, will be unique inside the environment. + Email *string `json:"email,omitempty"` + // First name of the user. + FirstName *string `json:"first_name,omitempty"` + // Last name of the user. + LastName *string `json:"last_name,omitempty"` + // Arbitraty user attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewUserCreate instantiates a new UserCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserCreate(key string) *UserCreate { + this := UserCreate{} + this.Key = key + return &this +} + +// NewUserCreateWithDefaults instantiates a new UserCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserCreateWithDefaults() *UserCreate { + this := UserCreate{} + return &this +} + +// GetKey returns the Key field value +func (o *UserCreate) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *UserCreate) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *UserCreate) SetKey(v string) { + o.Key = v +} + +// GetEmail returns the Email field value if set, zero value otherwise. +func (o *UserCreate) GetEmail() string { + if o == nil || IsNil(o.Email) { + var ret string + return ret + } + return *o.Email +} + +// GetEmailOk returns a tuple with the Email field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserCreate) GetEmailOk() (*string, bool) { + if o == nil || IsNil(o.Email) { + return nil, false + } + return o.Email, true +} + +// HasEmail returns a boolean if a field has been set. +func (o *UserCreate) HasEmail() bool { + if o != nil && !IsNil(o.Email) { + return true + } + + return false +} + +// SetEmail gets a reference to the given string and assigns it to the Email field. +func (o *UserCreate) SetEmail(v string) { + o.Email = &v +} + +// GetFirstName returns the FirstName field value if set, zero value otherwise. +func (o *UserCreate) GetFirstName() string { + if o == nil || IsNil(o.FirstName) { + var ret string + return ret + } + return *o.FirstName +} + +// GetFirstNameOk returns a tuple with the FirstName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserCreate) GetFirstNameOk() (*string, bool) { + if o == nil || IsNil(o.FirstName) { + return nil, false + } + return o.FirstName, true +} + +// HasFirstName returns a boolean if a field has been set. +func (o *UserCreate) HasFirstName() bool { + if o != nil && !IsNil(o.FirstName) { + return true + } + + return false +} + +// SetFirstName gets a reference to the given string and assigns it to the FirstName field. +func (o *UserCreate) SetFirstName(v string) { + o.FirstName = &v +} + +// GetLastName returns the LastName field value if set, zero value otherwise. +func (o *UserCreate) GetLastName() string { + if o == nil || IsNil(o.LastName) { + var ret string + return ret + } + return *o.LastName +} + +// GetLastNameOk returns a tuple with the LastName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserCreate) GetLastNameOk() (*string, bool) { + if o == nil || IsNil(o.LastName) { + return nil, false + } + return o.LastName, true +} + +// HasLastName returns a boolean if a field has been set. +func (o *UserCreate) HasLastName() bool { + if o != nil && !IsNil(o.LastName) { + return true + } + + return false +} + +// SetLastName gets a reference to the given string and assigns it to the LastName field. +func (o *UserCreate) SetLastName(v string) { + o.LastName = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *UserCreate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserCreate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *UserCreate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *UserCreate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o UserCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if !IsNil(o.Email) { + toSerialize["email"] = o.Email + } + if !IsNil(o.FirstName) { + toSerialize["first_name"] = o.FirstName + } + if !IsNil(o.LastName) { + toSerialize["last_name"] = o.LastName + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableUserCreate struct { + value *UserCreate + isSet bool +} + +func (v NullableUserCreate) Get() *UserCreate { + return v.value +} + +func (v *NullableUserCreate) Set(val *UserCreate) { + v.value = val + v.isSet = true +} + +func (v NullableUserCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableUserCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserCreate(val *UserCreate) *NullableUserCreate { + return &NullableUserCreate{value: val, isSet: true} +} + +func (v NullableUserCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_data.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_data.go new file mode 100644 index 00000000..aae6eaf3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_data.go @@ -0,0 +1,149 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserData struct for UserData +type UserData struct { + RoleAssignments *map[string][]string `json:"roleAssignments,omitempty"` + Attributes *map[string]Attributes `json:"attributes,omitempty"` +} + +// NewUserData instantiates a new UserData object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserData() *UserData { + this := UserData{} + return &this +} + +// NewUserDataWithDefaults instantiates a new UserData object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserDataWithDefaults() *UserData { + this := UserData{} + return &this +} + +// GetRoleAssignments returns the RoleAssignments field value if set, zero value otherwise. +func (o *UserData) GetRoleAssignments() map[string][]string { + if o == nil || IsNil(o.RoleAssignments) { + var ret map[string][]string + return ret + } + return *o.RoleAssignments +} + +// GetRoleAssignmentsOk returns a tuple with the RoleAssignments field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserData) GetRoleAssignmentsOk() (*map[string][]string, bool) { + if o == nil || IsNil(o.RoleAssignments) { + return nil, false + } + return o.RoleAssignments, true +} + +// HasRoleAssignments returns a boolean if a field has been set. +func (o *UserData) HasRoleAssignments() bool { + if o != nil && !IsNil(o.RoleAssignments) { + return true + } + + return false +} + +// SetRoleAssignments gets a reference to the given map[string][]string and assigns it to the RoleAssignments field. +func (o *UserData) SetRoleAssignments(v map[string][]string) { + o.RoleAssignments = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *UserData) GetAttributes() map[string]Attributes { + if o == nil || IsNil(o.Attributes) { + var ret map[string]Attributes + return ret + } + return *o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserData) GetAttributesOk() (*map[string]Attributes, bool) { + if o == nil || IsNil(o.Attributes) { + return nil, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *UserData) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]Attributes and assigns it to the Attributes field. +func (o *UserData) SetAttributes(v map[string]Attributes) { + o.Attributes = &v +} + +func (o UserData) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.RoleAssignments) { + toSerialize["roleAssignments"] = o.RoleAssignments + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableUserData struct { + value *UserData + isSet bool +} + +func (v NullableUserData) Get() *UserData { + return v.value +} + +func (v *NullableUserData) Set(val *UserData) { + v.value = val + v.isSet = true +} + +func (v NullableUserData) IsSet() bool { + return v.isSet +} + +func (v *NullableUserData) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserData(val *UserData) *NullableUserData { + return &NullableUserData{value: val, isSet: true} +} + +func (v NullableUserData) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserData) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_login_request_input.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_login_request_input.go new file mode 100644 index 00000000..c44eb8fb --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_login_request_input.go @@ -0,0 +1,137 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserLoginRequestInput struct for UserLoginRequestInput +type UserLoginRequestInput struct { + // ID or key of the user for whom to generate a token + UserId string `json:"user_id"` + // ID or key of the tenant to which access is requested + TenantId string `json:"tenant_id"` +} + +// NewUserLoginRequestInput instantiates a new UserLoginRequestInput object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserLoginRequestInput(userId string, tenantId string) *UserLoginRequestInput { + this := UserLoginRequestInput{} + this.UserId = userId + this.TenantId = tenantId + return &this +} + +// NewUserLoginRequestInputWithDefaults instantiates a new UserLoginRequestInput object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserLoginRequestInputWithDefaults() *UserLoginRequestInput { + this := UserLoginRequestInput{} + return &this +} + +// GetUserId returns the UserId field value +func (o *UserLoginRequestInput) GetUserId() string { + if o == nil { + var ret string + return ret + } + + return o.UserId +} + +// GetUserIdOk returns a tuple with the UserId field value +// and a boolean to check if the value has been set. +func (o *UserLoginRequestInput) GetUserIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.UserId, true +} + +// SetUserId sets field value +func (o *UserLoginRequestInput) SetUserId(v string) { + o.UserId = v +} + +// GetTenantId returns the TenantId field value +func (o *UserLoginRequestInput) GetTenantId() string { + if o == nil { + var ret string + return ret + } + + return o.TenantId +} + +// GetTenantIdOk returns a tuple with the TenantId field value +// and a boolean to check if the value has been set. +func (o *UserLoginRequestInput) GetTenantIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.TenantId, true +} + +// SetTenantId sets field value +func (o *UserLoginRequestInput) SetTenantId(v string) { + o.TenantId = v +} + +func (o UserLoginRequestInput) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["user_id"] = o.UserId + } + if true { + toSerialize["tenant_id"] = o.TenantId + } + return json.Marshal(toSerialize) +} + +type NullableUserLoginRequestInput struct { + value *UserLoginRequestInput + isSet bool +} + +func (v NullableUserLoginRequestInput) Get() *UserLoginRequestInput { + return v.value +} + +func (v *NullableUserLoginRequestInput) Set(val *UserLoginRequestInput) { + v.value = val + v.isSet = true +} + +func (v NullableUserLoginRequestInput) IsSet() bool { + return v.isSet +} + +func (v *NullableUserLoginRequestInput) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserLoginRequestInput(val *UserLoginRequestInput) *NullableUserLoginRequestInput { + return &NullableUserLoginRequestInput{value: val, isSet: true} +} + +func (v NullableUserLoginRequestInput) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserLoginRequestInput) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_read.go new file mode 100644 index 00000000..d2b663f8 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_read.go @@ -0,0 +1,411 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserRead struct for UserRead +type UserRead struct { + // A unique id by which Permit will identify the user for permission checks. + Key string `json:"key"` + // Unique id of the user + Id string `json:"id"` + // Unique id of the organization that the user belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the user belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the user belongs to. + EnvironmentId string `json:"environment_id"` + Roles []UserRole `json:"roles,omitempty"` + // The email of the user. If synced, will be unique inside the environment. + Email *string `json:"email,omitempty"` + // First name of the user. + FirstName *string `json:"first_name,omitempty"` + // Last name of the user. + LastName *string `json:"last_name,omitempty"` + // Arbitraty user attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewUserRead instantiates a new UserRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserRead(key string, id string, organizationId string, projectId string, environmentId string) *UserRead { + this := UserRead{} + this.Key = key + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + return &this +} + +// NewUserReadWithDefaults instantiates a new UserRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserReadWithDefaults() *UserRead { + this := UserRead{} + return &this +} + +// GetKey returns the Key field value +func (o *UserRead) GetKey() string { + if o == nil { + var ret string + return ret + } + + return o.Key +} + +// GetKeyOk returns a tuple with the Key field value +// and a boolean to check if the value has been set. +func (o *UserRead) GetKeyOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Key, true +} + +// SetKey sets field value +func (o *UserRead) SetKey(v string) { + o.Key = v +} + +// GetId returns the Id field value +func (o *UserRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *UserRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *UserRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *UserRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *UserRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *UserRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *UserRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *UserRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *UserRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *UserRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *UserRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *UserRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetRoles returns the Roles field value if set, zero value otherwise. +func (o *UserRead) GetRoles() []UserRole { + if o == nil || IsNil(o.Roles) { + var ret []UserRole + return ret + } + return o.Roles +} + +// GetRolesOk returns a tuple with the Roles field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRead) GetRolesOk() ([]UserRole, bool) { + if o == nil || IsNil(o.Roles) { + return nil, false + } + return o.Roles, true +} + +// HasRoles returns a boolean if a field has been set. +func (o *UserRead) HasRoles() bool { + if o != nil && !IsNil(o.Roles) { + return true + } + + return false +} + +// SetRoles gets a reference to the given []UserRole and assigns it to the Roles field. +func (o *UserRead) SetRoles(v []UserRole) { + o.Roles = v +} + +// GetEmail returns the Email field value if set, zero value otherwise. +func (o *UserRead) GetEmail() string { + if o == nil || IsNil(o.Email) { + var ret string + return ret + } + return *o.Email +} + +// GetEmailOk returns a tuple with the Email field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRead) GetEmailOk() (*string, bool) { + if o == nil || IsNil(o.Email) { + return nil, false + } + return o.Email, true +} + +// HasEmail returns a boolean if a field has been set. +func (o *UserRead) HasEmail() bool { + if o != nil && !IsNil(o.Email) { + return true + } + + return false +} + +// SetEmail gets a reference to the given string and assigns it to the Email field. +func (o *UserRead) SetEmail(v string) { + o.Email = &v +} + +// GetFirstName returns the FirstName field value if set, zero value otherwise. +func (o *UserRead) GetFirstName() string { + if o == nil || IsNil(o.FirstName) { + var ret string + return ret + } + return *o.FirstName +} + +// GetFirstNameOk returns a tuple with the FirstName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRead) GetFirstNameOk() (*string, bool) { + if o == nil || IsNil(o.FirstName) { + return nil, false + } + return o.FirstName, true +} + +// HasFirstName returns a boolean if a field has been set. +func (o *UserRead) HasFirstName() bool { + if o != nil && !IsNil(o.FirstName) { + return true + } + + return false +} + +// SetFirstName gets a reference to the given string and assigns it to the FirstName field. +func (o *UserRead) SetFirstName(v string) { + o.FirstName = &v +} + +// GetLastName returns the LastName field value if set, zero value otherwise. +func (o *UserRead) GetLastName() string { + if o == nil || IsNil(o.LastName) { + var ret string + return ret + } + return *o.LastName +} + +// GetLastNameOk returns a tuple with the LastName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRead) GetLastNameOk() (*string, bool) { + if o == nil || IsNil(o.LastName) { + return nil, false + } + return o.LastName, true +} + +// HasLastName returns a boolean if a field has been set. +func (o *UserRead) HasLastName() bool { + if o != nil && !IsNil(o.LastName) { + return true + } + + return false +} + +// SetLastName gets a reference to the given string and assigns it to the LastName field. +func (o *UserRead) SetLastName(v string) { + o.LastName = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *UserRead) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRead) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *UserRead) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *UserRead) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o UserRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["key"] = o.Key + } + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if !IsNil(o.Roles) { + toSerialize["roles"] = o.Roles + } + if !IsNil(o.Email) { + toSerialize["email"] = o.Email + } + if !IsNil(o.FirstName) { + toSerialize["first_name"] = o.FirstName + } + if !IsNil(o.LastName) { + toSerialize["last_name"] = o.LastName + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableUserRead struct { + value *UserRead + isSet bool +} + +func (v NullableUserRead) Get() *UserRead { + return v.value +} + +func (v *NullableUserRead) Set(val *UserRead) { + v.value = val + v.isSet = true +} + +func (v NullableUserRead) IsSet() bool { + return v.isSet +} + +func (v *NullableUserRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserRead(val *UserRead) *NullableUserRead { + return &NullableUserRead{value: val, isSet: true} +} + +func (v NullableUserRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role.go new file mode 100644 index 00000000..61080682 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role.go @@ -0,0 +1,137 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserRole struct for UserRole +type UserRole struct { + // the role that is assigned + Role string `json:"role"` + // the tenant the role is associated with + Tenant string `json:"tenant"` +} + +// NewUserRole instantiates a new UserRole object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserRole(role string, tenant string) *UserRole { + this := UserRole{} + this.Role = role + this.Tenant = tenant + return &this +} + +// NewUserRoleWithDefaults instantiates a new UserRole object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserRoleWithDefaults() *UserRole { + this := UserRole{} + return &this +} + +// GetRole returns the Role field value +func (o *UserRole) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *UserRole) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *UserRole) SetRole(v string) { + o.Role = v +} + +// GetTenant returns the Tenant field value +func (o *UserRole) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *UserRole) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *UserRole) SetTenant(v string) { + o.Tenant = v +} + +func (o UserRole) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["role"] = o.Role + } + if true { + toSerialize["tenant"] = o.Tenant + } + return json.Marshal(toSerialize) +} + +type NullableUserRole struct { + value *UserRole + isSet bool +} + +func (v NullableUserRole) Get() *UserRole { + return v.value +} + +func (v *NullableUserRole) Set(val *UserRole) { + v.value = val + v.isSet = true +} + +func (v NullableUserRole) IsSet() bool { + return v.isSet +} + +func (v *NullableUserRole) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserRole(val *UserRole) *NullableUserRole { + return &NullableUserRole{value: val, isSet: true} +} + +func (v NullableUserRole) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserRole) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_create.go new file mode 100644 index 00000000..d77261e3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_create.go @@ -0,0 +1,223 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// checks if the UserRoleCreate type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &UserRoleCreate{} + +// UserRoleCreate struct for UserRoleCreate +type UserRoleCreate struct { + // the role that will be assigned (accepts either the role id or the role key) + Role string `json:"role"` + // the tenant the role is associated with (accepts either the tenant id or the tenant key) + Tenant string `json:"tenant"` + // the resource instance the role is associated with (accepts either the resource instance id or key using this format resource_type:resource_instance) + ResourceInstance *string `json:"resource_instance,omitempty"` +} + +type _UserRoleCreate UserRoleCreate + +// NewUserRoleCreate instantiates a new UserRoleCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserRoleCreate(role string, tenant string) *UserRoleCreate { + this := UserRoleCreate{} + this.Role = role + this.Tenant = tenant + return &this +} + +// NewUserRoleCreateWithDefaults instantiates a new UserRoleCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserRoleCreateWithDefaults() *UserRoleCreate { + this := UserRoleCreate{} + return &this +} + +// GetRole returns the Role field value +func (o *UserRoleCreate) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *UserRoleCreate) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *UserRoleCreate) SetRole(v string) { + o.Role = v +} + +// GetTenant returns the Tenant field value +func (o *UserRoleCreate) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *UserRoleCreate) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *UserRoleCreate) SetTenant(v string) { + o.Tenant = v +} + +// GetResourceInstance returns the ResourceInstance field value if set, zero value otherwise. +func (o *UserRoleCreate) GetResourceInstance() string { + if o == nil || IsNil(o.ResourceInstance) { + var ret string + return ret + } + return *o.ResourceInstance +} + +// GetResourceInstanceOk returns a tuple with the ResourceInstance field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRoleCreate) GetResourceInstanceOk() (*string, bool) { + if o == nil || IsNil(o.ResourceInstance) { + return nil, false + } + return o.ResourceInstance, true +} + +// HasResourceInstance returns a boolean if a field has been set. +func (o *UserRoleCreate) HasResourceInstance() bool { + if o != nil && !IsNil(o.ResourceInstance) { + return true + } + + return false +} + +// SetResourceInstance gets a reference to the given string and assigns it to the ResourceInstance field. +func (o *UserRoleCreate) SetResourceInstance(v string) { + o.ResourceInstance = &v +} + +func (o UserRoleCreate) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o UserRoleCreate) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["role"] = o.Role + toSerialize["tenant"] = o.Tenant + if !IsNil(o.ResourceInstance) { + toSerialize["resource_instance"] = o.ResourceInstance + } + return toSerialize, nil +} + +func (o *UserRoleCreate) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "role", + "tenant", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varUserRoleCreate := _UserRoleCreate{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varUserRoleCreate) + + if err != nil { + return err + } + + *o = UserRoleCreate(varUserRoleCreate) + + return err +} + +type NullableUserRoleCreate struct { + value *UserRoleCreate + isSet bool +} + +func (v NullableUserRoleCreate) Get() *UserRoleCreate { + return v.value +} + +func (v *NullableUserRoleCreate) Set(val *UserRoleCreate) { + v.value = val + v.isSet = true +} + +func (v NullableUserRoleCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableUserRoleCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserRoleCreate(val *UserRoleCreate) *NullableUserRoleCreate { + return &NullableUserRoleCreate{value: val, isSet: true} +} + +func (v NullableUserRoleCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserRoleCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_remove.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_remove.go new file mode 100644 index 00000000..09341869 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_role_remove.go @@ -0,0 +1,174 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserRoleRemove struct for UserRoleRemove +type UserRoleRemove struct { + // the role that will be unassigned (accepts either the role id or the role key) + Role string `json:"role"` + // the tenant the role is associated with (accepts either the tenant id or the tenant key) + Tenant string `json:"tenant"` + // the resource instance the role is associated with (accepts either the resource instance id or key using this format resource_type:resource_instance) + ResourceInstance *string `json:"resource_instance,omitempty"` +} + +// NewUserRoleRemove instantiates a new UserRoleRemove object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserRoleRemove(role string, tenant string) *UserRoleRemove { + this := UserRoleRemove{} + this.Role = role + this.Tenant = tenant + return &this +} + +// NewUserRoleRemoveWithDefaults instantiates a new UserRoleRemove object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserRoleRemoveWithDefaults() *UserRoleRemove { + this := UserRoleRemove{} + return &this +} + +// GetRole returns the Role field value +func (o *UserRoleRemove) GetRole() string { + if o == nil { + var ret string + return ret + } + + return o.Role +} + +// GetRoleOk returns a tuple with the Role field value +// and a boolean to check if the value has been set. +func (o *UserRoleRemove) GetRoleOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Role, true +} + +// SetRole sets field value +func (o *UserRoleRemove) SetRole(v string) { + o.Role = v +} + +// GetTenant returns the Tenant field value +func (o *UserRoleRemove) GetTenant() string { + if o == nil { + var ret string + return ret + } + + return o.Tenant +} + +// GetTenantOk returns a tuple with the Tenant field value +// and a boolean to check if the value has been set. +func (o *UserRoleRemove) GetTenantOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Tenant, true +} + +// SetTenant sets field value +func (o *UserRoleRemove) SetTenant(v string) { + o.Tenant = v +} + +// GetResourceInstance returns the ResourceInstance field value if set, zero value otherwise. +func (o *UserRoleRemove) GetResourceInstance() string { + if o == nil || IsNil(o.ResourceInstance) { + var ret string + return ret + } + return *o.ResourceInstance +} + +// GetResourceInstanceOk returns a tuple with the ResourceInstance field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserRoleRemove) GetResourceInstanceOk() (*string, bool) { + if o == nil || IsNil(o.ResourceInstance) { + return nil, false + } + return o.ResourceInstance, true +} + +// HasResourceInstance returns a boolean if a field has been set. +func (o *UserRoleRemove) HasResourceInstance() bool { + if o != nil && !IsNil(o.ResourceInstance) { + return true + } + + return false +} + +// SetResourceInstance gets a reference to the given string and assigns it to the ResourceInstance field. +func (o *UserRoleRemove) SetResourceInstance(v string) { + o.ResourceInstance = &v +} + +func (o UserRoleRemove) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["role"] = o.Role + } + if true { + toSerialize["tenant"] = o.Tenant + } + if o.HasResourceInstance() { + toSerialize["resource_instance"] = o.ResourceInstance + } + return json.Marshal(toSerialize) +} + +type NullableUserRoleRemove struct { + value *UserRoleRemove + isSet bool +} + +func (v NullableUserRoleRemove) Get() *UserRoleRemove { + return v.value +} + +func (v *NullableUserRoleRemove) Set(val *UserRoleRemove) { + v.value = val + v.isSet = true +} + +func (v NullableUserRoleRemove) IsSet() bool { + return v.isSet +} + +func (v *NullableUserRoleRemove) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserRoleRemove(val *UserRoleRemove) *NullableUserRoleRemove { + return &NullableUserRoleRemove{value: val, isSet: true} +} + +func (v NullableUserRoleRemove) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserRoleRemove) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_sets.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_sets.go new file mode 100644 index 00000000..886fd33d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_sets.go @@ -0,0 +1,162 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// checks if the UserSets type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &UserSets{} + +// UserSets User sets to copy +type UserSets struct { + // Objects to include (use * as wildcard) + Include []string `json:"include,omitempty"` + // Object to exclude (use * as wildcard) + Exclude []string `json:"exclude,omitempty"` +} + +// NewUserSets instantiates a new UserSets object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserSets() *UserSets { + this := UserSets{} + return &this +} + +// NewUserSetsWithDefaults instantiates a new UserSets object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserSetsWithDefaults() *UserSets { + this := UserSets{} + return &this +} + +// GetInclude returns the Include field value if set, zero value otherwise. +func (o *UserSets) GetInclude() []string { + if o == nil || IsNil(o.Include) { + var ret []string + return ret + } + return o.Include +} + +// GetIncludeOk returns a tuple with the Include field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserSets) GetIncludeOk() ([]string, bool) { + if o == nil || IsNil(o.Include) { + return nil, false + } + return o.Include, true +} + +// HasInclude returns a boolean if a field has been set. +func (o *UserSets) HasInclude() bool { + if o != nil && !IsNil(o.Include) { + return true + } + + return false +} + +// SetInclude gets a reference to the given []string and assigns it to the Include field. +func (o *UserSets) SetInclude(v []string) { + o.Include = v +} + +// GetExclude returns the Exclude field value if set, zero value otherwise. +func (o *UserSets) GetExclude() []string { + if o == nil || IsNil(o.Exclude) { + var ret []string + return ret + } + return o.Exclude +} + +// GetExcludeOk returns a tuple with the Exclude field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserSets) GetExcludeOk() ([]string, bool) { + if o == nil || IsNil(o.Exclude) { + return nil, false + } + return o.Exclude, true +} + +// HasExclude returns a boolean if a field has been set. +func (o *UserSets) HasExclude() bool { + if o != nil && !IsNil(o.Exclude) { + return true + } + + return false +} + +// SetExclude gets a reference to the given []string and assigns it to the Exclude field. +func (o *UserSets) SetExclude(v []string) { + o.Exclude = v +} + +func (o UserSets) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o UserSets) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Include) { + toSerialize["include"] = o.Include + } + if !IsNil(o.Exclude) { + toSerialize["exclude"] = o.Exclude + } + return toSerialize, nil +} + +type NullableUserSets struct { + value *UserSets + isSet bool +} + +func (v NullableUserSets) Get() *UserSets { + return v.value +} + +func (v *NullableUserSets) Set(val *UserSets) { + v.value = val + v.isSet = true +} + +func (v NullableUserSets) IsSet() bool { + return v.isSet +} + +func (v *NullableUserSets) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserSets(val *UserSets) *NullableUserSets { + return &NullableUserSets{value: val, isSet: true} +} + +func (v NullableUserSets) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserSets) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_user_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_update.go new file mode 100644 index 00000000..893c0328 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_user_update.go @@ -0,0 +1,225 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// UserUpdate struct for UserUpdate +type UserUpdate struct { + // The email of the user. If synced, will be unique inside the environment. + Email *string `json:"email,omitempty"` + // First name of the user. + FirstName *string `json:"first_name,omitempty"` + // Last name of the user. + LastName *string `json:"last_name,omitempty"` + // Arbitraty user attributes that will be used to enforce attribute-based access control policies. + Attributes map[string]interface{} `json:"attributes,omitempty"` +} + +// NewUserUpdate instantiates a new UserUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewUserUpdate() *UserUpdate { + this := UserUpdate{} + return &this +} + +// NewUserUpdateWithDefaults instantiates a new UserUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewUserUpdateWithDefaults() *UserUpdate { + this := UserUpdate{} + return &this +} + +// GetEmail returns the Email field value if set, zero value otherwise. +func (o *UserUpdate) GetEmail() string { + if o == nil || IsNil(o.Email) { + var ret string + return ret + } + return *o.Email +} + +// GetEmailOk returns a tuple with the Email field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserUpdate) GetEmailOk() (*string, bool) { + if o == nil || IsNil(o.Email) { + return nil, false + } + return o.Email, true +} + +// HasEmail returns a boolean if a field has been set. +func (o *UserUpdate) HasEmail() bool { + if o != nil && !IsNil(o.Email) { + return true + } + + return false +} + +// SetEmail gets a reference to the given string and assigns it to the Email field. +func (o *UserUpdate) SetEmail(v string) { + o.Email = &v +} + +// GetFirstName returns the FirstName field value if set, zero value otherwise. +func (o *UserUpdate) GetFirstName() string { + if o == nil || IsNil(o.FirstName) { + var ret string + return ret + } + return *o.FirstName +} + +// GetFirstNameOk returns a tuple with the FirstName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserUpdate) GetFirstNameOk() (*string, bool) { + if o == nil || IsNil(o.FirstName) { + return nil, false + } + return o.FirstName, true +} + +// HasFirstName returns a boolean if a field has been set. +func (o *UserUpdate) HasFirstName() bool { + if o != nil && !IsNil(o.FirstName) { + return true + } + + return false +} + +// SetFirstName gets a reference to the given string and assigns it to the FirstName field. +func (o *UserUpdate) SetFirstName(v string) { + o.FirstName = &v +} + +// GetLastName returns the LastName field value if set, zero value otherwise. +func (o *UserUpdate) GetLastName() string { + if o == nil || IsNil(o.LastName) { + var ret string + return ret + } + return *o.LastName +} + +// GetLastNameOk returns a tuple with the LastName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserUpdate) GetLastNameOk() (*string, bool) { + if o == nil || IsNil(o.LastName) { + return nil, false + } + return o.LastName, true +} + +// HasLastName returns a boolean if a field has been set. +func (o *UserUpdate) HasLastName() bool { + if o != nil && !IsNil(o.LastName) { + return true + } + + return false +} + +// SetLastName gets a reference to the given string and assigns it to the LastName field. +func (o *UserUpdate) SetLastName(v string) { + o.LastName = &v +} + +// GetAttributes returns the Attributes field value if set, zero value otherwise. +func (o *UserUpdate) GetAttributes() map[string]interface{} { + if o == nil || IsNil(o.Attributes) { + var ret map[string]interface{} + return ret + } + return o.Attributes +} + +// GetAttributesOk returns a tuple with the Attributes field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *UserUpdate) GetAttributesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Attributes) { + return map[string]interface{}{}, false + } + return o.Attributes, true +} + +// HasAttributes returns a boolean if a field has been set. +func (o *UserUpdate) HasAttributes() bool { + if o != nil && !IsNil(o.Attributes) { + return true + } + + return false +} + +// SetAttributes gets a reference to the given map[string]interface{} and assigns it to the Attributes field. +func (o *UserUpdate) SetAttributes(v map[string]interface{}) { + o.Attributes = v +} + +func (o UserUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Email) { + toSerialize["email"] = o.Email + } + if !IsNil(o.FirstName) { + toSerialize["first_name"] = o.FirstName + } + if !IsNil(o.LastName) { + toSerialize["last_name"] = o.LastName + } + if !IsNil(o.Attributes) { + toSerialize["attributes"] = o.Attributes + } + return json.Marshal(toSerialize) +} + +type NullableUserUpdate struct { + value *UserUpdate + isSet bool +} + +func (v NullableUserUpdate) Get() *UserUpdate { + return v.value +} + +func (v *NullableUserUpdate) Set(val *UserUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableUserUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableUserUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableUserUpdate(val *UserUpdate) *NullableUserUpdate { + return &NullableUserUpdate{value: val, isSet: true} +} + +func (v NullableUserUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableUserUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_validation_error.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_validation_error.go new file mode 100644 index 00000000..1fb4f2fc --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_validation_error.go @@ -0,0 +1,164 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// ValidationError struct for ValidationError +type ValidationError struct { + Loc []LocationInner `json:"loc"` + Msg string `json:"msg"` + Type string `json:"type"` +} + +// NewValidationError instantiates a new ValidationError object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewValidationError(loc []LocationInner, msg string, type_ string) *ValidationError { + this := ValidationError{} + this.Loc = loc + this.Msg = msg + this.Type = type_ + return &this +} + +// NewValidationErrorWithDefaults instantiates a new ValidationError object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewValidationErrorWithDefaults() *ValidationError { + this := ValidationError{} + return &this +} + +// GetLoc returns the Loc field value +func (o *ValidationError) GetLoc() []LocationInner { + if o == nil { + var ret []LocationInner + return ret + } + + return o.Loc +} + +// GetLocOk returns a tuple with the Loc field value +// and a boolean to check if the value has been set. +func (o *ValidationError) GetLocOk() ([]LocationInner, bool) { + if o == nil { + return nil, false + } + return o.Loc, true +} + +// SetLoc sets field value +func (o *ValidationError) SetLoc(v []LocationInner) { + o.Loc = v +} + +// GetMsg returns the Msg field value +func (o *ValidationError) GetMsg() string { + if o == nil { + var ret string + return ret + } + + return o.Msg +} + +// GetMsgOk returns a tuple with the Msg field value +// and a boolean to check if the value has been set. +func (o *ValidationError) GetMsgOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Msg, true +} + +// SetMsg sets field value +func (o *ValidationError) SetMsg(v string) { + o.Msg = v +} + +// GetType returns the Type field value +func (o *ValidationError) GetType() string { + if o == nil { + var ret string + return ret + } + + return o.Type +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +func (o *ValidationError) GetTypeOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Type, true +} + +// SetType sets field value +func (o *ValidationError) SetType(v string) { + o.Type = v +} + +func (o ValidationError) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["loc"] = o.Loc + } + if true { + toSerialize["msg"] = o.Msg + } + if true { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) +} + +type NullableValidationError struct { + value *ValidationError + isSet bool +} + +func (v NullableValidationError) Get() *ValidationError { + return v.value +} + +func (v *NullableValidationError) Set(val *ValidationError) { + v.value = val + v.isSet = true +} + +func (v NullableValidationError) IsSet() bool { + return v.isSet +} + +func (v *NullableValidationError) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableValidationError(val *ValidationError) *NullableValidationError { + return &NullableValidationError{value: val, isSet: true} +} + +func (v NullableValidationError) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableValidationError) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_create.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_create.go new file mode 100644 index 00000000..88422ef6 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_create.go @@ -0,0 +1,144 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// WebhookCreate struct for WebhookCreate +type WebhookCreate struct { + // The url to POST the webhook to + Url string `json:"url"` + // An optional bearer token to use to authenticate the request + BearerToken *string `json:"bearer_token,omitempty"` +} + +// NewWebhookCreate instantiates a new WebhookCreate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewWebhookCreate(url string) *WebhookCreate { + this := WebhookCreate{} + this.Url = url + return &this +} + +// NewWebhookCreateWithDefaults instantiates a new WebhookCreate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewWebhookCreateWithDefaults() *WebhookCreate { + this := WebhookCreate{} + return &this +} + +// GetUrl returns the Url field value +func (o *WebhookCreate) GetUrl() string { + if o == nil { + var ret string + return ret + } + + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value +// and a boolean to check if the value has been set. +func (o *WebhookCreate) GetUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Url, true +} + +// SetUrl sets field value +func (o *WebhookCreate) SetUrl(v string) { + o.Url = v +} + +// GetBearerToken returns the BearerToken field value if set, zero value otherwise. +func (o *WebhookCreate) GetBearerToken() string { + if o == nil || IsNil(o.BearerToken) { + var ret string + return ret + } + return *o.BearerToken +} + +// GetBearerTokenOk returns a tuple with the BearerToken field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *WebhookCreate) GetBearerTokenOk() (*string, bool) { + if o == nil || IsNil(o.BearerToken) { + return nil, false + } + return o.BearerToken, true +} + +// HasBearerToken returns a boolean if a field has been set. +func (o *WebhookCreate) HasBearerToken() bool { + if o != nil && !IsNil(o.BearerToken) { + return true + } + + return false +} + +// SetBearerToken gets a reference to the given string and assigns it to the BearerToken field. +func (o *WebhookCreate) SetBearerToken(v string) { + o.BearerToken = &v +} + +func (o WebhookCreate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["url"] = o.Url + } + if !IsNil(o.BearerToken) { + toSerialize["bearer_token"] = o.BearerToken + } + return json.Marshal(toSerialize) +} + +type NullableWebhookCreate struct { + value *WebhookCreate + isSet bool +} + +func (v NullableWebhookCreate) Get() *WebhookCreate { + return v.value +} + +func (v *NullableWebhookCreate) Set(val *WebhookCreate) { + v.value = val + v.isSet = true +} + +func (v NullableWebhookCreate) IsSet() bool { + return v.isSet +} + +func (v *NullableWebhookCreate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableWebhookCreate(val *WebhookCreate) *NullableWebhookCreate { + return &NullableWebhookCreate{value: val, isSet: true} +} + +func (v NullableWebhookCreate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableWebhookCreate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_read.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_read.go new file mode 100644 index 00000000..3997f097 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_read.go @@ -0,0 +1,288 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "time" +) + +// WebhookRead struct for WebhookRead +type WebhookRead struct { + // Unique id of the webhook + Id string `json:"id"` + // Unique id of the organization that the webhook belongs to. + OrganizationId string `json:"organization_id"` + // Unique id of the project that the webhook belongs to. + ProjectId string `json:"project_id"` + // Unique id of the environment that the webhook belongs to. + EnvironmentId string `json:"environment_id"` + // Date and time when the webhook was created (ISO_8601 format). + CreatedAt time.Time `json:"created_at"` + // Date and time when the webhook was last updated/modified (ISO_8601 format). + UpdatedAt time.Time `json:"updated_at"` + // The url to POST the webhook to + Url string `json:"url"` +} + +// NewWebhookRead instantiates a new WebhookRead object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewWebhookRead(id string, organizationId string, projectId string, environmentId string, createdAt time.Time, updatedAt time.Time, url string) *WebhookRead { + this := WebhookRead{} + this.Id = id + this.OrganizationId = organizationId + this.ProjectId = projectId + this.EnvironmentId = environmentId + this.CreatedAt = createdAt + this.UpdatedAt = updatedAt + this.Url = url + return &this +} + +// NewWebhookReadWithDefaults instantiates a new WebhookRead object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewWebhookReadWithDefaults() *WebhookRead { + this := WebhookRead{} + return &this +} + +// GetId returns the Id field value +func (o *WebhookRead) GetId() string { + if o == nil { + var ret string + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *WebhookRead) SetId(v string) { + o.Id = v +} + +// GetOrganizationId returns the OrganizationId field value +func (o *WebhookRead) GetOrganizationId() string { + if o == nil { + var ret string + return ret + } + + return o.OrganizationId +} + +// GetOrganizationIdOk returns a tuple with the OrganizationId field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetOrganizationIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.OrganizationId, true +} + +// SetOrganizationId sets field value +func (o *WebhookRead) SetOrganizationId(v string) { + o.OrganizationId = v +} + +// GetProjectId returns the ProjectId field value +func (o *WebhookRead) GetProjectId() string { + if o == nil { + var ret string + return ret + } + + return o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetProjectIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.ProjectId, true +} + +// SetProjectId sets field value +func (o *WebhookRead) SetProjectId(v string) { + o.ProjectId = v +} + +// GetEnvironmentId returns the EnvironmentId field value +func (o *WebhookRead) GetEnvironmentId() string { + if o == nil { + var ret string + return ret + } + + return o.EnvironmentId +} + +// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetEnvironmentIdOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.EnvironmentId, true +} + +// SetEnvironmentId sets field value +func (o *WebhookRead) SetEnvironmentId(v string) { + o.EnvironmentId = v +} + +// GetCreatedAt returns the CreatedAt field value +func (o *WebhookRead) GetCreatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetCreatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.CreatedAt, true +} + +// SetCreatedAt sets field value +func (o *WebhookRead) SetCreatedAt(v time.Time) { + o.CreatedAt = v +} + +// GetUpdatedAt returns the UpdatedAt field value +func (o *WebhookRead) GetUpdatedAt() time.Time { + if o == nil { + var ret time.Time + return ret + } + + return o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + return &o.UpdatedAt, true +} + +// SetUpdatedAt sets field value +func (o *WebhookRead) SetUpdatedAt(v time.Time) { + o.UpdatedAt = v +} + +// GetUrl returns the Url field value +func (o *WebhookRead) GetUrl() string { + if o == nil { + var ret string + return ret + } + + return o.Url +} + +// GetUrlOk returns a tuple with the Url field value +// and a boolean to check if the value has been set. +func (o *WebhookRead) GetUrlOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Url, true +} + +// SetUrl sets field value +func (o *WebhookRead) SetUrl(v string) { + o.Url = v +} + +func (o WebhookRead) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["id"] = o.Id + } + if true { + toSerialize["organization_id"] = o.OrganizationId + } + if true { + toSerialize["project_id"] = o.ProjectId + } + if true { + toSerialize["environment_id"] = o.EnvironmentId + } + if true { + toSerialize["created_at"] = o.CreatedAt + } + if true { + toSerialize["updated_at"] = o.UpdatedAt + } + if true { + toSerialize["url"] = o.Url + } + return json.Marshal(toSerialize) +} + +type NullableWebhookRead struct { + value *WebhookRead + isSet bool +} + +func (v NullableWebhookRead) Get() *WebhookRead { + return v.value +} + +func (v *NullableWebhookRead) Set(val *WebhookRead) { + v.value = val + v.isSet = true +} + +func (v NullableWebhookRead) IsSet() bool { + return v.isSet +} + +func (v *NullableWebhookRead) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableWebhookRead(val *WebhookRead) *NullableWebhookRead { + return &NullableWebhookRead{value: val, isSet: true} +} + +func (v NullableWebhookRead) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableWebhookRead) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_update.go b/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_update.go new file mode 100644 index 00000000..4bbd2cad --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/model_webhook_update.go @@ -0,0 +1,151 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" +) + +// WebhookUpdate struct for WebhookUpdate +type WebhookUpdate struct { + // The url to POST the webhook to + Url *string `json:"url,omitempty"` + // An optional bearer token to use to authenticate the request + BearerToken *string `json:"bearer_token,omitempty"` +} + +// NewWebhookUpdate instantiates a new WebhookUpdate object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewWebhookUpdate() *WebhookUpdate { + this := WebhookUpdate{} + return &this +} + +// NewWebhookUpdateWithDefaults instantiates a new WebhookUpdate object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewWebhookUpdateWithDefaults() *WebhookUpdate { + this := WebhookUpdate{} + return &this +} + +// GetUrl returns the Url field value if set, zero value otherwise. +func (o *WebhookUpdate) GetUrl() string { + if o == nil || IsNil(o.Url) { + var ret string + return ret + } + return *o.Url +} + +// GetUrlOk returns a tuple with the Url field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *WebhookUpdate) GetUrlOk() (*string, bool) { + if o == nil || IsNil(o.Url) { + return nil, false + } + return o.Url, true +} + +// HasUrl returns a boolean if a field has been set. +func (o *WebhookUpdate) HasUrl() bool { + if o != nil && !IsNil(o.Url) { + return true + } + + return false +} + +// SetUrl gets a reference to the given string and assigns it to the Url field. +func (o *WebhookUpdate) SetUrl(v string) { + o.Url = &v +} + +// GetBearerToken returns the BearerToken field value if set, zero value otherwise. +func (o *WebhookUpdate) GetBearerToken() string { + if o == nil || IsNil(o.BearerToken) { + var ret string + return ret + } + return *o.BearerToken +} + +// GetBearerTokenOk returns a tuple with the BearerToken field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *WebhookUpdate) GetBearerTokenOk() (*string, bool) { + if o == nil || IsNil(o.BearerToken) { + return nil, false + } + return o.BearerToken, true +} + +// HasBearerToken returns a boolean if a field has been set. +func (o *WebhookUpdate) HasBearerToken() bool { + if o != nil && !IsNil(o.BearerToken) { + return true + } + + return false +} + +// SetBearerToken gets a reference to the given string and assigns it to the BearerToken field. +func (o *WebhookUpdate) SetBearerToken(v string) { + o.BearerToken = &v +} + +func (o WebhookUpdate) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Url) { + toSerialize["url"] = o.Url + } + if !IsNil(o.BearerToken) { + toSerialize["bearer_token"] = o.BearerToken + } + return json.Marshal(toSerialize) +} + +type NullableWebhookUpdate struct { + value *WebhookUpdate + isSet bool +} + +func (v NullableWebhookUpdate) Get() *WebhookUpdate { + return v.value +} + +func (v *NullableWebhookUpdate) Set(val *WebhookUpdate) { + v.value = val + v.isSet = true +} + +func (v NullableWebhookUpdate) IsSet() bool { + return v.isSet +} + +func (v *NullableWebhookUpdate) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableWebhookUpdate(val *WebhookUpdate) *NullableWebhookUpdate { + return &NullableWebhookUpdate{value: val, isSet: true} +} + +func (v NullableWebhookUpdate) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableWebhookUpdate) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/models/utils.go b/vendor/github.com/permitio/permit-golang/pkg/models/utils.go new file mode 100644 index 00000000..8219d458 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/models/utils.go @@ -0,0 +1,347 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package models + +import ( + "encoding/json" + "reflect" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +// IsNil checks if an input is nil +func IsNil(i interface{}) bool { + if i == nil { + return true + } + switch reflect.TypeOf(i).Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: + return reflect.ValueOf(i).IsNil() + case reflect.Array: + return reflect.ValueOf(i).IsZero() + } + return false +} + +type MappedNullable interface { + ToMap() (map[string]interface{}, error) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_api_keys.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_api_keys.go new file mode 100644 index 00000000..82da8624 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_api_keys.go @@ -0,0 +1,715 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// APIKeysApiService APIKeysApi service +type APIKeysApiService service + +type ApiCreateApiKeyRequest struct { + ctx context.Context + ApiService *APIKeysApiService + aPIKeyCreate *models.APIKeyCreate +} + +func (r ApiCreateApiKeyRequest) APIKeyCreate(aPIKeyCreate models.APIKeyCreate) ApiCreateApiKeyRequest { + r.aPIKeyCreate = &aPIKeyCreate + return r +} + +func (r ApiCreateApiKeyRequest) Execute() (*models.APIKeyRead, *http.Response, error) { + return r.ApiService.CreateApiKeyExecute(r) +} + +/* +CreateApiKey Create Api Key + +Creates a new api_key under the active organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateApiKeyRequest +*/ +func (a *APIKeysApiService) CreateApiKey(ctx context.Context) ApiCreateApiKeyRequest { + return ApiCreateApiKeyRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return APIKeyRead +func (a *APIKeysApiService) CreateApiKeyExecute(r ApiCreateApiKeyRequest) (*models.APIKeyRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.APIKeyRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "APIKeysApiService.CreateApiKey") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/api-key" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.aPIKeyCreate == nil { + return localVarReturnValue, nil, reportError("aPIKeyCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.aPIKeyCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteApiKeyRequest struct { + ctx context.Context + ApiService *APIKeysApiService + apiKeyId string +} + +func (r ApiDeleteApiKeyRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteApiKeyExecute(r) +} + +/* +DeleteApiKey Delete Api Key + +Deletes the api_key and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param apiKeyId The unique id of the API key + @return ApiDeleteApiKeyRequest +*/ +func (a *APIKeysApiService) DeleteApiKey(ctx context.Context, apiKeyId string) ApiDeleteApiKeyRequest { + return ApiDeleteApiKeyRequest{ + ApiService: a, + ctx: ctx, + apiKeyId: apiKeyId, + } +} + +// Execute executes the request +func (a *APIKeysApiService) DeleteApiKeyExecute(r ApiDeleteApiKeyRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "APIKeysApiService.DeleteApiKey") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/api-key/{api_key_id}" + localVarPath = strings.Replace(localVarPath, "{"+"api_key_id"+"}", url.PathEscape(parameterToString(r.apiKeyId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetApiKeyRequest struct { + ctx context.Context + ApiService *APIKeysApiService + apiKeyId string +} + +func (r ApiGetApiKeyRequest) Execute() (*models.APIKeyRead, *http.Response, error) { + return r.ApiService.GetApiKeyExecute(r) +} + +/* +GetApiKey Get Api Key + +Gets a single api_key matching the given api_key_id, if such api_key exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param apiKeyId The unique id of the API key + @return ApiGetApiKeyRequest +*/ +func (a *APIKeysApiService) GetApiKey(ctx context.Context, apiKeyId string) ApiGetApiKeyRequest { + return ApiGetApiKeyRequest{ + ApiService: a, + ctx: ctx, + apiKeyId: apiKeyId, + } +} + +// Execute executes the request +// +// @return APIKeyRead +func (a *APIKeysApiService) GetApiKeyExecute(r ApiGetApiKeyRequest) (*models.APIKeyRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.APIKeyRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "APIKeysApiService.GetApiKey") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/api-key/{api_key_id}" + localVarPath = strings.Replace(localVarPath, "{"+"api_key_id"+"}", url.PathEscape(parameterToString(r.apiKeyId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetApiKeyScopeRequest struct { + ctx context.Context + ApiService *APIKeysApiService +} + +func (r ApiGetApiKeyScopeRequest) Execute() (*models.APIKeyScopeRead, *http.Response, error) { + return r.ApiService.GetApiKeyScopeExecute(r) +} + +/* +GetApiKeyScope Get Api Key Scope + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetApiKeyScopeRequest +*/ +func (a *APIKeysApiService) GetApiKeyScope(ctx context.Context) ApiGetApiKeyScopeRequest { + return ApiGetApiKeyScopeRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return APIKeyScopeRead +func (a *APIKeysApiService) GetApiKeyScopeExecute(r ApiGetApiKeyScopeRequest) (*models.APIKeyScopeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.APIKeyScopeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "APIKeysApiService.GetApiKeyScope") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/api-key/scope" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetEnvironmentApiKeyRequest struct { + ctx context.Context + ApiService *APIKeysApiService + projId string + envId string +} + +func (r ApiGetEnvironmentApiKeyRequest) Execute() (*models.APIKeyRead, *http.Response, error) { + return r.ApiService.GetEnvironmentApiKeyExecute(r) +} + +/* +GetEnvironmentApiKey Get Environment Api Key + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiGetEnvironmentApiKeyRequest +*/ +func (a *APIKeysApiService) GetEnvironmentApiKey(ctx context.Context, projId string, envId string) ApiGetEnvironmentApiKeyRequest { + return ApiGetEnvironmentApiKeyRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return APIKeyRead +func (a *APIKeysApiService) GetEnvironmentApiKeyExecute(r ApiGetEnvironmentApiKeyRequest) (*models.APIKeyRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.APIKeyRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "APIKeysApiService.GetEnvironmentApiKey") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/api-key/{proj_id}/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListApiKeysRequest struct { + ctx context.Context + ApiService *APIKeysApiService + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListApiKeysRequest) Page(page int32) ApiListApiKeysRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListApiKeysRequest) PerPage(perPage int32) ApiListApiKeysRequest { + r.perPage = &perPage + return r +} + +func (r ApiListApiKeysRequest) Execute() (*models.PaginatedResultAPIKeyRead, *http.Response, error) { + return r.ApiService.ListApiKeysExecute(r) +} + +/* +ListApiKeys List Api Keys + +Lists all the api_keys under the active organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiListApiKeysRequest +*/ +func (a *APIKeysApiService) ListApiKeys(ctx context.Context) ApiListApiKeysRequest { + return ApiListApiKeysRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return PaginatedResultAPIKeyRead +func (a *APIKeysApiService) ListApiKeysExecute(r ApiListApiKeysRequest) (*models.PaginatedResultAPIKeyRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultAPIKeyRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "APIKeysApiService.ListApiKeys") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/api-key" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_authentication.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_authentication.go new file mode 100644 index 00000000..9581c9a9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_authentication.go @@ -0,0 +1,916 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// AuthenticationApiService AuthenticationApi service +type AuthenticationApiService service + +type ApiDevLoginRequest struct { + ctx context.Context + ApiService *AuthenticationApiService + devLogin *models.DevLogin +} + +func (r ApiDevLoginRequest) DevLogin(devLogin models.DevLogin) ApiDevLoginRequest { + r.devLogin = &devLogin + return r +} + +func (r ApiDevLoginRequest) Execute() (*http.Response, error) { + return r.ApiService.DevLoginExecute(r) +} + +/* +DevLogin (DEV MODE) Login + +The dev-login endpoints allows a developer inside permit.io to log in with an email address. + +THIS IS ONLY AVAILABLE IN DEV MODE. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiDevLoginRequest +*/ +func (a *AuthenticationApiService) DevLogin(ctx context.Context) ApiDevLoginRequest { + return ApiDevLoginRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +func (a *AuthenticationApiService) DevLoginExecute(r ApiDevLoginRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.DevLogin") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/devlogin" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.devLogin == nil { + return nil, reportError("devLogin is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.devLogin + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiElementsLoginAsRequest struct { + ctx context.Context + ApiService *AuthenticationApiService + userLoginRequestInput *models.UserLoginRequestInput +} + +func (r ApiElementsLoginAsRequest) UserLoginRequestInput(userLoginRequestInput models.UserLoginRequestInput) ApiElementsLoginAsRequest { + r.userLoginRequestInput = &userLoginRequestInput + return r +} + +func (r ApiElementsLoginAsRequest) Execute() (*models.EmbeddedLoginRequestOutput, *http.Response, error) { + return r.ApiService.ElementsLoginAsExecute(r) +} + +/* +ElementsLoginAs Elements Login As + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiElementsLoginAsRequest +*/ +func (a *AuthenticationApiService) ElementsLoginAs(ctx context.Context) ApiElementsLoginAsRequest { + return ApiElementsLoginAsRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return EmbeddedLoginRequestOutput +func (a *AuthenticationApiService) ElementsLoginAsExecute(r ApiElementsLoginAsRequest) (*models.EmbeddedLoginRequestOutput, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.EmbeddedLoginRequestOutput + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.ElementsLoginAs") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/elements_login_as" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.userLoginRequestInput == nil { + return localVarReturnValue, nil, reportError("userLoginRequestInput is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.userLoginRequestInput + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiLoginRequest struct { + ctx context.Context + ApiService *AuthenticationApiService + inviteCode *string +} + +// An optional invite code to an existing organization. If the invite code is provided and is valid, the member will gain access to that organization. +func (r ApiLoginRequest) InviteCode(inviteCode string) ApiLoginRequest { + r.inviteCode = &inviteCode + return r +} + +func (r ApiLoginRequest) Execute() (*models.LoginResult, *http.Response, error) { + return r.ApiService.LoginExecute(r) +} + +/* +Login Login + +The login endpoint allows the frontend app to exchange a user JWT with a user session. +The user session is stored on an httpOnly + secure cookie. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiLoginRequest +*/ +func (a *AuthenticationApiService) Login(ctx context.Context) ApiLoginRequest { + return ApiLoginRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return LoginResult +func (a *AuthenticationApiService) LoginExecute(r ApiLoginRequest) (*models.LoginResult, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.LoginResult + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.Login") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/login" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.inviteCode != nil { + localVarQueryParams.Add("invite_code", parameterToString(*r.inviteCode, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiLoginElementsRequest struct { + ctx context.Context + ApiService *AuthenticationApiService + token *string +} + +func (r ApiLoginElementsRequest) Token(token string) ApiLoginElementsRequest { + r.token = &token + return r +} + +func (r ApiLoginElementsRequest) Execute() (*models.LoginResult, *http.Response, error) { + return r.ApiService.LoginElementsExecute(r) +} + +/* +LoginElements Login Elements + +The login endpoint allows the frontend app to exchange a user JWT with a user session. +The user session is stored on an httpOnly + secure cookie. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiLoginElementsRequest +*/ +func (a *AuthenticationApiService) LoginElements(ctx context.Context) ApiLoginElementsRequest { + return ApiLoginElementsRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return LoginResult +func (a *AuthenticationApiService) LoginElementsExecute(r ApiLoginElementsRequest) (*models.LoginResult, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.LoginResult + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.LoginElements") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/login_elements" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.token == nil { + return localVarReturnValue, nil, reportError("token is required and must be specified") + } + + localVarQueryParams.Add("token", parameterToString(*r.token, "")) + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiLogoutGetRequest struct { + ctx context.Context + ApiService *AuthenticationApiService +} + +func (r ApiLogoutGetRequest) Execute() (*http.Response, error) { + return r.ApiService.LogoutGetExecute(r) +} + +/* +LogoutGet Logout Get + +The logout endpoint deletes the session cookie of a logged in user and invalidates cached VCs. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiLogoutGetRequest +*/ +func (a *AuthenticationApiService) LogoutGet(ctx context.Context) ApiLogoutGetRequest { + return ApiLogoutGetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +func (a *AuthenticationApiService) LogoutGetExecute(r ApiLogoutGetRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.LogoutGet") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/logout" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiLogoutPostRequest struct { + ctx context.Context + ApiService *AuthenticationApiService +} + +func (r ApiLogoutPostRequest) Execute() (*http.Response, error) { + return r.ApiService.LogoutPostExecute(r) +} + +/* +LogoutPost Logout Post + +The logout endpoint deletes the session cookie of a logged in user and invalidates cached VCs. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiLogoutPostRequest +*/ +func (a *AuthenticationApiService) LogoutPost(ctx context.Context) ApiLogoutPostRequest { + return ApiLogoutPostRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +func (a *AuthenticationApiService) LogoutPostExecute(r ApiLogoutPostRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.LogoutPost") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/logout" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiMeRequest struct { + ctx context.Context + ApiService *AuthenticationApiService +} + +func (r ApiMeRequest) Execute() (*models.AuthnMeRead, *http.Response, error) { + return r.ApiService.MeExecute(r) +} + +/* +Me Me + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiMeRequest +*/ +func (a *AuthenticationApiService) Me(ctx context.Context) ApiMeRequest { + return ApiMeRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return AuthnMeRead +func (a *AuthenticationApiService) MeExecute(r ApiMeRequest) (*models.AuthnMeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.AuthnMeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.Me") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/me" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiSwitchOrganizationRequest struct { + ctx context.Context + ApiService *AuthenticationApiService + orgId string +} + +func (r ApiSwitchOrganizationRequest) Execute() (*models.LoginResult, *http.Response, error) { + return r.ApiService.SwitchOrganizationExecute(r) +} + +/* +SwitchOrganization Switch Organization + +Allows the user to switch his active organization (manipulates the user's login session). + +This route will return a new login cookie to the user. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId the organization id the user wishes to switch to as the active org on the session + @return ApiSwitchOrganizationRequest +*/ +func (a *AuthenticationApiService) SwitchOrganization(ctx context.Context, orgId string) ApiSwitchOrganizationRequest { + return ApiSwitchOrganizationRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + } +} + +// Execute executes the request +// +// @return LoginResult +func (a *AuthenticationApiService) SwitchOrganizationExecute(r ApiSwitchOrganizationRequest) (*models.LoginResult, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.LoginResult + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthenticationApiService.SwitchOrganization") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/auth/switch_org/{org_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_set_rules.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_set_rules.go new file mode 100644 index 00000000..4b87a376 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_set_rules.go @@ -0,0 +1,445 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ConditionSetRulesApiService ConditionSetRulesApi service +type ConditionSetRulesApiService service + +type ApiAssignSetPermissionsRequest struct { + ctx context.Context + ApiService *ConditionSetRulesApiService + projId string + envId string + conditionSetRuleCreate *models.ConditionSetRuleCreate +} + +func (r ApiAssignSetPermissionsRequest) ConditionSetRuleCreate(conditionSetRuleCreate models.ConditionSetRuleCreate) ApiAssignSetPermissionsRequest { + r.conditionSetRuleCreate = &conditionSetRuleCreate + return r +} + +func (r ApiAssignSetPermissionsRequest) Execute() ([]models.ConditionSetRuleRead, *http.Response, error) { + return r.ApiService.AssignSetPermissionsExecute(r) +} + +/* +AssignSetPermissions Assign Set Permissions + +Grant permissions to a user set *on* a resource set. + +If the permission is already granted, it is skipped. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiAssignSetPermissionsRequest +*/ +func (a *ConditionSetRulesApiService) AssignSetPermissions(ctx context.Context, projId string, envId string) ApiAssignSetPermissionsRequest { + return ApiAssignSetPermissionsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []ConditionSetRuleRead +func (a *ConditionSetRulesApiService) AssignSetPermissionsExecute(r ApiAssignSetPermissionsRequest) ([]models.ConditionSetRuleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ConditionSetRuleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetRulesApiService.AssignSetPermissions") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/set_rules" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.conditionSetRuleCreate == nil { + return localVarReturnValue, nil, reportError("conditionSetRuleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.conditionSetRuleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListSetPermissionsRequest struct { + ctx context.Context + ApiService *ConditionSetRulesApiService + projId string + envId string + userSet *string + permission *string + resourceSet *string + page *int32 + perPage *int32 +} + +// optional user set filter, will only return rules where the permission is granted to this user set +func (r ApiListSetPermissionsRequest) UserSet(userSet string) ApiListSetPermissionsRequest { + r.userSet = &userSet + return r +} + +// optional permission filter, will only return condition set rules granting this permission +func (r ApiListSetPermissionsRequest) Permission(permission string) ApiListSetPermissionsRequest { + r.permission = &permission + return r +} + +// optional resource set filter, will only return rules where the permission is granted on this resource set +func (r ApiListSetPermissionsRequest) ResourceSet(resourceSet string) ApiListSetPermissionsRequest { + r.resourceSet = &resourceSet + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListSetPermissionsRequest) Page(page int32) ApiListSetPermissionsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListSetPermissionsRequest) PerPage(perPage int32) ApiListSetPermissionsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListSetPermissionsRequest) Execute() ([]models.ConditionSetRuleRead, *http.Response, error) { + return r.ApiService.ListSetPermissionsExecute(r) +} + +/* +ListSetPermissions List Set Permissions + +Lists the condition set rules matching the filter. +- If the `user_set` filter is present, will only return the permissions set of that user set. +- If the `permission` filter is present, will only return the permissions sets that equals to the queried permission. +- If the `resource_set` filter is present, will only return the permissions set of that resource set. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListSetPermissionsRequest +*/ +func (a *ConditionSetRulesApiService) ListSetPermissions(ctx context.Context, projId string, envId string) ApiListSetPermissionsRequest { + return ApiListSetPermissionsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []ConditionSetRuleRead +func (a *ConditionSetRulesApiService) ListSetPermissionsExecute(r ApiListSetPermissionsRequest) ([]models.ConditionSetRuleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ConditionSetRuleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetRulesApiService.ListSetPermissions") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/set_rules" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.userSet != nil { + localVarQueryParams.Add("user_set", parameterToString(*r.userSet, "")) + } + if r.permission != nil { + localVarQueryParams.Add("permission", parameterToString(*r.permission, "")) + } + if r.resourceSet != nil { + localVarQueryParams.Add("resource_set", parameterToString(*r.resourceSet, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUnassignSetPermissionsRequest struct { + ctx context.Context + ApiService *ConditionSetRulesApiService + projId string + envId string + conditionSetRuleRemove *models.ConditionSetRuleRemove +} + +func (r ApiUnassignSetPermissionsRequest) ConditionSetRuleRemove(conditionSetRuleRemove models.ConditionSetRuleRemove) ApiUnassignSetPermissionsRequest { + r.conditionSetRuleRemove = &conditionSetRuleRemove + return r +} + +func (r ApiUnassignSetPermissionsRequest) Execute() (*http.Response, error) { + return r.ApiService.UnassignSetPermissionsExecute(r) +} + +/* +UnassignSetPermissions Unassign Set Permissions + +Revokes permissions to a user set *on* a resource set. + +If the permission is not granted, it is skipped. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiUnassignSetPermissionsRequest +*/ +func (a *ConditionSetRulesApiService) UnassignSetPermissions(ctx context.Context, projId string, envId string) ApiUnassignSetPermissionsRequest { + return ApiUnassignSetPermissionsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +func (a *ConditionSetRulesApiService) UnassignSetPermissionsExecute(r ApiUnassignSetPermissionsRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetRulesApiService.UnassignSetPermissions") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/set_rules" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.conditionSetRuleRemove == nil { + return nil, reportError("conditionSetRuleRemove is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.conditionSetRuleRemove + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_sets.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_sets.go new file mode 100644 index 00000000..941da1ef --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_condition_sets.go @@ -0,0 +1,1104 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ConditionSetsApiService ConditionSetsApi service +type ConditionSetsApiService service + +type ApiCreateConditionSetRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetCreate *models.ConditionSetCreate +} + +func (r ApiCreateConditionSetRequest) ConditionSetCreate(conditionSetCreate models.ConditionSetCreate) ApiCreateConditionSetRequest { + r.conditionSetCreate = &conditionSetCreate + return r +} + +func (r ApiCreateConditionSetRequest) Execute() (*models.ConditionSetRead, *http.Response, error) { + return r.ApiService.CreateConditionSetExecute(r) +} + +/* +CreateConditionSet Create Condition Set + +Creates a new condition set (can be either a user set or a resource set). + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateConditionSetRequest +*/ +func (a *ConditionSetsApiService) CreateConditionSet(ctx context.Context, projId string, envId string) ApiCreateConditionSetRequest { + return ApiCreateConditionSetRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ConditionSetRead +func (a *ConditionSetsApiService) CreateConditionSetExecute(r ApiCreateConditionSetRequest) (*models.ConditionSetRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ConditionSetRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.CreateConditionSet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.conditionSetCreate == nil { + return localVarReturnValue, nil, reportError("conditionSetCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.conditionSetCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteConditionSetRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetId string +} + +func (r ApiDeleteConditionSetRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteConditionSetExecute(r) +} + +/* +DeleteConditionSet Delete Condition Set + +Deletes a condition set and all its related data. +This includes any permissions granted to said condition set (i.e: any matching condition set rules). + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param conditionSetId Either the unique id of the condition set, or the URL-friendly key of the condition set (i.e: the \"slug\"). + @return ApiDeleteConditionSetRequest +*/ +func (a *ConditionSetsApiService) DeleteConditionSet(ctx context.Context, projId string, envId string, conditionSetId string) ApiDeleteConditionSetRequest { + return ApiDeleteConditionSetRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + conditionSetId: conditionSetId, + } +} + +// Execute executes the request +func (a *ConditionSetsApiService) DeleteConditionSetExecute(r ApiDeleteConditionSetRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.DeleteConditionSet") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets/{condition_set_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"condition_set_id"+"}", url.PathEscape(parameterValueToString(r.conditionSetId, "conditionSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetConditionSetRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetId string +} + +func (r ApiGetConditionSetRequest) Execute() (*models.ConditionSetRead, *http.Response, error) { + return r.ApiService.GetConditionSetExecute(r) +} + +/* +GetConditionSet Get Condition Set + +Gets a single condition set, if such condition set exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param conditionSetId Either the unique id of the condition set, or the URL-friendly key of the condition set (i.e: the \"slug\"). + @return ApiGetConditionSetRequest +*/ +func (a *ConditionSetsApiService) GetConditionSet(ctx context.Context, projId string, envId string, conditionSetId string) ApiGetConditionSetRequest { + return ApiGetConditionSetRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + conditionSetId: conditionSetId, + } +} + +// Execute executes the request +// +// @return ConditionSetRead +func (a *ConditionSetsApiService) GetConditionSetExecute(r ApiGetConditionSetRequest) (*models.ConditionSetRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ConditionSetRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.GetConditionSet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets/{condition_set_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"condition_set_id"+"}", url.PathEscape(parameterValueToString(r.conditionSetId, "conditionSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetConditionSetAncestorsRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiGetConditionSetAncestorsRequest) Page(page int32) ApiGetConditionSetAncestorsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiGetConditionSetAncestorsRequest) PerPage(perPage int32) ApiGetConditionSetAncestorsRequest { + r.perPage = &perPage + return r +} + +func (r ApiGetConditionSetAncestorsRequest) Execute() ([]models.ConditionSetRead, *http.Response, error) { + return r.ApiService.GetConditionSetAncestorsExecute(r) +} + +/* +GetConditionSetAncestors Get Condition Set Ancestors + +Gets all ancestors (parent, parent of parent, and so on) + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param conditionSetId Either the unique id of the condition set, or the URL-friendly key of the condition set (i.e: the \"slug\"). + @return ApiGetConditionSetAncestorsRequest +*/ +func (a *ConditionSetsApiService) GetConditionSetAncestors(ctx context.Context, projId string, envId string, conditionSetId string) ApiGetConditionSetAncestorsRequest { + return ApiGetConditionSetAncestorsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + conditionSetId: conditionSetId, + } +} + +// Execute executes the request +// +// @return []ConditionSetRead +func (a *ConditionSetsApiService) GetConditionSetAncestorsExecute(r ApiGetConditionSetAncestorsRequest) ([]models.ConditionSetRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ConditionSetRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.GetConditionSetAncestors") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets/{condition_set_id}/ancestors" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"condition_set_id"+"}", url.PathEscape(parameterValueToString(r.conditionSetId, "conditionSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetConditionSetDescendantsRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiGetConditionSetDescendantsRequest) Page(page int32) ApiGetConditionSetDescendantsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiGetConditionSetDescendantsRequest) PerPage(perPage int32) ApiGetConditionSetDescendantsRequest { + r.perPage = &perPage + return r +} + +func (r ApiGetConditionSetDescendantsRequest) Execute() ([]models.ConditionSetRead, *http.Response, error) { + return r.ApiService.GetConditionSetDescendantsExecute(r) +} + +/* +GetConditionSetDescendants Get Condition Set Descendants + +Gets all descendants (children, children of children, and so on) + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param conditionSetId Either the unique id of the condition set, or the URL-friendly key of the condition set (i.e: the \"slug\"). + @return ApiGetConditionSetDescendantsRequest +*/ +func (a *ConditionSetsApiService) GetConditionSetDescendants(ctx context.Context, projId string, envId string, conditionSetId string) ApiGetConditionSetDescendantsRequest { + return ApiGetConditionSetDescendantsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + conditionSetId: conditionSetId, + } +} + +// Execute executes the request +// +// @return []ConditionSetRead +func (a *ConditionSetsApiService) GetConditionSetDescendantsExecute(r ApiGetConditionSetDescendantsRequest) ([]models.ConditionSetRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ConditionSetRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.GetConditionSetDescendants") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets/{condition_set_id}/descendants" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"condition_set_id"+"}", url.PathEscape(parameterValueToString(r.conditionSetId, "conditionSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetConditionSetPossibleParentsRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiGetConditionSetPossibleParentsRequest) Page(page int32) ApiGetConditionSetPossibleParentsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiGetConditionSetPossibleParentsRequest) PerPage(perPage int32) ApiGetConditionSetPossibleParentsRequest { + r.perPage = &perPage + return r +} + +func (r ApiGetConditionSetPossibleParentsRequest) Execute() ([]models.ConditionSetRead, *http.Response, error) { + return r.ApiService.GetConditionSetPossibleParentsExecute(r) +} + +/* +GetConditionSetPossibleParents Get Condition Set Possible Parents + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param conditionSetId Either the unique id of the condition set, or the URL-friendly key of the condition set (i.e: the \"slug\"). + @return ApiGetConditionSetPossibleParentsRequest +*/ +func (a *ConditionSetsApiService) GetConditionSetPossibleParents(ctx context.Context, projId string, envId string, conditionSetId string) ApiGetConditionSetPossibleParentsRequest { + return ApiGetConditionSetPossibleParentsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + conditionSetId: conditionSetId, + } +} + +// Execute executes the request +// +// @return []ConditionSetRead +func (a *ConditionSetsApiService) GetConditionSetPossibleParentsExecute(r ApiGetConditionSetPossibleParentsRequest) ([]models.ConditionSetRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ConditionSetRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.GetConditionSetPossibleParents") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets/{condition_set_id}/possible_parents" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"condition_set_id"+"}", url.PathEscape(parameterValueToString(r.conditionSetId, "conditionSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListConditionSetsRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + type_ *models.ConditionSetType + includeTotalCount *bool + page *int32 + perPage *int32 +} + +// if provided, will return only the condition sets of the specified type. e.g: only user sets. +func (r ApiListConditionSetsRequest) Type_(type_ models.ConditionSetType) ApiListConditionSetsRequest { + r.type_ = &type_ + return r +} + +// Include total count in response +func (r ApiListConditionSetsRequest) IncludeTotalCount(includeTotalCount bool) ApiListConditionSetsRequest { + r.includeTotalCount = &includeTotalCount + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListConditionSetsRequest) Page(page int32) ApiListConditionSetsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListConditionSetsRequest) PerPage(perPage int32) ApiListConditionSetsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListConditionSetsRequest) Execute() (*models.ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet, *http.Response, error) { + return r.ApiService.ListConditionSetsExecute(r) +} + +/* +ListConditionSets List Condition Sets + +Lists all condition sets matching a filter. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListConditionSetsRequest +*/ +func (a *ConditionSetsApiService) ListConditionSets(ctx context.Context, projId string, envId string) ApiListConditionSetsRequest { + return ApiListConditionSetsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet +// +// Deprecated +func (a *ConditionSetsApiService) ListConditionSetsExecute(r ApiListConditionSetsRequest) (*models.ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResponseListConditionSetsV2SchemaProjIdEnvIdConditionSetsGet + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.ListConditionSets") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.type_ != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "type", r.type_, "") + } + if r.includeTotalCount != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "include_total_count", r.includeTotalCount, "") + } + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateConditionSetRequest struct { + ctx context.Context + ApiService *ConditionSetsApiService + projId string + envId string + conditionSetId string + conditionSetUpdate *models.ConditionSetUpdate +} + +func (r ApiUpdateConditionSetRequest) ConditionSetUpdate(conditionSetUpdate models.ConditionSetUpdate) ApiUpdateConditionSetRequest { + r.conditionSetUpdate = &conditionSetUpdate + return r +} + +func (r ApiUpdateConditionSetRequest) Execute() (*models.ConditionSetRead, *http.Response, error) { + return r.ApiService.UpdateConditionSetExecute(r) +} + +/* +UpdateConditionSet Update Condition Set + +Partially updates a condition set. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param conditionSetId Either the unique id of the condition set, or the URL-friendly key of the condition set (i.e: the \"slug\"). + @return ApiUpdateConditionSetRequest +*/ +func (a *ConditionSetsApiService) UpdateConditionSet(ctx context.Context, projId string, envId string, conditionSetId string) ApiUpdateConditionSetRequest { + return ApiUpdateConditionSetRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + conditionSetId: conditionSetId, + } +} + +// Execute executes the request +// +// @return ConditionSetRead +func (a *ConditionSetsApiService) UpdateConditionSetExecute(r ApiUpdateConditionSetRequest) (*models.ConditionSetRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ConditionSetRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ConditionSetsApiService.UpdateConditionSet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/condition_sets/{condition_set_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"condition_set_id"+"}", url.PathEscape(parameterValueToString(r.conditionSetId, "conditionSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.conditionSetUpdate == nil { + return localVarReturnValue, nil, reportError("conditionSetUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.conditionSetUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs.go new file mode 100644 index 00000000..6972ff19 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs.go @@ -0,0 +1,231 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "reflect" + "strings" +) + +// DecisionLogsApiService DecisionLogsApi service +type DecisionLogsApiService service + +type ApiListPdpDecisionLogsRequest struct { + ctx context.Context + ApiService *DecisionLogsApiService + projId string + envId string + pdpId string + users *[]string + approved *bool + resources *[]string + timestampFrom *int32 + timestampTo *int32 + page *int32 + perPage *int32 +} + +// List of user IDs to filter by +func (r ApiListPdpDecisionLogsRequest) Users(users []string) ApiListPdpDecisionLogsRequest { + r.users = &users + return r +} + +// Filter by approved decisions +func (r ApiListPdpDecisionLogsRequest) Approved(approved bool) ApiListPdpDecisionLogsRequest { + r.approved = &approved + return r +} + +// Filter by resources +func (r ApiListPdpDecisionLogsRequest) Resources(resources []string) ApiListPdpDecisionLogsRequest { + r.resources = &resources + return r +} + +// Filter by timestamp from +func (r ApiListPdpDecisionLogsRequest) TimestampFrom(timestampFrom int32) ApiListPdpDecisionLogsRequest { + r.timestampFrom = ×tampFrom + return r +} + +// Filter by timestamp to +func (r ApiListPdpDecisionLogsRequest) TimestampTo(timestampTo int32) ApiListPdpDecisionLogsRequest { + r.timestampTo = ×tampTo + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListPdpDecisionLogsRequest) Page(page int32) ApiListPdpDecisionLogsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListPdpDecisionLogsRequest) PerPage(perPage int32) ApiListPdpDecisionLogsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListPdpDecisionLogsRequest) Execute() (*models.PaginatedResultOPADecisionLog, *http.Response, error) { + return r.ApiService.ListPdpDecisionLogsExecute(r) +} + +/* +ListPdpDecisionLogs List PDP Decisions + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param pdpId The unique id of the pdp + @return ApiListPdpDecisionLogsRequest +*/ +func (a *DecisionLogsApiService) ListPdpDecisionLogs(ctx context.Context, projId string, envId string, pdpId string) ApiListPdpDecisionLogsRequest { + return ApiListPdpDecisionLogsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + pdpId: pdpId, + } +} + +// Execute executes the request +// +// @return PaginatedResultOPADecisionLog +func (a *DecisionLogsApiService) ListPdpDecisionLogsExecute(r ApiListPdpDecisionLogsRequest) (*models.PaginatedResultOPADecisionLog, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultOPADecisionLog + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DecisionLogsApiService.ListPdpDecisionLogs") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/pdps/{proj_id}/{env_id}/decision-logs/{pdp_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"pdp_id"+"}", url.PathEscape(parameterToString(r.pdpId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.users != nil { + t := *r.users + if reflect.TypeOf(t).Kind() == reflect.Slice { + s := reflect.ValueOf(t) + for i := 0; i < s.Len(); i++ { + localVarQueryParams.Add("users", parameterToString(s.Index(i), "multi")) + } + } else { + localVarQueryParams.Add("users", parameterToString(t, "multi")) + } + } + if r.approved != nil { + localVarQueryParams.Add("approved", parameterToString(*r.approved, "")) + } + if r.resources != nil { + t := *r.resources + if reflect.TypeOf(t).Kind() == reflect.Slice { + s := reflect.ValueOf(t) + for i := 0; i < s.Len(); i++ { + localVarQueryParams.Add("resources", parameterToString(s.Index(i), "multi")) + } + } else { + localVarQueryParams.Add("resources", parameterToString(t, "multi")) + } + } + if r.timestampFrom != nil { + localVarQueryParams.Add("timestamp_from", parameterToString(*r.timestampFrom, "")) + } + if r.timestampTo != nil { + localVarQueryParams.Add("timestamp_to", parameterToString(*r.timestampTo, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs_ingress.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs_ingress.go new file mode 100644 index 00000000..b4e0fb9f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_decision_logs_ingress.go @@ -0,0 +1,132 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" +) + +// DecisionLogsIngressApiService DecisionLogsIngressApi service +type DecisionLogsIngressApiService service + +type ApiInsertOpaDecisionLogsRequest struct { + ctx context.Context + ApiService *DecisionLogsIngressApiService + requestBody *[]map[string]interface{} +} + +func (r ApiInsertOpaDecisionLogsRequest) RequestBody(requestBody []map[string]interface{}) ApiInsertOpaDecisionLogsRequest { + r.requestBody = &requestBody + return r +} + +func (r ApiInsertOpaDecisionLogsRequest) Execute() (*http.Response, error) { + return r.ApiService.InsertOpaDecisionLogsExecute(r) +} + +/* +InsertOpaDecisionLogs OPA Decision Logs Ingress + +This ingress endpoint captures OPA decision logs. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiInsertOpaDecisionLogsRequest +*/ +func (a *DecisionLogsIngressApiService) InsertOpaDecisionLogs(ctx context.Context) ApiInsertOpaDecisionLogsRequest { + return ApiInsertOpaDecisionLogsRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +func (a *DecisionLogsIngressApiService) InsertOpaDecisionLogsExecute(r ApiInsertOpaDecisionLogsRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DecisionLogsIngressApiService.InsertOpaDecisionLogs") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/decision-logs/ingress" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.requestBody == nil { + return nil, reportError("requestBody is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.requestBody + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_default.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_default.go new file mode 100644 index 00000000..19033d3f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_default.go @@ -0,0 +1,533 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" +) + +// DefaultApiService DefaultApi service +type DefaultApiService service + +type ApiDummyRequest struct { + ctx context.Context + ApiService *DefaultApiService +} + +func (r ApiDummyRequest) Execute() (interface{}, *http.Response, error) { + return r.ApiService.DummyExecute(r) +} + +/* +Dummy Dummy + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiDummyRequest +*/ +func (a *DefaultApiService) Dummy(ctx context.Context) ApiDummyRequest { + return ApiDummyRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return interface{} +func (a *DefaultApiService) DummyExecute(r ApiDummyRequest) (interface{}, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue interface{} + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.Dummy") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/stress/dummy" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDummyDbRequest struct { + ctx context.Context + ApiService *DefaultApiService +} + +func (r ApiDummyDbRequest) Execute() (interface{}, *http.Response, error) { + return r.ApiService.DummyDbExecute(r) +} + +/* +DummyDb Dummy Db + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiDummyDbRequest +*/ +func (a *DefaultApiService) DummyDb(ctx context.Context) ApiDummyDbRequest { + return ApiDummyDbRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return interface{} +func (a *DefaultApiService) DummyDbExecute(r ApiDummyDbRequest) (interface{}, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue interface{} + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.DummyDb") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/stress/db/dummy" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetOrganizationV2StressDbOrganizationGetRequest struct { + ctx context.Context + ApiService *DefaultApiService +} + +func (r ApiGetOrganizationV2StressDbOrganizationGetRequest) Execute() (*models.OrganizationRead, *http.Response, error) { + return r.ApiService.GetOrganizationV2StressDbOrganizationGetExecute(r) +} + +/* +GetOrganizationV2StressDbOrganizationGet Get Organization + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetOrganizationV2StressDbOrganizationGetRequest +*/ +func (a *DefaultApiService) GetOrganizationV2StressDbOrganizationGet(ctx context.Context) ApiGetOrganizationV2StressDbOrganizationGetRequest { + return ApiGetOrganizationV2StressDbOrganizationGetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return OrganizationRead +func (a *DefaultApiService) GetOrganizationV2StressDbOrganizationGetExecute(r ApiGetOrganizationV2StressDbOrganizationGetRequest) (*models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.GetOrganizationV2StressDbOrganizationGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/stress/db/organization" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetOrganizationWithAuthnRequest struct { + ctx context.Context + ApiService *DefaultApiService +} + +func (r ApiGetOrganizationWithAuthnRequest) Execute() (*models.OrganizationRead, *http.Response, error) { + return r.ApiService.GetOrganizationWithAuthnExecute(r) +} + +/* +GetOrganizationWithAuthn Get Organization With Authn + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetOrganizationWithAuthnRequest +*/ +func (a *DefaultApiService) GetOrganizationWithAuthn(ctx context.Context) ApiGetOrganizationWithAuthnRequest { + return ApiGetOrganizationWithAuthnRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return OrganizationRead +func (a *DefaultApiService) GetOrganizationWithAuthnExecute(r ApiGetOrganizationWithAuthnRequest) (*models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.GetOrganizationWithAuthn") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/stress/db/organization_auth" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetOrganizationWithAuthzRequest struct { + ctx context.Context + ApiService *DefaultApiService +} + +func (r ApiGetOrganizationWithAuthzRequest) Execute() (*models.OrganizationRead, *http.Response, error) { + return r.ApiService.GetOrganizationWithAuthzExecute(r) +} + +/* +GetOrganizationWithAuthz Get Organization With Authz + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetOrganizationWithAuthzRequest +*/ +func (a *DefaultApiService) GetOrganizationWithAuthz(ctx context.Context) ApiGetOrganizationWithAuthzRequest { + return ApiGetOrganizationWithAuthzRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return OrganizationRead +func (a *DefaultApiService) GetOrganizationWithAuthzExecute(r ApiGetOrganizationWithAuthzRequest) (*models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.GetOrganizationWithAuthz") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/stress/db/organization_authz" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_configs.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_configs.go new file mode 100644 index 00000000..8033ee6e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_configs.go @@ -0,0 +1,899 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ElementsConfigsApiService ElementsConfigsApi service +type ElementsConfigsApiService service + +type ApiCreateElementsConfigRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + projId string + envId string + elementsConfigCreate *models.ElementsConfigCreate +} + +func (r ApiCreateElementsConfigRequest) ElementsConfigCreate(elementsConfigCreate models.ElementsConfigCreate) ApiCreateElementsConfigRequest { + r.elementsConfigCreate = &elementsConfigCreate + return r +} + +func (r ApiCreateElementsConfigRequest) Execute() (*models.ElementsConfigRead, *http.Response, error) { + return r.ApiService.CreateElementsConfigExecute(r) +} + +/* +CreateElementsConfig Create Elements Config + +Creates a new elements_config under the active organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateElementsConfigRequest +*/ +func (a *ElementsConfigsApiService) CreateElementsConfig(ctx context.Context, projId string, envId string) ApiCreateElementsConfigRequest { + return ApiCreateElementsConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ElementsConfigRead +func (a *ElementsConfigsApiService) CreateElementsConfigExecute(r ApiCreateElementsConfigRequest) (*models.ElementsConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ElementsConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.CreateElementsConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.elementsConfigCreate == nil { + return localVarReturnValue, nil, reportError("elementsConfigCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.elementsConfigCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteElementsConfigRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + elementsConfigId string + projId string + envId string +} + +func (r ApiDeleteElementsConfigRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteElementsConfigExecute(r) +} + +/* +DeleteElementsConfig Delete Elements Config + +Deletes the elements_config and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiDeleteElementsConfigRequest +*/ +func (a *ElementsConfigsApiService) DeleteElementsConfig(ctx context.Context, elementsConfigId string, projId string, envId string) ApiDeleteElementsConfigRequest { + return ApiDeleteElementsConfigRequest{ + ApiService: a, + ctx: ctx, + elementsConfigId: elementsConfigId, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +func (a *ElementsConfigsApiService) DeleteElementsConfigExecute(r ApiDeleteElementsConfigRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.DeleteElementsConfig") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/{elements_config_id}" + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetElementsConfigRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + projId string + envId string + elementsConfigId string +} + +func (r ApiGetElementsConfigRequest) Execute() (*models.ElementsConfigRead, *http.Response, error) { + return r.ApiService.GetElementsConfigExecute(r) +} + +/* +GetElementsConfig Get Elements Config + +Gets a single elements_config matching the given elements_config_id, if such elements_config exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @return ApiGetElementsConfigRequest +*/ +func (a *ElementsConfigsApiService) GetElementsConfig(ctx context.Context, projId string, envId string, elementsConfigId string) ApiGetElementsConfigRequest { + return ApiGetElementsConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + } +} + +// Execute executes the request +// +// @return ElementsConfigRead +func (a *ElementsConfigsApiService) GetElementsConfigExecute(r ApiGetElementsConfigRequest) (*models.ElementsConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ElementsConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.GetElementsConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetEnvConfigRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + projId string + envId string +} + +func (r ApiGetEnvConfigRequest) Execute() (*models.ElementsEnvRead, *http.Response, error) { + return r.ApiService.GetEnvConfigExecute(r) +} + +/* +GetEnvConfig Get Env Config + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiGetEnvConfigRequest +*/ +func (a *ElementsConfigsApiService) GetEnvConfig(ctx context.Context, projId string, envId string) ApiGetEnvConfigRequest { + return ApiGetEnvConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ElementsEnvRead +func (a *ElementsConfigsApiService) GetEnvConfigExecute(r ApiGetEnvConfigRequest) (*models.ElementsEnvRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ElementsEnvRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.GetEnvConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListElementsConfigsRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + projId string + envId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListElementsConfigsRequest) Page(page int32) ApiListElementsConfigsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListElementsConfigsRequest) PerPage(perPage int32) ApiListElementsConfigsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListElementsConfigsRequest) Execute() (*models.PaginatedResultElementsConfigRead, *http.Response, error) { + return r.ApiService.ListElementsConfigsExecute(r) +} + +/* +ListElementsConfigs List Elements Configs + +Lists all the elements_configs under the active organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListElementsConfigsRequest +*/ +func (a *ElementsConfigsApiService) ListElementsConfigs(ctx context.Context, projId string, envId string) ApiListElementsConfigsRequest { + return ApiListElementsConfigsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return PaginatedResultElementsConfigRead +func (a *ElementsConfigsApiService) ListElementsConfigsExecute(r ApiListElementsConfigsRequest) (*models.PaginatedResultElementsConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultElementsConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.ListElementsConfigs") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateElementsConfigRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + elementsConfigId string + projId string + envId string + elementsConfigUpdate *models.ElementsConfigUpdate +} + +func (r ApiUpdateElementsConfigRequest) ElementsConfigUpdate(elementsConfigUpdate models.ElementsConfigUpdate) ApiUpdateElementsConfigRequest { + r.elementsConfigUpdate = &elementsConfigUpdate + return r +} + +func (r ApiUpdateElementsConfigRequest) Execute() (*models.ElementsConfigRead, *http.Response, error) { + return r.ApiService.UpdateElementsConfigExecute(r) +} + +/* +UpdateElementsConfig Update Elements Config + +Updates the elements_config. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiUpdateElementsConfigRequest +*/ +func (a *ElementsConfigsApiService) UpdateElementsConfig(ctx context.Context, elementsConfigId string, projId string, envId string) ApiUpdateElementsConfigRequest { + return ApiUpdateElementsConfigRequest{ + ApiService: a, + ctx: ctx, + elementsConfigId: elementsConfigId, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ElementsConfigRead +func (a *ElementsConfigsApiService) UpdateElementsConfigExecute(r ApiUpdateElementsConfigRequest) (*models.ElementsConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ElementsConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.UpdateElementsConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}" + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.elementsConfigUpdate == nil { + return localVarReturnValue, nil, reportError("elementsConfigUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.elementsConfigUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateElementsEnvRequest struct { + ctx context.Context + ApiService *ElementsConfigsApiService + projId string + envId string + elementsEnvUpdate *models.ElementsEnvUpdate +} + +func (r ApiUpdateElementsEnvRequest) ElementsEnvUpdate(elementsEnvUpdate models.ElementsEnvUpdate) ApiUpdateElementsEnvRequest { + r.elementsEnvUpdate = &elementsEnvUpdate + return r +} + +func (r ApiUpdateElementsEnvRequest) Execute() (*models.ElementsEnvRead, *http.Response, error) { + return r.ApiService.UpdateElementsEnvExecute(r) +} + +/* +UpdateElementsEnv Update Elements Env + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiUpdateElementsEnvRequest +*/ +func (a *ElementsConfigsApiService) UpdateElementsEnv(ctx context.Context, projId string, envId string) ApiUpdateElementsEnvRequest { + return ApiUpdateElementsEnvRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ElementsEnvRead +func (a *ElementsConfigsApiService) UpdateElementsEnvExecute(r ApiUpdateElementsEnvRequest) (*models.ElementsEnvRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ElementsEnvRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsConfigsApiService.UpdateElementsEnv") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.elementsEnvUpdate == nil { + return localVarReturnValue, nil, reportError("elementsEnvUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.elementsEnvUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_data.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_data.go new file mode 100644 index 00000000..e904893e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_elements_data.go @@ -0,0 +1,955 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ElementsDataApiService ElementsDataApi service +type ElementsDataApiService service + +type ApiElementsAssignRoleToUserRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + projId string + envId string + elementsConfigId string + userId string + elementsUserRoleCreate *models.ElementsUserRoleCreate +} + +func (r ApiElementsAssignRoleToUserRequest) ElementsUserRoleCreate(elementsUserRoleCreate models.ElementsUserRoleCreate) ApiElementsAssignRoleToUserRequest { + r.elementsUserRoleCreate = &elementsUserRoleCreate + return r +} + +func (r ApiElementsAssignRoleToUserRequest) Execute() (*models.RoleAssignmentRead, *http.Response, error) { + return r.ApiService.ElementsAssignRoleToUserExecute(r) +} + +/* +ElementsAssignRoleToUser Assign role to user + +Assigns a role to the user within the tenant. + +The tenant defines the scope of the assignment. In other words, the role is effective only within the tenant. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiElementsAssignRoleToUserRequest +*/ +func (a *ElementsDataApiService) ElementsAssignRoleToUser(ctx context.Context, projId string, envId string, elementsConfigId string, userId string) ApiElementsAssignRoleToUserRequest { + return ApiElementsAssignRoleToUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + userId: userId, + } +} + +// Execute executes the request +// +// @return RoleAssignmentRead +func (a *ElementsDataApiService) ElementsAssignRoleToUserExecute(r ApiElementsAssignRoleToUserRequest) (*models.RoleAssignmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleAssignmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.ElementsAssignRoleToUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/users/{user_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.elementsUserRoleCreate == nil { + return localVarReturnValue, nil, reportError("elementsUserRoleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.elementsUserRoleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiElementsCreateUserRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + projId string + envId string + elementsConfigId string + elementsUserCreate *models.ElementsUserCreate +} + +func (r ApiElementsCreateUserRequest) ElementsUserCreate(elementsUserCreate models.ElementsUserCreate) ApiElementsCreateUserRequest { + r.elementsUserCreate = &elementsUserCreate + return r +} + +func (r ApiElementsCreateUserRequest) Execute() (*models.UserRead, *http.Response, error) { + return r.ApiService.ElementsCreateUserExecute(r) +} + +/* +ElementsCreateUser Create user + +Creates a new user inside the Permit.io system, from that point forward +you may run permission checks on that user. + +If the user is already created: will return 200 instead of 201, +and will return the existing user object in the response body. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @return ApiElementsCreateUserRequest +*/ +func (a *ElementsDataApiService) ElementsCreateUser(ctx context.Context, projId string, envId string, elementsConfigId string) ApiElementsCreateUserRequest { + return ApiElementsCreateUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + } +} + +// Execute executes the request +// +// @return UserRead +func (a *ElementsDataApiService) ElementsCreateUserExecute(r ApiElementsCreateUserRequest) (*models.UserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.ElementsCreateUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/users" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.elementsUserCreate == nil { + return localVarReturnValue, nil, reportError("elementsUserCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.elementsUserCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiElementsDeleteUserRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + projId string + envId string + elementsConfigId string + userId string +} + +func (r ApiElementsDeleteUserRequest) Execute() (*http.Response, error) { + return r.ApiService.ElementsDeleteUserExecute(r) +} + +/* +ElementsDeleteUser Delete user + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiElementsDeleteUserRequest +*/ +func (a *ElementsDataApiService) ElementsDeleteUser(ctx context.Context, projId string, envId string, elementsConfigId string, userId string) ApiElementsDeleteUserRequest { + return ApiElementsDeleteUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + userId: userId, + } +} + +// Execute executes the request +func (a *ElementsDataApiService) ElementsDeleteUserExecute(r ApiElementsDeleteUserRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.ElementsDeleteUser") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiElementsListRolesRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + projId string + envId string + elementsConfigId string + search *string + page *int32 + perPage *int32 +} + +// Text search for the email field +func (r ApiElementsListRolesRequest) Search(search string) ApiElementsListRolesRequest { + r.search = &search + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiElementsListRolesRequest) Page(page int32) ApiElementsListRolesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiElementsListRolesRequest) PerPage(perPage int32) ApiElementsListRolesRequest { + r.perPage = &perPage + return r +} + +func (r ApiElementsListRolesRequest) Execute() ([]models.ElementsRoleRead, *http.Response, error) { + return r.ApiService.ElementsListRolesExecute(r) +} + +/* +ElementsListRoles List roles + +Lists all the users defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @return ApiElementsListRolesRequest +*/ +func (a *ElementsDataApiService) ElementsListRoles(ctx context.Context, projId string, envId string, elementsConfigId string) ApiElementsListRolesRequest { + return ApiElementsListRolesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + } +} + +// Execute executes the request +// +// @return []ElementsRoleRead +func (a *ElementsDataApiService) ElementsListRolesExecute(r ApiElementsListRolesRequest) ([]models.ElementsRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ElementsRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.ElementsListRoles") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.search != nil { + localVarQueryParams.Add("search", parameterToString(*r.search, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiElementsListUsersRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + projId string + envId string + elementsConfigId string + search *string + page *int32 + perPage *int32 +} + +// Text search for the email field +func (r ApiElementsListUsersRequest) Search(search string) ApiElementsListUsersRequest { + r.search = &search + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiElementsListUsersRequest) Page(page int32) ApiElementsListUsersRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiElementsListUsersRequest) PerPage(perPage int32) ApiElementsListUsersRequest { + r.perPage = &perPage + return r +} + +func (r ApiElementsListUsersRequest) Execute() (*models.PaginatedResultUserRead, *http.Response, error) { + return r.ApiService.ElementsListUsersExecute(r) +} + +/* +ElementsListUsers List users + +Lists all the users defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @return ApiElementsListUsersRequest +*/ +func (a *ElementsDataApiService) ElementsListUsers(ctx context.Context, projId string, envId string, elementsConfigId string) ApiElementsListUsersRequest { + return ApiElementsListUsersRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + } +} + +// Execute executes the request +// +// @return PaginatedResultUserRead +func (a *ElementsDataApiService) ElementsListUsersExecute(r ApiElementsListUsersRequest) (*models.PaginatedResultUserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultUserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.ElementsListUsers") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/users" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.search != nil { + localVarQueryParams.Add("search", parameterToString(*r.search, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiElementsUnassignRoleFromUserRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + projId string + envId string + elementsConfigId string + userId string + elementsUserRoleRemove *models.ElementsUserRoleRemove +} + +func (r ApiElementsUnassignRoleFromUserRequest) ElementsUserRoleRemove(elementsUserRoleRemove models.ElementsUserRoleRemove) ApiElementsUnassignRoleFromUserRequest { + r.elementsUserRoleRemove = &elementsUserRoleRemove + return r +} + +func (r ApiElementsUnassignRoleFromUserRequest) Execute() (*http.Response, error) { + return r.ApiService.ElementsUnassignRoleFromUserExecute(r) +} + +/* +ElementsUnassignRoleFromUser Unassign role from user + +Unassigns the role from the user within the tenant. + +The tenant defines the scope of the assignment. In other words, the role is effective only within the tenant. + +If the role is not actually assigned, will return 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiElementsUnassignRoleFromUserRequest +*/ +func (a *ElementsDataApiService) ElementsUnassignRoleFromUser(ctx context.Context, projId string, envId string, elementsConfigId string, userId string) ApiElementsUnassignRoleFromUserRequest { + return ApiElementsUnassignRoleFromUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + elementsConfigId: elementsConfigId, + userId: userId, + } +} + +// Execute executes the request +func (a *ElementsDataApiService) ElementsUnassignRoleFromUserExecute(r ApiElementsUnassignRoleFromUserRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.ElementsUnassignRoleFromUser") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/users/{user_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.elementsUserRoleRemove == nil { + return nil, reportError("elementsUserRoleRemove is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.elementsUserRoleRemove + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiSetConfigActiveRequest struct { + ctx context.Context + ApiService *ElementsDataApiService + elementsConfigId string + projId string + envId string +} + +func (r ApiSetConfigActiveRequest) Execute() (*http.Response, error) { + return r.ApiService.SetConfigActiveExecute(r) +} + +/* +SetConfigActive Set Config Active + +Updates the embed_config. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param elementsConfigId Either the unique id of the elements_config, or the URL-friendly key of the elements_config (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiSetConfigActiveRequest +*/ +func (a *ElementsDataApiService) SetConfigActive(ctx context.Context, elementsConfigId string, projId string, envId string) ApiSetConfigActiveRequest { + return ApiSetConfigActiveRequest{ + ApiService: a, + ctx: ctx, + elementsConfigId: elementsConfigId, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +func (a *ElementsDataApiService) SetConfigActiveExecute(r ApiSetConfigActiveRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ElementsDataApiService.SetConfigActive") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/elements/{proj_id}/{env_id}/config/{elements_config_id}/data/active" + localVarPath = strings.Replace(localVarPath, "{"+"elements_config_id"+"}", url.PathEscape(parameterToString(r.elementsConfigId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_environments.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_environments.go new file mode 100644 index 00000000..8b89ab2e --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_environments.go @@ -0,0 +1,895 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// EnvironmentsApiService EnvironmentsApi service +type EnvironmentsApiService service + +type ApiCopyEnvironmentRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + envId string + environmentCopy *models.EnvironmentCopy +} + +func (r ApiCopyEnvironmentRequest) EnvironmentCopy(environmentCopy models.EnvironmentCopy) ApiCopyEnvironmentRequest { + r.environmentCopy = &environmentCopy + return r +} + +func (r ApiCopyEnvironmentRequest) Execute() (*models.EnvironmentRead, *http.Response, error) { + return r.ApiService.CopyEnvironmentExecute(r) +} + +/* +CopyEnvironment Copy Environment + +# Copy environment + +This endpoint either duplicates an existing environment to a new environment +in the same project, or copies from an existing environment to another +existing environment. + +The `scope` object controls which objects will be copied to the target +environment. + +To clone to a new environment, the user must have write permissions +to the containing project. To clone into an existing environment, +the user must have write permissions to the target environment. + +Copying environments across projects or organizations is not +allowed. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCopyEnvironmentRequest +*/ +func (a *EnvironmentsApiService) CopyEnvironment(ctx context.Context, projId string, envId string) ApiCopyEnvironmentRequest { + return ApiCopyEnvironmentRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return EnvironmentRead +func (a *EnvironmentsApiService) CopyEnvironmentExecute(r ApiCopyEnvironmentRequest) (*models.EnvironmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.EnvironmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.CopyEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs/{env_id}/copy" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.environmentCopy == nil { + return localVarReturnValue, nil, reportError("environmentCopy is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.environmentCopy + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiCreateEnvironmentRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + environmentCreate *models.EnvironmentCreate +} + +func (r ApiCreateEnvironmentRequest) EnvironmentCreate(environmentCreate models.EnvironmentCreate) ApiCreateEnvironmentRequest { + r.environmentCreate = &environmentCreate + return r +} + +func (r ApiCreateEnvironmentRequest) Execute() (*models.EnvironmentRead, *http.Response, error) { + return r.ApiService.CreateEnvironmentExecute(r) +} + +/* +CreateEnvironment Create Environment + +Creates a new environment under a given project. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiCreateEnvironmentRequest +*/ +func (a *EnvironmentsApiService) CreateEnvironment(ctx context.Context, projId string) ApiCreateEnvironmentRequest { + return ApiCreateEnvironmentRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return EnvironmentRead +func (a *EnvironmentsApiService) CreateEnvironmentExecute(r ApiCreateEnvironmentRequest) (*models.EnvironmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.EnvironmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.CreateEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.environmentCreate == nil { + return localVarReturnValue, nil, reportError("environmentCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.environmentCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteEnvironmentRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + envId string +} + +func (r ApiDeleteEnvironmentRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteEnvironmentExecute(r) +} + +/* +DeleteEnvironment Delete Environment + +Deletes an environment and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiDeleteEnvironmentRequest +*/ +func (a *EnvironmentsApiService) DeleteEnvironment(ctx context.Context, projId string, envId string) ApiDeleteEnvironmentRequest { + return ApiDeleteEnvironmentRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +func (a *EnvironmentsApiService) DeleteEnvironmentExecute(r ApiDeleteEnvironmentRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.DeleteEnvironment") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetEnvironmentRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + envId string +} + +func (r ApiGetEnvironmentRequest) Execute() (*models.EnvironmentRead, *http.Response, error) { + return r.ApiService.GetEnvironmentExecute(r) +} + +/* +GetEnvironment Get Environment + +Gets a single environment matching the given env_id, if such environment exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiGetEnvironmentRequest +*/ +func (a *EnvironmentsApiService) GetEnvironment(ctx context.Context, projId string, envId string) ApiGetEnvironmentRequest { + return ApiGetEnvironmentRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return EnvironmentRead +func (a *EnvironmentsApiService) GetEnvironmentExecute(r ApiGetEnvironmentRequest) (*models.EnvironmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.EnvironmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.GetEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListEnvironmentsRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListEnvironmentsRequest) Page(page int32) ApiListEnvironmentsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListEnvironmentsRequest) PerPage(perPage int32) ApiListEnvironmentsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListEnvironmentsRequest) Execute() ([]models.EnvironmentRead, *http.Response, error) { + return r.ApiService.ListEnvironmentsExecute(r) +} + +/* +ListEnvironments List Environments + +Lists all the environments under a given project. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiListEnvironmentsRequest +*/ +func (a *EnvironmentsApiService) ListEnvironments(ctx context.Context, projId string) ApiListEnvironmentsRequest { + return ApiListEnvironmentsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return []EnvironmentRead +func (a *EnvironmentsApiService) ListEnvironmentsExecute(r ApiListEnvironmentsRequest) ([]models.EnvironmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.EnvironmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.ListEnvironments") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiStatsEnvironmentsRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + envId string +} + +func (r ApiStatsEnvironmentsRequest) Execute() (*models.EnvironmentStats, *http.Response, error) { + return r.ApiService.StatsEnvironmentsExecute(r) +} + +/* +StatsEnvironments Stats Environments + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiStatsEnvironmentsRequest +*/ +func (a *EnvironmentsApiService) StatsEnvironments(ctx context.Context, projId string, envId string) ApiStatsEnvironmentsRequest { + return ApiStatsEnvironmentsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return EnvironmentStats +func (a *EnvironmentsApiService) StatsEnvironmentsExecute(r ApiStatsEnvironmentsRequest) (*models.EnvironmentStats, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.EnvironmentStats + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.StatsEnvironments") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs/{env_id}/stats" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateEnvironmentRequest struct { + ctx context.Context + ApiService *EnvironmentsApiService + projId string + envId string + environmentUpdate *models.EnvironmentUpdate +} + +func (r ApiUpdateEnvironmentRequest) EnvironmentUpdate(environmentUpdate models.EnvironmentUpdate) ApiUpdateEnvironmentRequest { + r.environmentUpdate = &environmentUpdate + return r +} + +func (r ApiUpdateEnvironmentRequest) Execute() (*models.EnvironmentRead, *http.Response, error) { + return r.ApiService.UpdateEnvironmentExecute(r) +} + +/* +UpdateEnvironment Update Environment + +Updates the environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiUpdateEnvironmentRequest +*/ +func (a *EnvironmentsApiService) UpdateEnvironment(ctx context.Context, projId string, envId string) ApiUpdateEnvironmentRequest { + return ApiUpdateEnvironmentRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return EnvironmentRead +func (a *EnvironmentsApiService) UpdateEnvironmentExecute(r ApiUpdateEnvironmentRequest) (*models.EnvironmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.EnvironmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentsApiService.UpdateEnvironment") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/envs/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.environmentUpdate == nil { + return localVarReturnValue, nil, reportError("environmentUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.environmentUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_implicit_grants.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_implicit_grants.go new file mode 100644 index 00000000..07cd761d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_implicit_grants.go @@ -0,0 +1,441 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ImplicitGrantsAPIService ImplicitGrantsAPI service +type ImplicitGrantsAPIService service + +type ApiCreateImplicitGrantRequest struct { + ctx context.Context + ApiService *ImplicitGrantsAPIService + projId string + envId string + resourceId string + roleId string + derivedRoleRuleCreate *models.DerivedRoleRuleCreate + permitSession *string +} + +func (r ApiCreateImplicitGrantRequest) DerivedRoleRuleCreate(derivedRoleRuleCreate models.DerivedRoleRuleCreate) ApiCreateImplicitGrantRequest { + r.derivedRoleRuleCreate = &derivedRoleRuleCreate + return r +} + +func (r ApiCreateImplicitGrantRequest) PermitSession(permitSession string) ApiCreateImplicitGrantRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiCreateImplicitGrantRequest) Execute() (*models.DerivedRoleRuleRead, *http.Response, error) { + return r.ApiService.CreateImplicitGrantExecute(r) +} + +/* +CreateImplicitGrant Create Implicit Grant + +Creates an implicit grant on a given role + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiCreateImplicitGrantRequest +*/ +func (a *ImplicitGrantsAPIService) CreateImplicitGrant(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiCreateImplicitGrantRequest { + return ApiCreateImplicitGrantRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return DerivedRoleRuleRead +func (a *ImplicitGrantsAPIService) CreateImplicitGrantExecute(r ApiCreateImplicitGrantRequest) (*models.DerivedRoleRuleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.DerivedRoleRuleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ImplicitGrantsAPIService.CreateImplicitGrant") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/implicit_grants" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.derivedRoleRuleCreate == nil { + return localVarReturnValue, nil, reportError("derivedRoleRuleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.derivedRoleRuleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteImplicitGrantRequest struct { + ctx context.Context + ApiService *ImplicitGrantsAPIService + projId string + envId string + roleId string + resourceId string + derivedRoleRuleDelete *models.DerivedRoleRuleDelete + permitSession *string +} + +func (r ApiDeleteImplicitGrantRequest) DerivedRoleRuleDelete(derivedRoleRuleDelete models.DerivedRoleRuleDelete) ApiDeleteImplicitGrantRequest { + r.derivedRoleRuleDelete = &derivedRoleRuleDelete + return r +} + +func (r ApiDeleteImplicitGrantRequest) PermitSession(permitSession string) ApiDeleteImplicitGrantRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiDeleteImplicitGrantRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteImplicitGrantExecute(r) +} + +/* +DeleteImplicitGrant Delete Implicit Grant + +Deletes an implicit grant on a given role + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiDeleteImplicitGrantRequest +*/ +func (a *ImplicitGrantsAPIService) DeleteImplicitGrant(ctx context.Context, projId string, envId string, roleId string, resourceId string) ApiDeleteImplicitGrantRequest { + return ApiDeleteImplicitGrantRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + resourceId: resourceId, + } +} + +// Execute executes the request +func (a *ImplicitGrantsAPIService) DeleteImplicitGrantExecute(r ApiDeleteImplicitGrantRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ImplicitGrantsAPIService.DeleteImplicitGrant") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/implicit_grants" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.derivedRoleRuleDelete == nil { + return nil, reportError("derivedRoleRuleDelete is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.derivedRoleRuleDelete + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiUpdateImplicitGrantsConditionsRequest struct { + ctx context.Context + ApiService *ImplicitGrantsAPIService + projId string + envId string + resourceId string + roleId string + permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings *models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + permitSession *string +} + +func (r ApiUpdateImplicitGrantsConditionsRequest) PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings(permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings) ApiUpdateImplicitGrantsConditionsRequest { + r.permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings = &permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + return r +} + +func (r ApiUpdateImplicitGrantsConditionsRequest) PermitSession(permitSession string) ApiUpdateImplicitGrantsConditionsRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiUpdateImplicitGrantsConditionsRequest) Execute() (*models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, *http.Response, error) { + return r.ApiService.UpdateImplicitGrantsConditionsExecute(r) +} + +/* +UpdateImplicitGrantsConditions Update Implicit Grants Conditions + +Update the `when` for implicit grants on a given role + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiUpdateImplicitGrantsConditionsRequest +*/ +func (a *ImplicitGrantsAPIService) UpdateImplicitGrantsConditions(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiUpdateImplicitGrantsConditionsRequest { + return ApiUpdateImplicitGrantsConditionsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings +func (a *ImplicitGrantsAPIService) UpdateImplicitGrantsConditionsExecute(r ApiUpdateImplicitGrantsConditionsRequest) (*models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PermitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ImplicitGrantsAPIService.UpdateImplicitGrantsConditions") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/implicit_grants/conditions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings == nil { + return localVarReturnValue, nil, reportError("permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.permitBackendSchemasSchemaDerivedRoleRuleDerivationSettings + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_instructions.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_instructions.go new file mode 100644 index 00000000..210b9df9 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_instructions.go @@ -0,0 +1,142 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// InstructionsApiService InstructionsApi service +type InstructionsApiService service + +type ApiListLanguageInstructionsRequest struct { + ctx context.Context + ApiService *InstructionsApiService + projId string + envId string +} + +func (r ApiListLanguageInstructionsRequest) Execute() ([]models.LanguageInstructions, *http.Response, error) { + return r.ApiService.ListLanguageInstructionsExecute(r) +} + +/* +ListLanguageInstructions List Language Instructions + +Lists pending organization invites + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListLanguageInstructionsRequest +*/ +func (a *InstructionsApiService) ListLanguageInstructions(ctx context.Context, projId string, envId string) ApiListLanguageInstructionsRequest { + return ApiListLanguageInstructionsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []LanguageInstructions +func (a *InstructionsApiService) ListLanguageInstructionsExecute(r ApiListLanguageInstructionsRequest) ([]models.LanguageInstructions, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.LanguageInstructions + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "InstructionsApiService.ListLanguageInstructions") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/{proj_id}/{env_id}/get_instructions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_members.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_members.go new file mode 100644 index 00000000..1fd5a037 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_members.go @@ -0,0 +1,612 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// MembersApiService MembersApi service +type MembersApiService service + +type ApiDeleteOrganizationMemberRequest struct { + ctx context.Context + ApiService *MembersApiService + memberId string +} + +func (r ApiDeleteOrganizationMemberRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteOrganizationMemberExecute(r) +} + +/* +DeleteOrganizationMember Delete Organization Member + +Deletes an account member matching the given id or email address. +The member will be removed from the active account in permit.io. + +If the member is the only member in its account (organization), returns 400 (bad request), +due to nobody remains with access to the account, meaning deletion of the entire account (org). +To completely remove an account, call DELETE `/orgs/{org}`. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param memberId Either the unique id (UUID) of the account member, or the email address of the account member. + @return ApiDeleteOrganizationMemberRequest +*/ +func (a *MembersApiService) DeleteOrganizationMember(ctx context.Context, memberId string) ApiDeleteOrganizationMemberRequest { + return ApiDeleteOrganizationMemberRequest{ + ApiService: a, + ctx: ctx, + memberId: memberId, + } +} + +// Execute executes the request +func (a *MembersApiService) DeleteOrganizationMemberExecute(r ApiDeleteOrganizationMemberRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MembersApiService.DeleteOrganizationMember") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/members/{member_id}" + localVarPath = strings.Replace(localVarPath, "{"+"member_id"+"}", url.PathEscape(parameterToString(r.memberId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetAuthenticatedMemberRequest struct { + ctx context.Context + ApiService *MembersApiService +} + +func (r ApiGetAuthenticatedMemberRequest) Execute() (*models.OrgMemberRead, *http.Response, error) { + return r.ApiService.GetAuthenticatedMemberExecute(r) +} + +/* +GetAuthenticatedMember Get the authenticated account member + +Gets the authenticated account member's details. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetAuthenticatedMemberRequest +*/ +func (a *MembersApiService) GetAuthenticatedMember(ctx context.Context) ApiGetAuthenticatedMemberRequest { + return ApiGetAuthenticatedMemberRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return OrgMemberRead +func (a *MembersApiService) GetAuthenticatedMemberExecute(r ApiGetAuthenticatedMemberRequest) (*models.OrgMemberRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrgMemberRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MembersApiService.GetAuthenticatedMember") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/members/me" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetOrganizationMemberRequest struct { + ctx context.Context + ApiService *MembersApiService + memberId string +} + +func (r ApiGetOrganizationMemberRequest) Execute() (*models.OrgMemberRead, *http.Response, error) { + return r.ApiService.GetOrganizationMemberExecute(r) +} + +/* +GetOrganizationMember Get Organization Member + +Gets a single account member by its id or email address. matching the given member, +if no such member exists under the current active account (organization), returns 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param memberId Either the unique id (UUID) of the account member, or the email address of the account member. + @return ApiGetOrganizationMemberRequest +*/ +func (a *MembersApiService) GetOrganizationMember(ctx context.Context, memberId string) ApiGetOrganizationMemberRequest { + return ApiGetOrganizationMemberRequest{ + ApiService: a, + ctx: ctx, + memberId: memberId, + } +} + +// Execute executes the request +// +// @return OrgMemberRead +func (a *MembersApiService) GetOrganizationMemberExecute(r ApiGetOrganizationMemberRequest) (*models.OrgMemberRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrgMemberRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MembersApiService.GetOrganizationMember") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/members/{member_id}" + localVarPath = strings.Replace(localVarPath, "{"+"member_id"+"}", url.PathEscape(parameterToString(r.memberId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListOrganizationMembersRequest struct { + ctx context.Context + ApiService *MembersApiService + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListOrganizationMembersRequest) Page(page int32) ApiListOrganizationMembersRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListOrganizationMembersRequest) PerPage(perPage int32) ApiListOrganizationMembersRequest { + r.perPage = &perPage + return r +} + +func (r ApiListOrganizationMembersRequest) Execute() ([]models.OrgMemberRead, *http.Response, error) { + return r.ApiService.ListOrganizationMembersExecute(r) +} + +/* +ListOrganizationMembers List Organization Members + +Lists all the account members that have access to the current active account. +The active account/organization is determined by the API Key used or by the authenticated session id. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiListOrganizationMembersRequest +*/ +func (a *MembersApiService) ListOrganizationMembers(ctx context.Context) ApiListOrganizationMembersRequest { + return ApiListOrganizationMembersRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return []OrgMemberRead +func (a *MembersApiService) ListOrganizationMembersExecute(r ApiListOrganizationMembersRequest) ([]models.OrgMemberRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.OrgMemberRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MembersApiService.ListOrganizationMembers") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/members" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateOrganizationMemberRequest struct { + ctx context.Context + ApiService *MembersApiService + memberId string + orgMemberUpdate *models.OrgMemberUpdate +} + +func (r ApiUpdateOrganizationMemberRequest) OrgMemberUpdate(orgMemberUpdate models.OrgMemberUpdate) ApiUpdateOrganizationMemberRequest { + r.orgMemberUpdate = &orgMemberUpdate + return r +} + +func (r ApiUpdateOrganizationMemberRequest) Execute() (*models.OrgMemberRead, *http.Response, error) { + return r.ApiService.UpdateOrganizationMemberExecute(r) +} + +/* +UpdateOrganizationMember Update Organization Member + +Updates an account member's settings. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param memberId Either the unique id (UUID) of the account member, or the email address of the account member. + @return ApiUpdateOrganizationMemberRequest +*/ +func (a *MembersApiService) UpdateOrganizationMember(ctx context.Context, memberId string) ApiUpdateOrganizationMemberRequest { + return ApiUpdateOrganizationMemberRequest{ + ApiService: a, + ctx: ctx, + memberId: memberId, + } +} + +// Execute executes the request +// +// @return OrgMemberRead +func (a *MembersApiService) UpdateOrganizationMemberExecute(r ApiUpdateOrganizationMemberRequest) (*models.OrgMemberRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrgMemberRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "MembersApiService.UpdateOrganizationMember") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/members/{member_id}" + localVarPath = strings.Replace(localVarPath, "{"+"member_id"+"}", url.PathEscape(parameterToString(r.memberId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.orgMemberUpdate == nil { + return localVarReturnValue, nil, reportError("orgMemberUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.orgMemberUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_opal_data.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_opal_data.go new file mode 100644 index 00000000..ebbed089 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_opal_data.go @@ -0,0 +1,531 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// OPALDataApiService OPALDataApi service +type OPALDataApiService service + +type ApiGetAllDataRequest struct { + ctx context.Context + ApiService *OPALDataApiService + orgId string + projId string + envId string + internalUpdateCache *bool +} + +func (r ApiGetAllDataRequest) InternalUpdateCache(internalUpdateCache bool) ApiGetAllDataRequest { + r.internalUpdateCache = &internalUpdateCache + return r +} + +func (r ApiGetAllDataRequest) Execute() (*models.FullData, *http.Response, error) { + return r.ApiService.GetAllDataExecute(r) +} + +/* +GetAllData Get All Data + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiGetAllDataRequest +*/ +func (a *OPALDataApiService) GetAllData(ctx context.Context, orgId string, projId string, envId string) ApiGetAllDataRequest { + return ApiGetAllDataRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return FullData +func (a *OPALDataApiService) GetAllDataExecute(r ApiGetAllDataRequest) (*models.FullData, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.FullData + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OPALDataApiService.GetAllData") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/internal/opal_data/{org_id}/{proj_id}/{env_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.internalUpdateCache != nil { + localVarQueryParams.Add("__internal_update_cache", parameterToString(*r.internalUpdateCache, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetDataForRoleRequest struct { + ctx context.Context + ApiService *OPALDataApiService + orgId string + projId string + envId string + roleId string +} + +func (r ApiGetDataForRoleRequest) Execute() (*models.RoleData, *http.Response, error) { + return r.ApiService.GetDataForRoleExecute(r) +} + +/* +GetDataForRole Get Data For Role + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId + @return ApiGetDataForRoleRequest +*/ +func (a *OPALDataApiService) GetDataForRole(ctx context.Context, orgId string, projId string, envId string, roleId string) ApiGetDataForRoleRequest { + return ApiGetDataForRoleRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + projId: projId, + envId: envId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return RoleData +func (a *OPALDataApiService) GetDataForRoleExecute(r ApiGetDataForRoleRequest) (*models.RoleData, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleData + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OPALDataApiService.GetDataForRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/internal/opal_data/{org_id}/{proj_id}/{env_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetDataForSetRuleRequest struct { + ctx context.Context + ApiService *OPALDataApiService + orgId string + projId string + envId string + userSetId string + resourceSetId string +} + +func (r ApiGetDataForSetRuleRequest) Execute() (*map[string][]string, *http.Response, error) { + return r.ApiService.GetDataForSetRuleExecute(r) +} + +/* +GetDataForSetRule Get Data For Set Rule + +return permission assignment data between user sets and resource sets (i.e: condition set rules data) + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userSetId + @param resourceSetId + @return ApiGetDataForSetRuleRequest +*/ +func (a *OPALDataApiService) GetDataForSetRule(ctx context.Context, orgId string, projId string, envId string, userSetId string, resourceSetId string) ApiGetDataForSetRuleRequest { + return ApiGetDataForSetRuleRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + projId: projId, + envId: envId, + userSetId: userSetId, + resourceSetId: resourceSetId, + } +} + +// Execute executes the request +// +// @return map[string][]string +func (a *OPALDataApiService) GetDataForSetRuleExecute(r ApiGetDataForSetRuleRequest) (*map[string][]string, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *map[string][]string + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OPALDataApiService.GetDataForSetRule") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/internal/opal_data/{org_id}/{proj_id}/{env_id}/condition_set_rules/{user_set_id}/{resource_set_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_set_id"+"}", url.PathEscape(parameterToString(r.userSetId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_set_id"+"}", url.PathEscape(parameterToString(r.resourceSetId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetDataForUserRequest struct { + ctx context.Context + ApiService *OPALDataApiService + orgId string + projId string + envId string + userId string +} + +func (r ApiGetDataForUserRequest) Execute() (*models.UserData, *http.Response, error) { + return r.ApiService.GetDataForUserExecute(r) +} + +/* +GetDataForUser Get Data For User + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId + @return ApiGetDataForUserRequest +*/ +func (a *OPALDataApiService) GetDataForUser(ctx context.Context, orgId string, projId string, envId string, userId string) ApiGetDataForUserRequest { + return ApiGetDataForUserRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +// +// @return UserData +func (a *OPALDataApiService) GetDataForUserExecute(r ApiGetDataForUserRequest) (*models.UserData, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserData + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OPALDataApiService.GetDataForUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/internal/opal_data/{org_id}/{proj_id}/{env_id}/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_organizations.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_organizations.go new file mode 100644 index 00000000..d36072b5 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_organizations.go @@ -0,0 +1,1113 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// OrganizationsApiService OrganizationsApi service +type OrganizationsApiService service + +type ApiCancelInviteRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + orgId string + inviteId string +} + +func (r ApiCancelInviteRequest) Execute() (*http.Response, error) { + return r.ApiService.CancelInviteExecute(r) +} + +/* +CancelInvite Cancel Invite + +Cancels an invite that was sent to a new member. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @param inviteId Id of the invite to cancel + @return ApiCancelInviteRequest +*/ +func (a *OrganizationsApiService) CancelInvite(ctx context.Context, orgId string, inviteId string) ApiCancelInviteRequest { + return ApiCancelInviteRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + inviteId: inviteId, + } +} + +// Execute executes the request +func (a *OrganizationsApiService) CancelInviteExecute(r ApiCancelInviteRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.CancelInvite") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/{org_id}/invites/{invite_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"invite_id"+"}", url.PathEscape(parameterToString(r.inviteId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiCreateOrganizationRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + organizationCreate *models.OrganizationCreate +} + +func (r ApiCreateOrganizationRequest) OrganizationCreate(organizationCreate models.OrganizationCreate) ApiCreateOrganizationRequest { + r.organizationCreate = &organizationCreate + return r +} + +func (r ApiCreateOrganizationRequest) Execute() (*models.OrganizationReadWithAPIKey, *http.Response, error) { + return r.ApiService.CreateOrganizationExecute(r) +} + +/* +CreateOrganization Create Organization + +Creates a new organization that will be owned by the +authenticated actor (i.e: human team member or api key). + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateOrganizationRequest +*/ +func (a *OrganizationsApiService) CreateOrganization(ctx context.Context) ApiCreateOrganizationRequest { + return ApiCreateOrganizationRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return OrganizationReadWithAPIKey +func (a *OrganizationsApiService) CreateOrganizationExecute(r ApiCreateOrganizationRequest) (*models.OrganizationReadWithAPIKey, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationReadWithAPIKey + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.CreateOrganization") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.organizationCreate == nil { + return localVarReturnValue, nil, reportError("organizationCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.organizationCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteOrganizationRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + orgId string +} + +func (r ApiDeleteOrganizationRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteOrganizationExecute(r) +} + +/* +DeleteOrganization Delete Organization + +Deletes an organization (Permit.io account) and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @return ApiDeleteOrganizationRequest +*/ +func (a *OrganizationsApiService) DeleteOrganization(ctx context.Context, orgId string) ApiDeleteOrganizationRequest { + return ApiDeleteOrganizationRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + } +} + +// Execute executes the request +func (a *OrganizationsApiService) DeleteOrganizationExecute(r ApiDeleteOrganizationRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.DeleteOrganization") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/{org_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetActiveOrganizationRequest struct { + ctx context.Context + ApiService *OrganizationsApiService +} + +func (r ApiGetActiveOrganizationRequest) Execute() (*models.OrganizationRead, *http.Response, error) { + return r.ApiService.GetActiveOrganizationExecute(r) +} + +/* +GetActiveOrganization Get Active Organization + +Gets a single organization (Permit.io account) matching the given org_id, +if such org exists and can be accessed by the authenticated actor. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetActiveOrganizationRequest +*/ +func (a *OrganizationsApiService) GetActiveOrganization(ctx context.Context) ApiGetActiveOrganizationRequest { + return ApiGetActiveOrganizationRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return OrganizationRead +func (a *OrganizationsApiService) GetActiveOrganizationExecute(r ApiGetActiveOrganizationRequest) (*models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.GetActiveOrganization") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/active/org" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetOrganizationRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + orgId string +} + +func (r ApiGetOrganizationRequest) Execute() (*models.OrganizationRead, *http.Response, error) { + return r.ApiService.GetOrganizationExecute(r) +} + +/* +GetOrganization Get Organization + +Gets a single organization (Permit.io account) matching the given org_id, +if such org exists and can be accessed by the authenticated actor. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @return ApiGetOrganizationRequest +*/ +func (a *OrganizationsApiService) GetOrganization(ctx context.Context, orgId string) ApiGetOrganizationRequest { + return ApiGetOrganizationRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + } +} + +// Execute executes the request +// +// @return OrganizationRead +func (a *OrganizationsApiService) GetOrganizationExecute(r ApiGetOrganizationRequest) (*models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.GetOrganization") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/{org_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiInviteMembersToOrganizationRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + orgId string + inviteCreate *[]models.InviteCreate + inviterName *string + inviterEmail *string +} + +func (r ApiInviteMembersToOrganizationRequest) InviteCreate(inviteCreate []models.InviteCreate) ApiInviteMembersToOrganizationRequest { + r.inviteCreate = &inviteCreate + return r +} + +func (r ApiInviteMembersToOrganizationRequest) InviterName(inviterName string) ApiInviteMembersToOrganizationRequest { + r.inviterName = &inviterName + return r +} + +func (r ApiInviteMembersToOrganizationRequest) InviterEmail(inviterEmail string) ApiInviteMembersToOrganizationRequest { + r.inviterEmail = &inviterEmail + return r +} + +func (r ApiInviteMembersToOrganizationRequest) Execute() (*models.MultiInviteResult, *http.Response, error) { + return r.ApiService.InviteMembersToOrganizationExecute(r) +} + +/* +InviteMembersToOrganization Invite Members To Organization + +Invite new members into the organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @return ApiInviteMembersToOrganizationRequest +*/ +func (a *OrganizationsApiService) InviteMembersToOrganization(ctx context.Context, orgId string) ApiInviteMembersToOrganizationRequest { + return ApiInviteMembersToOrganizationRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + } +} + +// Execute executes the request +// +// @return MultiInviteResult +func (a *OrganizationsApiService) InviteMembersToOrganizationExecute(r ApiInviteMembersToOrganizationRequest) (*models.MultiInviteResult, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.MultiInviteResult + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.InviteMembersToOrganization") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/{org_id}/invites" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.inviteCreate == nil { + return localVarReturnValue, nil, reportError("inviteCreate is required and must be specified") + } + + if r.inviterName != nil { + localVarQueryParams.Add("inviter_name", parameterToString(*r.inviterName, "")) + } + if r.inviterEmail != nil { + localVarQueryParams.Add("inviter_email", parameterToString(*r.inviterEmail, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.inviteCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListOrganizationInvitesRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + orgId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListOrganizationInvitesRequest) Page(page int32) ApiListOrganizationInvitesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListOrganizationInvitesRequest) PerPage(perPage int32) ApiListOrganizationInvitesRequest { + r.perPage = &perPage + return r +} + +func (r ApiListOrganizationInvitesRequest) Execute() ([]models.InviteRead, *http.Response, error) { + return r.ApiService.ListOrganizationInvitesExecute(r) +} + +/* +ListOrganizationInvites List Organization Invites + +Lists pending organization invites + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @return ApiListOrganizationInvitesRequest +*/ +func (a *OrganizationsApiService) ListOrganizationInvites(ctx context.Context, orgId string) ApiListOrganizationInvitesRequest { + return ApiListOrganizationInvitesRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + } +} + +// Execute executes the request +// +// @return []InviteRead +func (a *OrganizationsApiService) ListOrganizationInvitesExecute(r ApiListOrganizationInvitesRequest) ([]models.InviteRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.InviteRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.ListOrganizationInvites") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/{org_id}/invites" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListOrganizationsRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListOrganizationsRequest) Page(page int32) ApiListOrganizationsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListOrganizationsRequest) PerPage(perPage int32) ApiListOrganizationsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListOrganizationsRequest) Execute() ([]models.OrganizationRead, *http.Response, error) { + return r.ApiService.ListOrganizationsExecute(r) +} + +/* +ListOrganizations List Organizations + +Lists all the organizations that can be accessed by the +authenticated actor (i.e: human team member or api key). + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiListOrganizationsRequest +*/ +func (a *OrganizationsApiService) ListOrganizations(ctx context.Context) ApiListOrganizationsRequest { + return ApiListOrganizationsRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return []OrganizationRead +func (a *OrganizationsApiService) ListOrganizationsExecute(r ApiListOrganizationsRequest) ([]models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.ListOrganizations") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateOrganizationRequest struct { + ctx context.Context + ApiService *OrganizationsApiService + orgId string + organizationUpdate *models.OrganizationUpdate +} + +func (r ApiUpdateOrganizationRequest) OrganizationUpdate(organizationUpdate models.OrganizationUpdate) ApiUpdateOrganizationRequest { + r.organizationUpdate = &organizationUpdate + return r +} + +func (r ApiUpdateOrganizationRequest) Execute() (*models.OrganizationRead, *http.Response, error) { + return r.ApiService.UpdateOrganizationExecute(r) +} + +/* +UpdateOrganization Update Organization + +Updates the organization's profile. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param orgId Either the unique id of the organization, or the URL-friendly key of the organization (i.e: the \"slug\"). + @return ApiUpdateOrganizationRequest +*/ +func (a *OrganizationsApiService) UpdateOrganization(ctx context.Context, orgId string) ApiUpdateOrganizationRequest { + return ApiUpdateOrganizationRequest{ + ApiService: a, + ctx: ctx, + orgId: orgId, + } +} + +// Execute executes the request +// +// @return OrganizationRead +func (a *OrganizationsApiService) UpdateOrganizationExecute(r ApiUpdateOrganizationRequest) (*models.OrganizationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.OrganizationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "OrganizationsApiService.UpdateOrganization") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/orgs/{org_id}" + localVarPath = strings.Replace(localVarPath, "{"+"org_id"+"}", url.PathEscape(parameterToString(r.orgId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.organizationUpdate == nil { + return localVarReturnValue, nil, reportError("organizationUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.organizationUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy.go new file mode 100644 index 00000000..803db3e2 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy.go @@ -0,0 +1,257 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" +) + +// PolicyApiService PolicyApi service +type PolicyApiService service + +type ApiGetOpalDataSourcesRequest struct { + ctx context.Context + ApiService *PolicyApiService + token *string +} + +func (r ApiGetOpalDataSourcesRequest) Token(token string) ApiGetOpalDataSourcesRequest { + r.token = &token + return r +} + +func (r ApiGetOpalDataSourcesRequest) Execute() (*models.DataSourceConfig, *http.Response, error) { + return r.ApiService.GetOpalDataSourcesExecute(r) +} + +/* +GetOpalDataSources Get Opal Data Sources + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetOpalDataSourcesRequest +*/ +func (a *PolicyApiService) GetOpalDataSources(ctx context.Context) ApiGetOpalDataSourcesRequest { + return ApiGetOpalDataSourcesRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return DataSourceConfig +func (a *PolicyApiService) GetOpalDataSourcesExecute(r ApiGetOpalDataSourcesRequest) (*models.DataSourceConfig, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.DataSourceConfig + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyApiService.GetOpalDataSources") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/opal/data/config" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.token != nil { + localVarQueryParams.Add("token", parameterToString(*r.token, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetOpalDataSourcesOpalDataConfigGetRequest struct { + ctx context.Context + ApiService *PolicyApiService + token *string +} + +func (r ApiGetOpalDataSourcesOpalDataConfigGetRequest) Token(token string) ApiGetOpalDataSourcesOpalDataConfigGetRequest { + r.token = &token + return r +} + +func (r ApiGetOpalDataSourcesOpalDataConfigGetRequest) Execute() (*models.DataSourceConfig, *http.Response, error) { + return r.ApiService.GetOpalDataSourcesOpalDataConfigGetExecute(r) +} + +/* +GetOpalDataSourcesOpalDataConfigGet Get Opal Data Sources + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetOpalDataSourcesOpalDataConfigGetRequest +*/ +func (a *PolicyApiService) GetOpalDataSourcesOpalDataConfigGet(ctx context.Context) ApiGetOpalDataSourcesOpalDataConfigGetRequest { + return ApiGetOpalDataSourcesOpalDataConfigGetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return DataSourceConfig +func (a *PolicyApiService) GetOpalDataSourcesOpalDataConfigGetExecute(r ApiGetOpalDataSourcesOpalDataConfigGetRequest) (*models.DataSourceConfig, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.DataSourceConfig + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyApiService.GetOpalDataSourcesOpalDataConfigGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/opal/data/config" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.token != nil { + localVarQueryParams.Add("token", parameterToString(*r.token, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_decision_points.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_decision_points.go new file mode 100644 index 00000000..e883a2f4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_decision_points.go @@ -0,0 +1,654 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// PolicyDecisionPointsApiService PolicyDecisionPointsApi service +type PolicyDecisionPointsApiService service + +type ApiGetAuthenticatingPdpConfigValuesRequest struct { + ctx context.Context + ApiService *PolicyDecisionPointsApiService + pDPStateUpdate *models.PDPStateUpdate +} + +func (r ApiGetAuthenticatingPdpConfigValuesRequest) PDPStateUpdate(pDPStateUpdate models.PDPStateUpdate) ApiGetAuthenticatingPdpConfigValuesRequest { + r.pDPStateUpdate = &pDPStateUpdate + return r +} + +func (r ApiGetAuthenticatingPdpConfigValuesRequest) Execute() (*models.RemoteConfig, *http.Response, error) { + return r.ApiService.GetAuthenticatingPdpConfigValuesExecute(r) +} + +/* +GetAuthenticatingPdpConfigValues Get connected PDP configuration and push state + +Gets the configuration values for the currently authenticated PDP container. + +The PDP authenticates with an API key scoped to a given Permit.io environment. +The system identifies the PDP via its API key and then returns all the configuration +values required for the container to run correctly. + +The config values returned are considered "overrides", meaning they are overriding +any default values given to the container by the user. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetAuthenticatingPdpConfigValuesRequest +*/ +func (a *PolicyDecisionPointsApiService) GetAuthenticatingPdpConfigValues(ctx context.Context) ApiGetAuthenticatingPdpConfigValuesRequest { + return ApiGetAuthenticatingPdpConfigValuesRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return RemoteConfig +func (a *PolicyDecisionPointsApiService) GetAuthenticatingPdpConfigValuesExecute(r ApiGetAuthenticatingPdpConfigValuesRequest) (*models.RemoteConfig, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RemoteConfig + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyDecisionPointsApiService.GetAuthenticatingPdpConfigValues") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/pdps/me/config" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.pDPStateUpdate == nil { + return localVarReturnValue, nil, reportError("pDPStateUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.pDPStateUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetAuthenticatingPdpConfigValuesLegacyRequest struct { + ctx context.Context + ApiService *PolicyDecisionPointsApiService +} + +func (r ApiGetAuthenticatingPdpConfigValuesLegacyRequest) Execute() (*models.RemoteConfig, *http.Response, error) { + return r.ApiService.GetAuthenticatingPdpConfigValuesLegacyExecute(r) +} + +/* +GetAuthenticatingPdpConfigValuesLegacy Get connected PDP configuration + +Gets the configuration values for the currently authenticated PDP container. + +The PDP authenticates with an API key scoped to a given Permit.io environment. +The system identifies the PDP via its API key and then returns all the configuration +values required for the container to run correctly. + +The config values returned are considered "overrides", meaning they are overriding +any default values given to the container by the user. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiGetAuthenticatingPdpConfigValuesLegacyRequest +*/ +func (a *PolicyDecisionPointsApiService) GetAuthenticatingPdpConfigValuesLegacy(ctx context.Context) ApiGetAuthenticatingPdpConfigValuesLegacyRequest { + return ApiGetAuthenticatingPdpConfigValuesLegacyRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return RemoteConfig +func (a *PolicyDecisionPointsApiService) GetAuthenticatingPdpConfigValuesLegacyExecute(r ApiGetAuthenticatingPdpConfigValuesLegacyRequest) (*models.RemoteConfig, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RemoteConfig + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyDecisionPointsApiService.GetAuthenticatingPdpConfigValuesLegacy") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/pdps/me/config" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetPdpConfigValuesRequest struct { + ctx context.Context + ApiService *PolicyDecisionPointsApiService + projId string + envId string + pdpId string +} + +func (r ApiGetPdpConfigValuesRequest) Execute() (*models.RemoteConfig, *http.Response, error) { + return r.ApiService.GetPdpConfigValuesExecute(r) +} + +/* +GetPdpConfigValues Get PDP configuration + +Gets the configuration values for the PDP container with id `pdp_id`. + +The config values returned are considered "overrides", meaning they are overriding +any default values given to the container by the user. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param pdpId The unique id of the pdp + @return ApiGetPdpConfigValuesRequest +*/ +func (a *PolicyDecisionPointsApiService) GetPdpConfigValues(ctx context.Context, projId string, envId string, pdpId string) ApiGetPdpConfigValuesRequest { + return ApiGetPdpConfigValuesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + pdpId: pdpId, + } +} + +// Execute executes the request +// +// @return RemoteConfig +func (a *PolicyDecisionPointsApiService) GetPdpConfigValuesExecute(r ApiGetPdpConfigValuesRequest) (*models.RemoteConfig, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RemoteConfig + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyDecisionPointsApiService.GetPdpConfigValues") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/pdps/{proj_id}/{env_id}/configs/{pdp_id}/values" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"pdp_id"+"}", url.PathEscape(parameterToString(r.pdpId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListPdpConfigsRequest struct { + ctx context.Context + ApiService *PolicyDecisionPointsApiService + projId string + envId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListPdpConfigsRequest) Page(page int32) ApiListPdpConfigsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListPdpConfigsRequest) PerPage(perPage int32) ApiListPdpConfigsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListPdpConfigsRequest) Execute() ([]models.PDPConfigRead, *http.Response, error) { + return r.ApiService.ListPdpConfigsExecute(r) +} + +/* +ListPdpConfigs List PDP configurations + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListPdpConfigsRequest +*/ +func (a *PolicyDecisionPointsApiService) ListPdpConfigs(ctx context.Context, projId string, envId string) ApiListPdpConfigsRequest { + return ApiListPdpConfigsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []PDPConfigRead +func (a *PolicyDecisionPointsApiService) ListPdpConfigsExecute(r ApiListPdpConfigsRequest) ([]models.PDPConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.PDPConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyDecisionPointsApiService.ListPdpConfigs") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/pdps/{proj_id}/{env_id}/configs" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiRotatePdpApiKeyRequest struct { + ctx context.Context + ApiService *PolicyDecisionPointsApiService + projId string + envId string + pdpId string +} + +func (r ApiRotatePdpApiKeyRequest) Execute() (*models.PDPConfigRead, *http.Response, error) { + return r.ApiService.RotatePdpApiKeyExecute(r) +} + +/* +RotatePdpApiKey Rotate PDP API Key + +Rotates the API key of the PDP container with id `pdp_id`. + +The rotation of the API key revokes the old API key and issues a new API key to the PDP. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param pdpId The unique id of the pdp + @return ApiRotatePdpApiKeyRequest +*/ +func (a *PolicyDecisionPointsApiService) RotatePdpApiKey(ctx context.Context, projId string, envId string, pdpId string) ApiRotatePdpApiKeyRequest { + return ApiRotatePdpApiKeyRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + pdpId: pdpId, + } +} + +// Execute executes the request +// +// @return PDPConfigRead +func (a *PolicyDecisionPointsApiService) RotatePdpApiKeyExecute(r ApiRotatePdpApiKeyRequest) (*models.PDPConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PDPConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyDecisionPointsApiService.RotatePdpApiKey") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/pdps/{proj_id}/{env_id}/configs/{pdp_id}/rotate-api-key" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"pdp_id"+"}", url.PathEscape(parameterToString(r.pdpId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_git_repositories.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_git_repositories.go new file mode 100644 index 00000000..1b35d2a4 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_policy_git_repositories.go @@ -0,0 +1,858 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// PolicyGitRepositoriesApiService PolicyGitRepositoriesApi service +type PolicyGitRepositoriesApiService service + +type ApiActivatePolicyRepoRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string + repoId string +} + +func (r ApiActivatePolicyRepoRequest) Execute() (*models.ProjectRead, *http.Response, error) { + return r.ApiService.ActivatePolicyRepoExecute(r) +} + +/* +ActivatePolicyRepo Activate Policy Repo + +Disable the currently active policy repo, this action means to turn off the gitops feature. +If there is no active policy repo, this action will do nothing. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param repoId Either the unique id of the policy repo, or the URL-friendly key of the policy repo (i.e: the \"slug\"). + @return ApiActivatePolicyRepoRequest +*/ +func (a *PolicyGitRepositoriesApiService) ActivatePolicyRepo(ctx context.Context, projId string, repoId string) ApiActivatePolicyRepoRequest { + return ApiActivatePolicyRepoRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + repoId: repoId, + } +} + +// Execute executes the request +// +// @return ProjectRead +func (a *PolicyGitRepositoriesApiService) ActivatePolicyRepoExecute(r ApiActivatePolicyRepoRequest) (*models.ProjectRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProjectRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.ActivatePolicyRepo") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos/{repo_id}/activate" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"repo_id"+"}", url.PathEscape(parameterToString(r.repoId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiCreatePolicyRepoRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string + policyRepoCreate *models.PolicyRepoCreate +} + +func (r ApiCreatePolicyRepoRequest) PolicyRepoCreate(policyRepoCreate models.PolicyRepoCreate) ApiCreatePolicyRepoRequest { + r.policyRepoCreate = &policyRepoCreate + return r +} + +func (r ApiCreatePolicyRepoRequest) Execute() (*models.PolicyRepoRead, *http.Response, error) { + return r.ApiService.CreatePolicyRepoExecute(r) +} + +/* +CreatePolicyRepo Create Policy Repo + +Creates a new policy repository configuration under a given project. +The given repository is created with status 'pending', it will be changed and used as the 'active' repository for +the policy only after a successful attempt to use it. +The repository main branch must be present in the remote. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiCreatePolicyRepoRequest +*/ +func (a *PolicyGitRepositoriesApiService) CreatePolicyRepo(ctx context.Context, projId string) ApiCreatePolicyRepoRequest { + return ApiCreatePolicyRepoRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return PolicyRepoRead +func (a *PolicyGitRepositoriesApiService) CreatePolicyRepoExecute(r ApiCreatePolicyRepoRequest) (*models.PolicyRepoRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PolicyRepoRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.CreatePolicyRepo") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.policyRepoCreate == nil { + return localVarReturnValue, nil, reportError("policyRepoCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.policyRepoCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeletePolicyRepoRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string + repoId string +} + +func (r ApiDeletePolicyRepoRequest) Execute() (*http.Response, error) { + return r.ApiService.DeletePolicyRepoExecute(r) +} + +/* +DeletePolicyRepo Delete Policy Repo + +Deletes an environment and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param repoId Either the unique id of the policy repo, or the URL-friendly key of the policy repo (i.e: the \"slug\"). + @return ApiDeletePolicyRepoRequest +*/ +func (a *PolicyGitRepositoriesApiService) DeletePolicyRepo(ctx context.Context, projId string, repoId string) ApiDeletePolicyRepoRequest { + return ApiDeletePolicyRepoRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + repoId: repoId, + } +} + +// Execute executes the request +func (a *PolicyGitRepositoriesApiService) DeletePolicyRepoExecute(r ApiDeletePolicyRepoRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.DeletePolicyRepo") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos/{repo_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"repo_id"+"}", url.PathEscape(parameterToString(r.repoId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiDisableActivePolicyRepoRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string +} + +func (r ApiDisableActivePolicyRepoRequest) Execute() (*models.ProjectRead, *http.Response, error) { + return r.ApiService.DisableActivePolicyRepoExecute(r) +} + +/* +DisableActivePolicyRepo Disable Active Policy Repo + +Disable the currently active policy repo, this action means to turn off the gitops feature. +If there is no active policy repo, this action will do nothing. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiDisableActivePolicyRepoRequest +*/ +func (a *PolicyGitRepositoriesApiService) DisableActivePolicyRepo(ctx context.Context, projId string) ApiDisableActivePolicyRepoRequest { + return ApiDisableActivePolicyRepoRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return ProjectRead +func (a *PolicyGitRepositoriesApiService) DisableActivePolicyRepoExecute(r ApiDisableActivePolicyRepoRequest) (*models.ProjectRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProjectRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.DisableActivePolicyRepo") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos/disable" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetActivePolicyRepoRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string +} + +func (r ApiGetActivePolicyRepoRequest) Execute() (*models.PolicyRepoRead, *http.Response, error) { + return r.ApiService.GetActivePolicyRepoExecute(r) +} + +/* +GetActivePolicyRepo Get Active Policy Repo + +Gets the currently active repository, if such repository exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiGetActivePolicyRepoRequest +*/ +func (a *PolicyGitRepositoriesApiService) GetActivePolicyRepo(ctx context.Context, projId string) ApiGetActivePolicyRepoRequest { + return ApiGetActivePolicyRepoRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return PolicyRepoRead +func (a *PolicyGitRepositoriesApiService) GetActivePolicyRepoExecute(r ApiGetActivePolicyRepoRequest) (*models.PolicyRepoRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PolicyRepoRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.GetActivePolicyRepo") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos/active" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetPolicyRepoRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string + repoId string +} + +func (r ApiGetPolicyRepoRequest) Execute() (*models.PolicyRepoRead, *http.Response, error) { + return r.ApiService.GetPolicyRepoExecute(r) +} + +/* +GetPolicyRepo Get Policy Repo + +Gets a single repository matching the given repo_id, if such repository exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param repoId Either the unique id of the policy repo, or the URL-friendly key of the policy repo (i.e: the \"slug\"). + @return ApiGetPolicyRepoRequest +*/ +func (a *PolicyGitRepositoriesApiService) GetPolicyRepo(ctx context.Context, projId string, repoId string) ApiGetPolicyRepoRequest { + return ApiGetPolicyRepoRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + repoId: repoId, + } +} + +// Execute executes the request +// +// @return PolicyRepoRead +func (a *PolicyGitRepositoriesApiService) GetPolicyRepoExecute(r ApiGetPolicyRepoRequest) (*models.PolicyRepoRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PolicyRepoRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.GetPolicyRepo") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos/{repo_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"repo_id"+"}", url.PathEscape(parameterToString(r.repoId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListPolicyReposRequest struct { + ctx context.Context + ApiService *PolicyGitRepositoriesApiService + projId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListPolicyReposRequest) Page(page int32) ApiListPolicyReposRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListPolicyReposRequest) PerPage(perPage int32) ApiListPolicyReposRequest { + r.perPage = &perPage + return r +} + +func (r ApiListPolicyReposRequest) Execute() ([]models.PolicyRepoRead, *http.Response, error) { + return r.ApiService.ListPolicyReposExecute(r) +} + +/* +ListPolicyRepos List Policy Repos + +Lists all the policy repositories under a given project. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiListPolicyReposRequest +*/ +func (a *PolicyGitRepositoriesApiService) ListPolicyRepos(ctx context.Context, projId string) ApiListPolicyReposRequest { + return ApiListPolicyReposRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return []PolicyRepoRead +func (a *PolicyGitRepositoriesApiService) ListPolicyReposExecute(r ApiListPolicyReposRequest) ([]models.PolicyRepoRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.PolicyRepoRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PolicyGitRepositoriesApiService.ListPolicyRepos") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}/repos" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_projects.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_projects.go new file mode 100644 index 00000000..3983c172 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_projects.go @@ -0,0 +1,616 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ProjectsApiService ProjectsApi service +type ProjectsApiService service + +type ApiCreateProjectRequest struct { + ctx context.Context + ApiService *ProjectsApiService + projectCreate *models.ProjectCreate +} + +func (r ApiCreateProjectRequest) ProjectCreate(projectCreate models.ProjectCreate) ApiCreateProjectRequest { + r.projectCreate = &projectCreate + return r +} + +func (r ApiCreateProjectRequest) Execute() (*models.ProjectRead, *http.Response, error) { + return r.ApiService.CreateProjectExecute(r) +} + +/* +CreateProject Create Project + +Creates a new project under the active organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiCreateProjectRequest +*/ +func (a *ProjectsApiService) CreateProject(ctx context.Context) ApiCreateProjectRequest { + return ApiCreateProjectRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return ProjectRead +func (a *ProjectsApiService) CreateProjectExecute(r ApiCreateProjectRequest) (*models.ProjectRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProjectRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectsApiService.CreateProject") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.projectCreate == nil { + return localVarReturnValue, nil, reportError("projectCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.projectCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteProjectRequest struct { + ctx context.Context + ApiService *ProjectsApiService + projId string +} + +func (r ApiDeleteProjectRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteProjectExecute(r) +} + +/* +DeleteProject Delete Project + +Deletes the project and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiDeleteProjectRequest +*/ +func (a *ProjectsApiService) DeleteProject(ctx context.Context, projId string) ApiDeleteProjectRequest { + return ApiDeleteProjectRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +func (a *ProjectsApiService) DeleteProjectExecute(r ApiDeleteProjectRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectsApiService.DeleteProject") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetProjectRequest struct { + ctx context.Context + ApiService *ProjectsApiService + projId string +} + +func (r ApiGetProjectRequest) Execute() (*models.ProjectRead, *http.Response, error) { + return r.ApiService.GetProjectExecute(r) +} + +/* +GetProject Get Project + +Gets a single project matching the given proj_id, if such project exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiGetProjectRequest +*/ +func (a *ProjectsApiService) GetProject(ctx context.Context, projId string) ApiGetProjectRequest { + return ApiGetProjectRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return ProjectRead +func (a *ProjectsApiService) GetProjectExecute(r ApiGetProjectRequest) (*models.ProjectRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProjectRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectsApiService.GetProject") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListProjectsRequest struct { + ctx context.Context + ApiService *ProjectsApiService + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListProjectsRequest) Page(page int32) ApiListProjectsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListProjectsRequest) PerPage(perPage int32) ApiListProjectsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListProjectsRequest) Execute() ([]models.ProjectRead, *http.Response, error) { + return r.ApiService.ListProjectsExecute(r) +} + +/* +ListProjects List Projects + +Lists all the projects under the active organization. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiListProjectsRequest +*/ +func (a *ProjectsApiService) ListProjects(ctx context.Context) ApiListProjectsRequest { + return ApiListProjectsRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return []ProjectRead +func (a *ProjectsApiService) ListProjectsExecute(r ApiListProjectsRequest) ([]models.ProjectRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ProjectRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectsApiService.ListProjects") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateProjectRequest struct { + ctx context.Context + ApiService *ProjectsApiService + projId string + projectUpdate *models.ProjectUpdate +} + +func (r ApiUpdateProjectRequest) ProjectUpdate(projectUpdate models.ProjectUpdate) ApiUpdateProjectRequest { + r.projectUpdate = &projectUpdate + return r +} + +func (r ApiUpdateProjectRequest) Execute() (*models.ProjectRead, *http.Response, error) { + return r.ApiService.UpdateProjectExecute(r) +} + +/* +UpdateProject Update Project + +Updates the project. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @return ApiUpdateProjectRequest +*/ +func (a *ProjectsApiService) UpdateProject(ctx context.Context, projId string) ApiUpdateProjectRequest { + return ApiUpdateProjectRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + } +} + +// Execute executes the request +// +// @return ProjectRead +func (a *ProjectsApiService) UpdateProjectExecute(r ApiUpdateProjectRequest) (*models.ProjectRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProjectRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectsApiService.UpdateProject") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/projects/{proj_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.projectUpdate == nil { + return localVarReturnValue, nil, reportError("projectUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.projectUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_proxy_config.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_proxy_config.go new file mode 100644 index 00000000..7c4a76ba --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_proxy_config.go @@ -0,0 +1,666 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ProxyConfigAPIService ProxyConfigAPI service +type ProxyConfigAPIService service + +type ApiCreateProxyConfigRequest struct { + ctx context.Context + ApiService *ProxyConfigAPIService + projId string + envId string + proxyConfigCreate *models.ProxyConfigCreate +} + +func (r ApiCreateProxyConfigRequest) ProxyConfigCreate(proxyConfigCreate models.ProxyConfigCreate) ApiCreateProxyConfigRequest { + r.proxyConfigCreate = &proxyConfigCreate + return r +} + +func (r ApiCreateProxyConfigRequest) Execute() (*models.ProxyConfigRead, *http.Response, error) { + return r.ApiService.CreateProxyConfigExecute(r) +} + +/* +CreateProxyConfig Create Proxy Config + +Creates a new proxy config inside the Permit.io system. + +If the proxy config is already created: will return 200 instead of 201, +and will return the existing proxy config object in the response body. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateProxyConfigRequest +*/ +func (a *ProxyConfigAPIService) CreateProxyConfig(ctx context.Context, projId string, envId string) ApiCreateProxyConfigRequest { + return ApiCreateProxyConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ProxyConfigRead +func (a *ProxyConfigAPIService) CreateProxyConfigExecute(r ApiCreateProxyConfigRequest) (*models.ProxyConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProxyConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProxyConfigAPIService.CreateProxyConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/proxy_configs" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.proxyConfigCreate == nil { + return localVarReturnValue, nil, reportError("proxyConfigCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.proxyConfigCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteProxyConfigRequest struct { + ctx context.Context + ApiService *ProxyConfigAPIService + projId string + envId string + proxyConfigId string +} + +func (r ApiDeleteProxyConfigRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteProxyConfigExecute(r) +} + +/* +DeleteProxyConfig Delete Proxy Config + +Deletes the proxy config and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param proxyConfigId Either the unique id of the proxy config, or the URL-friendly key of the proxy config (i.e: the \"slug\"). + @return ApiDeleteProxyConfigRequest +*/ +func (a *ProxyConfigAPIService) DeleteProxyConfig(ctx context.Context, projId string, envId string, proxyConfigId string) ApiDeleteProxyConfigRequest { + return ApiDeleteProxyConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + proxyConfigId: proxyConfigId, + } +} + +// Execute executes the request +func (a *ProxyConfigAPIService) DeleteProxyConfigExecute(r ApiDeleteProxyConfigRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProxyConfigAPIService.DeleteProxyConfig") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/proxy_configs/{proxy_config_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proxy_config_id"+"}", url.PathEscape(parameterToString(r.proxyConfigId, "proxyConfigId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetProxyConfigRequest struct { + ctx context.Context + ApiService *ProxyConfigAPIService + projId string + envId string + proxyConfigId string +} + +func (r ApiGetProxyConfigRequest) Execute() (*models.ProxyConfigRead, *http.Response, error) { + return r.ApiService.GetProxyConfigExecute(r) +} + +/* +GetProxyConfig Get Proxy Config + +Gets a proxy config, if such proxy config exists. Otherwise returns 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param proxyConfigId Either the unique id of the proxy config, or the URL-friendly key of the proxy config (i.e: the \"slug\"). + @return ApiGetProxyConfigRequest +*/ +func (a *ProxyConfigAPIService) GetProxyConfig(ctx context.Context, projId string, envId string, proxyConfigId string) ApiGetProxyConfigRequest { + return ApiGetProxyConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + proxyConfigId: proxyConfigId, + } +} + +// Execute executes the request +// +// @return ProxyConfigRead +func (a *ProxyConfigAPIService) GetProxyConfigExecute(r ApiGetProxyConfigRequest) (*models.ProxyConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProxyConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProxyConfigAPIService.GetProxyConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/proxy_configs/{proxy_config_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proxy_config_id"+"}", url.PathEscape(parameterToString(r.proxyConfigId, "proxyConfigId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListProxyConfigsRequest struct { + ctx context.Context + ApiService *ProxyConfigAPIService + projId string + envId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListProxyConfigsRequest) Page(page int32) ApiListProxyConfigsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListProxyConfigsRequest) PerPage(perPage int32) ApiListProxyConfigsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListProxyConfigsRequest) Execute() ([]models.ProxyConfigRead, *http.Response, error) { + return r.ApiService.ListProxyConfigsExecute(r) +} + +/* +ListProxyConfigs List Proxy Configs + +Lists all the proxy configs defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListProxyConfigsRequest +*/ +func (a *ProxyConfigAPIService) ListProxyConfigs(ctx context.Context, projId string, envId string) ApiListProxyConfigsRequest { + return ApiListProxyConfigsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []ProxyConfigRead +func (a *ProxyConfigAPIService) ListProxyConfigsExecute(r ApiListProxyConfigsRequest) ([]models.ProxyConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ProxyConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProxyConfigAPIService.ListProxyConfigs") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/proxy_configs" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } else { + var defaultValue int32 = 1 + r.page = &defaultValue + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } else { + var defaultValue int32 = 30 + r.perPage = &defaultValue + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateProxyConfigRequest struct { + ctx context.Context + ApiService *ProxyConfigAPIService + projId string + envId string + proxyConfigId string + proxyConfigUpdate *models.ProxyConfigUpdate +} + +func (r ApiUpdateProxyConfigRequest) ProxyConfigUpdate(proxyConfigUpdate models.ProxyConfigUpdate) ApiUpdateProxyConfigRequest { + r.proxyConfigUpdate = &proxyConfigUpdate + return r +} + +func (r ApiUpdateProxyConfigRequest) Execute() (*models.ProxyConfigRead, *http.Response, error) { + return r.ApiService.UpdateProxyConfigExecute(r) +} + +/* +UpdateProxyConfig Update Proxy Config + +Partially updates the proxy config definition. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param proxyConfigId Either the unique id of the proxy config, or the URL-friendly key of the proxy config (i.e: the \"slug\"). + @return ApiUpdateProxyConfigRequest +*/ +func (a *ProxyConfigAPIService) UpdateProxyConfig(ctx context.Context, projId string, envId string, proxyConfigId string) ApiUpdateProxyConfigRequest { + return ApiUpdateProxyConfigRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + proxyConfigId: proxyConfigId, + } +} + +// Execute executes the request +// +// @return ProxyConfigRead +func (a *ProxyConfigAPIService) UpdateProxyConfigExecute(r ApiUpdateProxyConfigRequest) (*models.ProxyConfigRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ProxyConfigRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProxyConfigAPIService.UpdateProxyConfig") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/proxy_configs/{proxy_config_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"proxy_config_id"+"}", url.PathEscape(parameterToString(r.proxyConfigId, "proxyConfigId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.proxyConfigUpdate == nil { + return localVarReturnValue, nil, reportError("proxyConfigUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.proxyConfigUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_relationship_tuples.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_relationship_tuples.go new file mode 100644 index 00000000..b3b2bc08 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_relationship_tuples.go @@ -0,0 +1,751 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// RelationshipTuplesAPIService RelationshipTuplesAPI service +type RelationshipTuplesAPIService service + +type ApiBulkCreateRelationshipTuplesRequest struct { + ctx context.Context + ApiService *RelationshipTuplesAPIService + projId string + envId string + relationshipTupleCreateBulkOperation *models.RelationshipTupleCreateBulkOperation + permitSession *string +} + +func (r ApiBulkCreateRelationshipTuplesRequest) RelationshipTupleCreateBulkOperation(relationshipTupleCreateBulkOperation models.RelationshipTupleCreateBulkOperation) ApiBulkCreateRelationshipTuplesRequest { + r.relationshipTupleCreateBulkOperation = &relationshipTupleCreateBulkOperation + return r +} + +func (r ApiBulkCreateRelationshipTuplesRequest) PermitSession(permitSession string) ApiBulkCreateRelationshipTuplesRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiBulkCreateRelationshipTuplesRequest) Execute() (map[string]interface{}, *http.Response, error) { + return r.ApiService.BulkCreateRelationshipTuplesExecute(r) +} + +/* +BulkCreateRelationshipTuples Bulk Create Relationship Tuples + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiBulkCreateRelationshipTuplesRequest +*/ +func (a *RelationshipTuplesAPIService) BulkCreateRelationshipTuples(ctx context.Context, projId string, envId string) ApiBulkCreateRelationshipTuplesRequest { + return ApiBulkCreateRelationshipTuplesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return map[string]interface{} +func (a *RelationshipTuplesAPIService) BulkCreateRelationshipTuplesExecute(r ApiBulkCreateRelationshipTuplesRequest) (map[string]interface{}, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RelationshipTuplesAPIService.BulkCreateRelationshipTuples") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/relationship_tuples/bulk" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.relationshipTupleCreateBulkOperation == nil { + return localVarReturnValue, nil, reportError("relationshipTupleCreateBulkOperation is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.relationshipTupleCreateBulkOperation + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiBulkDeleteRelationshipTuplesRequest struct { + ctx context.Context + ApiService *RelationshipTuplesAPIService + projId string + envId string + relationshipTupleDeleteBulkOperation *models.RelationshipTupleDeleteBulkOperation + permitSession *string +} + +func (r ApiBulkDeleteRelationshipTuplesRequest) RelationshipTupleDeleteBulkOperation(relationshipTupleDeleteBulkOperation models.RelationshipTupleDeleteBulkOperation) ApiBulkDeleteRelationshipTuplesRequest { + r.relationshipTupleDeleteBulkOperation = &relationshipTupleDeleteBulkOperation + return r +} + +func (r ApiBulkDeleteRelationshipTuplesRequest) PermitSession(permitSession string) ApiBulkDeleteRelationshipTuplesRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiBulkDeleteRelationshipTuplesRequest) Execute() (map[string]interface{}, *http.Response, error) { + return r.ApiService.BulkDeleteRelationshipTuplesExecute(r) +} + +/* +BulkDeleteRelationshipTuples Bulk Delete Relationship Tuples + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiBulkDeleteRelationshipTuplesRequest +*/ +func (a *RelationshipTuplesAPIService) BulkDeleteRelationshipTuples(ctx context.Context, projId string, envId string) ApiBulkDeleteRelationshipTuplesRequest { + return ApiBulkDeleteRelationshipTuplesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return map[string]interface{} +func (a *RelationshipTuplesAPIService) BulkDeleteRelationshipTuplesExecute(r ApiBulkDeleteRelationshipTuplesRequest) (map[string]interface{}, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RelationshipTuplesAPIService.BulkDeleteRelationshipTuples") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/relationship_tuples/bulk" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.relationshipTupleDeleteBulkOperation == nil { + return localVarReturnValue, nil, reportError("relationshipTupleDeleteBulkOperation is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.relationshipTupleDeleteBulkOperation + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiCreateRelationshipTupleRequest struct { + ctx context.Context + ApiService *RelationshipTuplesAPIService + projId string + envId string + relationshipTupleCreate *models.RelationshipTupleCreate + permitSession *string +} + +func (r ApiCreateRelationshipTupleRequest) RelationshipTupleCreate(relationshipTupleCreate models.RelationshipTupleCreate) ApiCreateRelationshipTupleRequest { + r.relationshipTupleCreate = &relationshipTupleCreate + return r +} + +func (r ApiCreateRelationshipTupleRequest) PermitSession(permitSession string) ApiCreateRelationshipTupleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiCreateRelationshipTupleRequest) Execute() (*models.RelationshipTupleRead, *http.Response, error) { + return r.ApiService.CreateRelationshipTupleExecute(r) +} + +/* +CreateRelationshipTuple Create Relationship Tuple + +Create a relationship between two resource instances using a relation. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateRelationshipTupleRequest +*/ +func (a *RelationshipTuplesAPIService) CreateRelationshipTuple(ctx context.Context, projId string, envId string) ApiCreateRelationshipTupleRequest { + return ApiCreateRelationshipTupleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return RelationshipTupleRead +func (a *RelationshipTuplesAPIService) CreateRelationshipTupleExecute(r ApiCreateRelationshipTupleRequest) (*models.RelationshipTupleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RelationshipTupleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RelationshipTuplesAPIService.CreateRelationshipTuple") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/relationship_tuples" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.relationshipTupleCreate == nil { + return localVarReturnValue, nil, reportError("relationshipTupleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.relationshipTupleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteRelationshipTupleRequest struct { + ctx context.Context + ApiService *RelationshipTuplesAPIService + projId string + envId string + relationshipTupleDelete *models.RelationshipTupleDelete + permitSession *string +} + +func (r ApiDeleteRelationshipTupleRequest) RelationshipTupleDelete(relationshipTupleDelete models.RelationshipTupleDelete) ApiDeleteRelationshipTupleRequest { + r.relationshipTupleDelete = &relationshipTupleDelete + return r +} + +func (r ApiDeleteRelationshipTupleRequest) PermitSession(permitSession string) ApiDeleteRelationshipTupleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiDeleteRelationshipTupleRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteRelationshipTupleExecute(r) +} + +/* +DeleteRelationshipTuple Delete Relationship Tuple + +Delete a relationship between two resource instances. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiDeleteRelationshipTupleRequest +*/ +func (a *RelationshipTuplesAPIService) DeleteRelationshipTuple(ctx context.Context, projId string, envId string) ApiDeleteRelationshipTupleRequest { + return ApiDeleteRelationshipTupleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +func (a *RelationshipTuplesAPIService) DeleteRelationshipTupleExecute(r ApiDeleteRelationshipTupleRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RelationshipTuplesAPIService.DeleteRelationshipTuple") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/relationship_tuples" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.relationshipTupleDelete == nil { + return nil, reportError("relationshipTupleDelete is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.relationshipTupleDelete + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiListRelationshipTuplesRequest struct { + ctx context.Context + ApiService *RelationshipTuplesAPIService + projId string + envId string + detailed *bool + page *int32 + perPage *int32 + tenant *string + subject *string + relation *string + object *string + permitSession *string +} + +// If true, will return the full subject and object resource instances. +func (r ApiListRelationshipTuplesRequest) Detailed(detailed bool) ApiListRelationshipTuplesRequest { + r.detailed = &detailed + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListRelationshipTuplesRequest) Page(page int32) ApiListRelationshipTuplesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListRelationshipTuplesRequest) PerPage(perPage int32) ApiListRelationshipTuplesRequest { + r.perPage = &perPage + return r +} + +// The tenant key or id to filter by +func (r ApiListRelationshipTuplesRequest) Tenant(tenant string) ApiListRelationshipTuplesRequest { + r.tenant = &tenant + return r +} + +// The subject to filter by, accepts either the resource instance id or resource_type:resource_instance +func (r ApiListRelationshipTuplesRequest) Subject(subject string) ApiListRelationshipTuplesRequest { + r.subject = &subject + return r +} + +// The relation id or key to filter by +func (r ApiListRelationshipTuplesRequest) Relation(relation string) ApiListRelationshipTuplesRequest { + r.relation = &relation + return r +} + +// The object to filter by, accepts either the resource instance id or resource_type:resource_instance +func (r ApiListRelationshipTuplesRequest) Object(object string) ApiListRelationshipTuplesRequest { + r.object = &object + return r +} + +func (r ApiListRelationshipTuplesRequest) PermitSession(permitSession string) ApiListRelationshipTuplesRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiListRelationshipTuplesRequest) Execute() ([]models.RelationshipTupleRead, *http.Response, error) { + return r.ApiService.ListRelationshipTuplesExecute(r) +} + +/* +ListRelationshipTuples List Relationship Tuples + +Lists the relationship tuples defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListRelationshipTuplesRequest +*/ +func (a *RelationshipTuplesAPIService) ListRelationshipTuples(ctx context.Context, projId string, envId string) ApiListRelationshipTuplesRequest { + return ApiListRelationshipTuplesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []RelationshipTupleRead +func (a *RelationshipTuplesAPIService) ListRelationshipTuplesExecute(r ApiListRelationshipTuplesRequest) ([]models.RelationshipTupleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.RelationshipTupleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RelationshipTuplesAPIService.ListRelationshipTuples") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/relationship_tuples" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.detailed != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "detailed", r.detailed, "") + } else { + var defaultValue bool = false + r.detailed = &defaultValue + } + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } else { + var defaultValue int32 = 1 + r.page = &defaultValue + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } else { + var defaultValue int32 = 30 + r.perPage = &defaultValue + } + if r.tenant != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "tenant", r.tenant, "") + } + if r.subject != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "subject", r.subject, "") + } + if r.relation != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "relation", r.relation, "") + } + if r.object != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "object", r.object, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_action_groups.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_action_groups.go new file mode 100644 index 00000000..ec6b20a3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_action_groups.go @@ -0,0 +1,547 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ResourceActionGroupsApiService ResourceActionGroupsApi service +type ResourceActionGroupsApiService service + +type ApiCreateResourceActionGroupRequest struct { + ctx context.Context + ApiService *ResourceActionGroupsApiService + projId string + envId string + resourceId string + resourceActionGroupCreate *models.ResourceActionGroupCreate +} + +func (r ApiCreateResourceActionGroupRequest) ResourceActionGroupCreate(resourceActionGroupCreate models.ResourceActionGroupCreate) ApiCreateResourceActionGroupRequest { + r.resourceActionGroupCreate = &resourceActionGroupCreate + return r +} + +func (r ApiCreateResourceActionGroupRequest) Execute() (*models.ResourceActionGroupRead, *http.Response, error) { + return r.ApiService.CreateResourceActionGroupExecute(r) +} + +/* +CreateResourceActionGroup Create Resource Action Group + +Creates a new action group that can affect the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiCreateResourceActionGroupRequest +*/ +func (a *ResourceActionGroupsApiService) CreateResourceActionGroup(ctx context.Context, projId string, envId string, resourceId string) ApiCreateResourceActionGroupRequest { + return ApiCreateResourceActionGroupRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceActionGroupRead +func (a *ResourceActionGroupsApiService) CreateResourceActionGroupExecute(r ApiCreateResourceActionGroupRequest) (*models.ResourceActionGroupRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceActionGroupRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionGroupsApiService.CreateResourceActionGroup") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/action_groups" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceActionGroupCreate == nil { + return localVarReturnValue, nil, reportError("resourceActionGroupCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceActionGroupCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceActionGroupRequest struct { + ctx context.Context + ApiService *ResourceActionGroupsApiService + projId string + envId string + resourceId string + actionGroupId string +} + +func (r ApiDeleteResourceActionGroupRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceActionGroupExecute(r) +} + +/* +DeleteResourceActionGroup Delete Resource Action Group + +Deletes the action and all its related data. +This includes any permissions granted to perform the action. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param actionGroupId Either the unique id of the action group, or the URL-friendly key of the action group (i.e: the \"slug\"). + @return ApiDeleteResourceActionGroupRequest +*/ +func (a *ResourceActionGroupsApiService) DeleteResourceActionGroup(ctx context.Context, projId string, envId string, resourceId string, actionGroupId string) ApiDeleteResourceActionGroupRequest { + return ApiDeleteResourceActionGroupRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + actionGroupId: actionGroupId, + } +} + +// Execute executes the request +func (a *ResourceActionGroupsApiService) DeleteResourceActionGroupExecute(r ApiDeleteResourceActionGroupRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionGroupsApiService.DeleteResourceActionGroup") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/action_groups/{action_group_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"action_group_id"+"}", url.PathEscape(parameterValueToString(r.actionGroupId, "actionGroupId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceActionGroupRequest struct { + ctx context.Context + ApiService *ResourceActionGroupsApiService + projId string + envId string + resourceId string + actionGroupId string +} + +func (r ApiGetResourceActionGroupRequest) Execute() (*models.ResourceActionGroupRead, *http.Response, error) { + return r.ApiService.GetResourceActionGroupExecute(r) +} + +/* +GetResourceActionGroup Get Resource Action Group + +Gets a single action group defined on the resource, if such action exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param actionGroupId Either the unique id of the action group, or the URL-friendly key of the action group (i.e: the \"slug\"). + @return ApiGetResourceActionGroupRequest +*/ +func (a *ResourceActionGroupsApiService) GetResourceActionGroup(ctx context.Context, projId string, envId string, resourceId string, actionGroupId string) ApiGetResourceActionGroupRequest { + return ApiGetResourceActionGroupRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + actionGroupId: actionGroupId, + } +} + +// Execute executes the request +// +// @return ResourceActionGroupRead +func (a *ResourceActionGroupsApiService) GetResourceActionGroupExecute(r ApiGetResourceActionGroupRequest) (*models.ResourceActionGroupRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceActionGroupRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionGroupsApiService.GetResourceActionGroup") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/action_groups/{action_group_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"action_group_id"+"}", url.PathEscape(parameterValueToString(r.actionGroupId, "actionGroupId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourceActionGroupsRequest struct { + ctx context.Context + ApiService *ResourceActionGroupsApiService + projId string + envId string + resourceId string + page *int32 + perPage *int32 + attributesFilter map[string]interface{} +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourceActionGroupsRequest) Page(page int32) ApiListResourceActionGroupsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourceActionGroupsRequest) PerPage(perPage int32) ApiListResourceActionGroupsRequest { + r.perPage = &perPage + return r +} + +// AttributeFilters on the result of the actions list +func (r ApiListResourceActionGroupsRequest) AttributesFilter(attributesFilter map[string]interface{}) ApiListResourceActionGroupsRequest { + r.attributesFilter = attributesFilter + return r +} + +func (r ApiListResourceActionGroupsRequest) Execute() ([]models.ResourceActionGroupRead, *http.Response, error) { + return r.ApiService.ListResourceActionGroupsExecute(r) +} + +/* +ListResourceActionGroups List Resource Action Groups + +Lists all the action groups defined on the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiListResourceActionGroupsRequest +*/ +func (a *ResourceActionGroupsApiService) ListResourceActionGroups(ctx context.Context, projId string, envId string, resourceId string) ApiListResourceActionGroupsRequest { + return ApiListResourceActionGroupsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return []ResourceActionGroupRead +func (a *ResourceActionGroupsApiService) ListResourceActionGroupsExecute(r ApiListResourceActionGroupsRequest) ([]models.ResourceActionGroupRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceActionGroupRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionGroupsApiService.ListResourceActionGroups") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/action_groups" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_actions.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_actions.go new file mode 100644 index 00000000..dabe1176 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_actions.go @@ -0,0 +1,692 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ResourceActionsApiService ResourceActionsApi service +type ResourceActionsApiService service + +type ApiCreateResourceActionRequest struct { + ctx context.Context + ApiService *ResourceActionsApiService + projId string + envId string + resourceId string + resourceActionCreate *models.ResourceActionCreate +} + +func (r ApiCreateResourceActionRequest) ResourceActionCreate(resourceActionCreate models.ResourceActionCreate) ApiCreateResourceActionRequest { + r.resourceActionCreate = &resourceActionCreate + return r +} + +func (r ApiCreateResourceActionRequest) Execute() (*models.ResourceActionRead, *http.Response, error) { + return r.ApiService.CreateResourceActionExecute(r) +} + +/* +CreateResourceAction Create Resource Action + +Creates a new action that can affect the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiCreateResourceActionRequest +*/ +func (a *ResourceActionsApiService) CreateResourceAction(ctx context.Context, projId string, envId string, resourceId string) ApiCreateResourceActionRequest { + return ApiCreateResourceActionRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceActionRead +func (a *ResourceActionsApiService) CreateResourceActionExecute(r ApiCreateResourceActionRequest) (*models.ResourceActionRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceActionRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionsApiService.CreateResourceAction") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/actions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceActionCreate == nil { + return localVarReturnValue, nil, reportError("resourceActionCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceActionCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceActionRequest struct { + ctx context.Context + ApiService *ResourceActionsApiService + projId string + envId string + resourceId string + actionId string +} + +func (r ApiDeleteResourceActionRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceActionExecute(r) +} + +/* +DeleteResourceAction Delete Resource Action + +Deletes the action and all its related data. +This includes any permissions granted to perform the action. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param actionId Either the unique id of the action, or the URL-friendly key of the action (i.e: the \"slug\"). + @return ApiDeleteResourceActionRequest +*/ +func (a *ResourceActionsApiService) DeleteResourceAction(ctx context.Context, projId string, envId string, resourceId string, actionId string) ApiDeleteResourceActionRequest { + return ApiDeleteResourceActionRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + actionId: actionId, + } +} + +// Execute executes the request +func (a *ResourceActionsApiService) DeleteResourceActionExecute(r ApiDeleteResourceActionRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionsApiService.DeleteResourceAction") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/actions/{action_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"action_id"+"}", url.PathEscape(parameterToString(r.actionId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceActionRequest struct { + ctx context.Context + ApiService *ResourceActionsApiService + projId string + envId string + resourceId string + actionId string +} + +func (r ApiGetResourceActionRequest) Execute() (*models.ResourceActionRead, *http.Response, error) { + return r.ApiService.GetResourceActionExecute(r) +} + +/* +GetResourceAction Get Resource Action + +Gets a single action defined on the resource, if such action exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param actionId Either the unique id of the action, or the URL-friendly key of the action (i.e: the \"slug\"). + @return ApiGetResourceActionRequest +*/ +func (a *ResourceActionsApiService) GetResourceAction(ctx context.Context, projId string, envId string, resourceId string, actionId string) ApiGetResourceActionRequest { + return ApiGetResourceActionRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + actionId: actionId, + } +} + +// Execute executes the request +// +// @return ResourceActionRead +func (a *ResourceActionsApiService) GetResourceActionExecute(r ApiGetResourceActionRequest) (*models.ResourceActionRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceActionRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionsApiService.GetResourceAction") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/actions/{action_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"action_id"+"}", url.PathEscape(parameterToString(r.actionId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourceActionsRequest struct { + ctx context.Context + ApiService *ResourceActionsApiService + projId string + envId string + resourceId string + page *int32 + perPage *int32 + attributesFilter map[string]interface{} +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourceActionsRequest) Page(page int32) ApiListResourceActionsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourceActionsRequest) PerPage(perPage int32) ApiListResourceActionsRequest { + r.perPage = &perPage + return r +} + +// AttributeFilters on the result of the actions list +func (r ApiListResourceActionsRequest) AttributesFilter(attributesFilter map[string]interface{}) ApiListResourceActionsRequest { + r.attributesFilter = attributesFilter + return r +} + +func (r ApiListResourceActionsRequest) Execute() ([]models.ResourceActionRead, *http.Response, error) { + return r.ApiService.ListResourceActionsExecute(r) +} + +/* +ListResourceActions List Resource Actions + +Lists all the actions defined on the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiListResourceActionsRequest +*/ +func (a *ResourceActionsApiService) ListResourceActions(ctx context.Context, projId string, envId string, resourceId string) ApiListResourceActionsRequest { + return ApiListResourceActionsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return []ResourceActionRead +func (a *ResourceActionsApiService) ListResourceActionsExecute(r ApiListResourceActionsRequest) ([]models.ResourceActionRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceActionRead + ) + const attributeFilterPrefix = "attr_" + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionsApiService.ListResourceActions") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/actions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.attributesFilter != nil { + for k, v := range r.attributesFilter { + localVarQueryParams.Add(attributeFilterPrefix+k, parameterToString(v, "")) + } + } + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateResourceActionRequest struct { + ctx context.Context + ApiService *ResourceActionsApiService + projId string + envId string + resourceId string + actionId string + resourceActionUpdate *models.ResourceActionUpdate +} + +func (r ApiUpdateResourceActionRequest) ResourceActionUpdate(resourceActionUpdate models.ResourceActionUpdate) ApiUpdateResourceActionRequest { + r.resourceActionUpdate = &resourceActionUpdate + return r +} + +func (r ApiUpdateResourceActionRequest) Execute() (*models.ResourceActionRead, *http.Response, error) { + return r.ApiService.UpdateResourceActionExecute(r) +} + +/* +UpdateResourceAction Update Resource Action + +Partially updates the action defined on a resource. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param actionId Either the unique id of the action, or the URL-friendly key of the action (i.e: the \"slug\"). + @return ApiUpdateResourceActionRequest +*/ +func (a *ResourceActionsApiService) UpdateResourceAction(ctx context.Context, projId string, envId string, resourceId string, actionId string) ApiUpdateResourceActionRequest { + return ApiUpdateResourceActionRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + actionId: actionId, + } +} + +// Execute executes the request +// +// @return ResourceActionRead +func (a *ResourceActionsApiService) UpdateResourceActionExecute(r ApiUpdateResourceActionRequest) (*models.ResourceActionRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceActionRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceActionsApiService.UpdateResourceAction") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/actions/{action_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"action_id"+"}", url.PathEscape(parameterToString(r.actionId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceActionUpdate == nil { + return localVarReturnValue, nil, reportError("resourceActionUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceActionUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_attributes.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_attributes.go new file mode 100644 index 00000000..116c220b --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_attributes.go @@ -0,0 +1,700 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ResourceAttributesApiService ResourceAttributesApi service +type ResourceAttributesApiService service + +type ApiCreateResourceAttributeRequest struct { + ctx context.Context + ApiService *ResourceAttributesApiService + projId string + envId string + resourceId string + resourceAttributeCreate *models.ResourceAttributeCreate +} + +func (r ApiCreateResourceAttributeRequest) ResourceAttributeCreate(resourceAttributeCreate models.ResourceAttributeCreate) ApiCreateResourceAttributeRequest { + r.resourceAttributeCreate = &resourceAttributeCreate + return r +} + +func (r ApiCreateResourceAttributeRequest) Execute() (*models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.CreateResourceAttributeExecute(r) +} + +/* +CreateResourceAttribute Create Resource Attribute + +Creates a new attribute as part of the resource definition. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiCreateResourceAttributeRequest +*/ +func (a *ResourceAttributesApiService) CreateResourceAttribute(ctx context.Context, projId string, envId string, resourceId string) ApiCreateResourceAttributeRequest { + return ApiCreateResourceAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceAttributeRead +func (a *ResourceAttributesApiService) CreateResourceAttributeExecute(r ApiCreateResourceAttributeRequest) (*models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceAttributesApiService.CreateResourceAttribute") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/attributes" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceAttributeCreate == nil { + return localVarReturnValue, nil, reportError("resourceAttributeCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceAttributeCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceAttributeRequest struct { + ctx context.Context + ApiService *ResourceAttributesApiService + projId string + envId string + resourceId string + attributeId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiDeleteResourceAttributeRequest) Page(page int32) ApiDeleteResourceAttributeRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiDeleteResourceAttributeRequest) PerPage(perPage int32) ApiDeleteResourceAttributeRequest { + r.perPage = &perPage + return r +} + +func (r ApiDeleteResourceAttributeRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceAttributeExecute(r) +} + +/* +DeleteResourceAttribute Delete Resource Attribute + +Deletes the attribute and all its related data. + +Note: If the attribute is used by policies, removing it will cause the +attribute to evaluate as `undefined`. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param attributeId Either the unique id of the attribute, or the URL-friendly key of the attribute (i.e: the \"slug\"). + @return ApiDeleteResourceAttributeRequest +*/ +func (a *ResourceAttributesApiService) DeleteResourceAttribute(ctx context.Context, projId string, envId string, resourceId string, attributeId string) ApiDeleteResourceAttributeRequest { + return ApiDeleteResourceAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + attributeId: attributeId, + } +} + +// Execute executes the request +func (a *ResourceAttributesApiService) DeleteResourceAttributeExecute(r ApiDeleteResourceAttributeRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceAttributesApiService.DeleteResourceAttribute") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/attributes/{attribute_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"attribute_id"+"}", url.PathEscape(parameterToString(r.attributeId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceAttributeRequest struct { + ctx context.Context + ApiService *ResourceAttributesApiService + projId string + envId string + resourceId string + attributeId string +} + +func (r ApiGetResourceAttributeRequest) Execute() (*models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.GetResourceAttributeExecute(r) +} + +/* +GetResourceAttribute Get Resource Attribute + +Gets a single attribute defined on the resource, if such attribute exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param attributeId Either the unique id of the attribute, or the URL-friendly key of the attribute (i.e: the \"slug\"). + @return ApiGetResourceAttributeRequest +*/ +func (a *ResourceAttributesApiService) GetResourceAttribute(ctx context.Context, projId string, envId string, resourceId string, attributeId string) ApiGetResourceAttributeRequest { + return ApiGetResourceAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + attributeId: attributeId, + } +} + +// Execute executes the request +// +// @return ResourceAttributeRead +func (a *ResourceAttributesApiService) GetResourceAttributeExecute(r ApiGetResourceAttributeRequest) (*models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceAttributesApiService.GetResourceAttribute") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/attributes/{attribute_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"attribute_id"+"}", url.PathEscape(parameterToString(r.attributeId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourceAttributesRequest struct { + ctx context.Context + ApiService *ResourceAttributesApiService + projId string + envId string + resourceId string + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourceAttributesRequest) Page(page int32) ApiListResourceAttributesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourceAttributesRequest) PerPage(perPage int32) ApiListResourceAttributesRequest { + r.perPage = &perPage + return r +} + +func (r ApiListResourceAttributesRequest) Execute() ([]models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.ListResourceAttributesExecute(r) +} + +/* +ListResourceAttributes List Resource Attributes + +Lists all the attributes defined on the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiListResourceAttributesRequest +*/ +func (a *ResourceAttributesApiService) ListResourceAttributes(ctx context.Context, projId string, envId string, resourceId string) ApiListResourceAttributesRequest { + return ApiListResourceAttributesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return []ResourceAttributeRead +func (a *ResourceAttributesApiService) ListResourceAttributesExecute(r ApiListResourceAttributesRequest) ([]models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceAttributesApiService.ListResourceAttributes") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/attributes" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateResourceAttributeRequest struct { + ctx context.Context + ApiService *ResourceAttributesApiService + projId string + envId string + resourceId string + attributeId string + resourceAttributeUpdate *models.ResourceAttributeUpdate +} + +func (r ApiUpdateResourceAttributeRequest) ResourceAttributeUpdate(resourceAttributeUpdate models.ResourceAttributeUpdate) ApiUpdateResourceAttributeRequest { + r.resourceAttributeUpdate = &resourceAttributeUpdate + return r +} + +func (r ApiUpdateResourceAttributeRequest) Execute() (*models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.UpdateResourceAttributeExecute(r) +} + +/* +UpdateResourceAttribute Update Resource Attribute + +Partially updates the attribute defined on a resource. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param attributeId Either the unique id of the attribute, or the URL-friendly key of the attribute (i.e: the \"slug\"). + @return ApiUpdateResourceAttributeRequest +*/ +func (a *ResourceAttributesApiService) UpdateResourceAttribute(ctx context.Context, projId string, envId string, resourceId string, attributeId string) ApiUpdateResourceAttributeRequest { + return ApiUpdateResourceAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + attributeId: attributeId, + } +} + +// Execute executes the request +// +// @return ResourceAttributeRead +func (a *ResourceAttributesApiService) UpdateResourceAttributeExecute(r ApiUpdateResourceAttributeRequest) (*models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceAttributesApiService.UpdateResourceAttribute") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/attributes/{attribute_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"attribute_id"+"}", url.PathEscape(parameterToString(r.attributeId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceAttributeUpdate == nil { + return localVarReturnValue, nil, reportError("resourceAttributeUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceAttributeUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_instances.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_instances.go new file mode 100644 index 00000000..35750cb3 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_instances.go @@ -0,0 +1,739 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ResourceInstancesApiService ResourceInstancesAPI service +type ResourceInstancesApiService service + +type ApiCreateResourceInstanceRequest struct { + ctx context.Context + ApiService *ResourceInstancesApiService + projId string + envId string + resourceInstanceCreate *models.ResourceInstanceCreate + permitSession *string +} + +func (r ApiCreateResourceInstanceRequest) ResourceInstanceCreate(resourceInstanceCreate models.ResourceInstanceCreate) ApiCreateResourceInstanceRequest { + r.resourceInstanceCreate = &resourceInstanceCreate + return r +} + +func (r ApiCreateResourceInstanceRequest) PermitSession(permitSession string) ApiCreateResourceInstanceRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiCreateResourceInstanceRequest) Execute() (*models.ResourceInstanceRead, *http.Response, error) { + return r.ApiService.CreateResourceInstanceExecute(r) +} + +/* +CreateResourceInstance Create Resource Instance + +Creates a new instance inside the Permit.io system. + +If the instance is already created: will return 200 instead of 201, +and will return the existing instance object in the response body. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateResourceInstanceRequest +*/ +func (a *ResourceInstancesApiService) CreateResourceInstance(ctx context.Context, projId string, envId string) ApiCreateResourceInstanceRequest { + return ApiCreateResourceInstanceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ResourceInstanceRead +func (a *ResourceInstancesApiService) CreateResourceInstanceExecute(r ApiCreateResourceInstanceRequest) (*models.ResourceInstanceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceInstanceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceInstancesApiService.CreateResourceInstance") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/resource_instances" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceInstanceCreate == nil { + return localVarReturnValue, nil, reportError("resourceInstanceCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceInstanceCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceInstanceRequest struct { + ctx context.Context + ApiService *ResourceInstancesApiService + projId string + envId string + instanceId string + permitSession *string +} + +func (r ApiDeleteResourceInstanceRequest) PermitSession(permitSession string) ApiDeleteResourceInstanceRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiDeleteResourceInstanceRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceInstanceExecute(r) +} + +/* +DeleteResourceInstance Delete Resource Instance + +Deletes the instance and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param instanceId Either the unique id of the resource instance, or the URL-friendly key of the resource instance (i.e: the \"slug\"). + @return ApiDeleteResourceInstanceRequest +*/ +func (a *ResourceInstancesApiService) DeleteResourceInstance(ctx context.Context, projId string, envId string, instanceId string) ApiDeleteResourceInstanceRequest { + return ApiDeleteResourceInstanceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + instanceId: instanceId, + } +} + +// Execute executes the request +func (a *ResourceInstancesApiService) DeleteResourceInstanceExecute(r ApiDeleteResourceInstanceRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceInstancesApiService.DeleteResourceInstance") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/resource_instances/{instance_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"instance_id"+"}", url.PathEscape(parameterValueToString(r.instanceId, "instanceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceInstanceRequest struct { + ctx context.Context + ApiService *ResourceInstancesApiService + projId string + envId string + instanceId string + permitSession *string +} + +func (r ApiGetResourceInstanceRequest) PermitSession(permitSession string) ApiGetResourceInstanceRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiGetResourceInstanceRequest) Execute() (*models.ResourceInstanceRead, *http.Response, error) { + return r.ApiService.GetResourceInstanceExecute(r) +} + +/* +GetResourceInstance Get Resource Instance + +Gets a instance, if such instance exists. Otherwise returns 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param instanceId Either the unique id of the resource instance, or the URL-friendly key of the resource instance (i.e: the \"slug\"). + @return ApiGetResourceInstanceRequest +*/ +func (a *ResourceInstancesApiService) GetResourceInstance(ctx context.Context, projId string, envId string, instanceId string) ApiGetResourceInstanceRequest { + return ApiGetResourceInstanceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + instanceId: instanceId, + } +} + +// Execute executes the request +// +// @return ResourceInstanceRead +func (a *ResourceInstancesApiService) GetResourceInstanceExecute(r ApiGetResourceInstanceRequest) (*models.ResourceInstanceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceInstanceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceInstancesApiService.GetResourceInstance") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/resource_instances/{instance_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"instance_id"+"}", url.PathEscape(parameterValueToString(r.instanceId, "instanceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourceInstancesRequest struct { + ctx context.Context + ApiService *ResourceInstancesApiService + projId string + envId string + tenant *string + resource *string + detailed *bool + page *int32 + perPage *int32 + search *string + permitSession *string +} + +// The tenant key or id to filter by +func (r ApiListResourceInstancesRequest) Tenant(tenant string) ApiListResourceInstancesRequest { + r.tenant = &tenant + return r +} + +// The resource key or id to filter by +func (r ApiListResourceInstancesRequest) Resource(resource string) ApiListResourceInstancesRequest { + r.resource = &resource + return r +} + +// If true, will return the relationships of the resource instance. +func (r ApiListResourceInstancesRequest) Detailed(detailed bool) ApiListResourceInstancesRequest { + r.detailed = &detailed + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourceInstancesRequest) Page(page int32) ApiListResourceInstancesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourceInstancesRequest) PerPage(perPage int32) ApiListResourceInstancesRequest { + r.perPage = &perPage + return r +} + +// Text search for the object name or key +func (r ApiListResourceInstancesRequest) Search(search string) ApiListResourceInstancesRequest { + r.search = &search + return r +} + +func (r ApiListResourceInstancesRequest) PermitSession(permitSession string) ApiListResourceInstancesRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiListResourceInstancesRequest) Execute() ([]models.ResourceInstanceRead, *http.Response, error) { + return r.ApiService.ListResourceInstancesExecute(r) +} + +/* +ListResourceInstances List Resource Instances + +Lists all the resource instances defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListResourceInstancesRequest +*/ +func (a *ResourceInstancesApiService) ListResourceInstances(ctx context.Context, projId string, envId string) ApiListResourceInstancesRequest { + return ApiListResourceInstancesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []ResourceInstanceRead +func (a *ResourceInstancesApiService) ListResourceInstancesExecute(r ApiListResourceInstancesRequest) ([]models.ResourceInstanceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceInstanceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceInstancesApiService.ListResourceInstances") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/resource_instances" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.tenant != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "tenant", r.tenant, "") + } + if r.resource != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "resource", r.resource, "") + } + if r.detailed != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "detailed", r.detailed, "") + } else { + var defaultValue bool = false + r.detailed = &defaultValue + } + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } else { + var defaultValue int32 = 1 + r.page = &defaultValue + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } else { + var defaultValue int32 = 30 + r.perPage = &defaultValue + } + if r.search != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "search", r.search, "") + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateResourceInstanceRequest struct { + ctx context.Context + ApiService *ResourceInstancesApiService + projId string + envId string + instanceId string + resourceInstanceUpdate *models.ResourceInstanceUpdate + permitSession *string +} + +func (r ApiUpdateResourceInstanceRequest) ResourceInstanceUpdate(resourceInstanceUpdate models.ResourceInstanceUpdate) ApiUpdateResourceInstanceRequest { + r.resourceInstanceUpdate = &resourceInstanceUpdate + return r +} + +func (r ApiUpdateResourceInstanceRequest) PermitSession(permitSession string) ApiUpdateResourceInstanceRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiUpdateResourceInstanceRequest) Execute() (*models.ResourceInstanceRead, *http.Response, error) { + return r.ApiService.UpdateResourceInstanceExecute(r) +} + +/* +UpdateResourceInstance Update Resource Instance + +Partially updates the instance definition. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param instanceId Either the unique id of the resource instance, or the URL-friendly key of the resource instance (i.e: the \"slug\"). + @return ApiUpdateResourceInstanceRequest +*/ +func (a *ResourceInstancesApiService) UpdateResourceInstance(ctx context.Context, projId string, envId string, instanceId string) ApiUpdateResourceInstanceRequest { + return ApiUpdateResourceInstanceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + instanceId: instanceId, + } +} + +// Execute executes the request +// +// @return ResourceInstanceRead +func (a *ResourceInstancesApiService) UpdateResourceInstanceExecute(r ApiUpdateResourceInstanceRequest) (*models.ResourceInstanceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceInstanceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceInstancesApiService.UpdateResourceInstance") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/resource_instances/{instance_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"instance_id"+"}", url.PathEscape(parameterValueToString(r.instanceId, "instanceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceInstanceUpdate == nil { + return localVarReturnValue, nil, reportError("resourceInstanceUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceInstanceUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_relations.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_relations.go new file mode 100644 index 00000000..c154698f --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_relations.go @@ -0,0 +1,569 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ResourceRelationsAPIService ResourceRelationsAPI service +type ResourceRelationsAPIService service + +type ApiCreateResourceRelationRequest struct { + ctx context.Context + ApiService *ResourceRelationsAPIService + projId string + envId string + resourceId string + relationCreate *models.RelationCreate + permitSession *string +} + +func (r ApiCreateResourceRelationRequest) RelationCreate(relationCreate models.RelationCreate) ApiCreateResourceRelationRequest { + r.relationCreate = &relationCreate + return r +} + +func (r ApiCreateResourceRelationRequest) PermitSession(permitSession string) ApiCreateResourceRelationRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiCreateResourceRelationRequest) Execute() (*models.RelationRead, *http.Response, error) { + return r.ApiService.CreateResourceRelationExecute(r) +} + +/* +CreateResourceRelation Create Resource Relation + +Creates a resource relation to another resource + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiCreateResourceRelationRequest +*/ +func (a *ResourceRelationsAPIService) CreateResourceRelation(ctx context.Context, projId string, envId string, resourceId string) ApiCreateResourceRelationRequest { + return ApiCreateResourceRelationRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return RelationRead +func (a *ResourceRelationsAPIService) CreateResourceRelationExecute(r ApiCreateResourceRelationRequest) (*models.RelationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RelationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRelationsAPIService.CreateResourceRelation") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/relations" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.relationCreate == nil { + return localVarReturnValue, nil, reportError("relationCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.relationCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceRelationRequest struct { + ctx context.Context + ApiService *ResourceRelationsAPIService + projId string + envId string + resourceId string + relationId string + permitSession *string +} + +func (r ApiDeleteResourceRelationRequest) PermitSession(permitSession string) ApiDeleteResourceRelationRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiDeleteResourceRelationRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceRelationExecute(r) +} + +/* +DeleteResourceRelation Delete Resource Relation + +Deletes a resource relation + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param relationId Either the unique id of the relation, or the URL-friendly key of the relation (i.e: the \"slug\"). + @return ApiDeleteResourceRelationRequest +*/ +func (a *ResourceRelationsAPIService) DeleteResourceRelation(ctx context.Context, projId string, envId string, resourceId string, relationId string) ApiDeleteResourceRelationRequest { + return ApiDeleteResourceRelationRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + relationId: relationId, + } +} + +// Execute executes the request +func (a *ResourceRelationsAPIService) DeleteResourceRelationExecute(r ApiDeleteResourceRelationRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRelationsAPIService.DeleteResourceRelation") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/relations/{relation_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"relation_id"+"}", url.PathEscape(parameterValueToString(r.relationId, "relationId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceRelationRequest struct { + ctx context.Context + ApiService *ResourceRelationsAPIService + projId string + envId string + resourceId string + relationId string + permitSession *string +} + +func (r ApiGetResourceRelationRequest) PermitSession(permitSession string) ApiGetResourceRelationRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiGetResourceRelationRequest) Execute() (*models.RelationRead, *http.Response, error) { + return r.ApiService.GetResourceRelationExecute(r) +} + +/* +GetResourceRelation Get Resource Relation + +Get a resource relation + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param relationId Either the unique id of the relation, or the URL-friendly key of the relation (i.e: the \"slug\"). + @return ApiGetResourceRelationRequest +*/ +func (a *ResourceRelationsAPIService) GetResourceRelation(ctx context.Context, projId string, envId string, resourceId string, relationId string) ApiGetResourceRelationRequest { + return ApiGetResourceRelationRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + relationId: relationId, + } +} + +// Execute executes the request +// +// @return RelationRead +func (a *ResourceRelationsAPIService) GetResourceRelationExecute(r ApiGetResourceRelationRequest) (*models.RelationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RelationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRelationsAPIService.GetResourceRelation") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/relations/{relation_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"relation_id"+"}", url.PathEscape(parameterValueToString(r.relationId, "relationId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourceRelationsRequest struct { + ctx context.Context + ApiService *ResourceRelationsAPIService + projId string + envId string + resourceId string + page *int32 + perPage *int32 + permitSession *string +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourceRelationsRequest) Page(page int32) ApiListResourceRelationsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourceRelationsRequest) PerPage(perPage int32) ApiListResourceRelationsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListResourceRelationsRequest) PermitSession(permitSession string) ApiListResourceRelationsRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiListResourceRelationsRequest) Execute() (*models.PaginatedResultRelationRead, *http.Response, error) { + return r.ApiService.ListResourceRelationsExecute(r) +} + +/* +ListResourceRelations List Resource Relations + +List relations on a given resource + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiListResourceRelationsRequest +*/ +func (a *ResourceRelationsAPIService) ListResourceRelations(ctx context.Context, projId string, envId string, resourceId string) ApiListResourceRelationsRequest { + return ApiListResourceRelationsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return PaginatedResultRelationRead +func (a *ResourceRelationsAPIService) ListResourceRelationsExecute(r ApiListResourceRelationsRequest) (*models.PaginatedResultRelationRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultRelationRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRelationsAPIService.ListResourceRelations") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/relations" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } else { + var defaultValue int32 = 1 + r.page = &defaultValue + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } else { + var defaultValue int32 = 30 + r.perPage = &defaultValue + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_roles.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_roles.go new file mode 100644 index 00000000..b230e5c7 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resource_roles.go @@ -0,0 +1,1555 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// ResourceRolesApiService ResourceRolesAPI service +type ResourceRolesApiService service + +type ApiAddParentResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + parentRoleId string + permitSession *string +} + +func (r ApiAddParentResourceRoleRequest) PermitSession(permitSession string) ApiAddParentResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiAddParentResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.AddParentResourceRoleExecute(r) +} + +/* +AddParentResourceRole Add Parent Role + +This endpoint is part of the role hierarchy feature. + +Makes role with id `role_id` extend the role with id `parent_role_id`. +In other words, `role_id` will automatically be assigned any permissions +that are granted to `parent_role_id`. + +We can say the `role_id` **extends** `parent_role_id` or **inherits** from `parent_role_id`. + +If `role_id` is already an ancestor of `parent_role_id`, +the request will fail with HTTP 400 to prevent a cycle in the role hierarchy. + +Both roles must be defined on the same resource, identified by id `resource_id`. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @param parentRoleId Either the unique id of the parent role, or the URL-friendly key of the parent role (i.e: the \"slug\"). + @return ApiAddParentResourceRoleRequest +*/ +func (a *ResourceRolesApiService) AddParentResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string, parentRoleId string) ApiAddParentResourceRoleRequest { + return ApiAddParentResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + parentRoleId: parentRoleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) AddParentResourceRoleExecute(r ApiAddParentResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.AddParentResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/parents/{parent_role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"parent_role_id"+"}", url.PathEscape(parameterValueToString(r.parentRoleId, "parentRoleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiAssignPermissionsToResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + addRolePermissions *models.AddRolePermissions + permitSession *string +} + +func (r ApiAssignPermissionsToResourceRoleRequest) AddRolePermissions(addRolePermissions models.AddRolePermissions) ApiAssignPermissionsToResourceRoleRequest { + r.addRolePermissions = &addRolePermissions + return r +} + +func (r ApiAssignPermissionsToResourceRoleRequest) PermitSession(permitSession string) ApiAssignPermissionsToResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiAssignPermissionsToResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.AssignPermissionsToResourceRoleExecute(r) +} + +/* +AssignPermissionsToResourceRole Assign Permissions to Role + +Assign permissions to role. + +If some of the permissions specified are already assigned, will skip them. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiAssignPermissionsToResourceRoleRequest +*/ +func (a *ResourceRolesApiService) AssignPermissionsToResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiAssignPermissionsToResourceRoleRequest { + return ApiAssignPermissionsToResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) AssignPermissionsToResourceRoleExecute(r ApiAssignPermissionsToResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.AssignPermissionsToResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/permissions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.addRolePermissions == nil { + return localVarReturnValue, nil, reportError("addRolePermissions is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.addRolePermissions + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiCreateResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + resourceRoleCreate *models.ResourceRoleCreate + permitSession *string +} + +func (r ApiCreateResourceRoleRequest) ResourceRoleCreate(resourceRoleCreate models.ResourceRoleCreate) ApiCreateResourceRoleRequest { + r.resourceRoleCreate = &resourceRoleCreate + return r +} + +func (r ApiCreateResourceRoleRequest) PermitSession(permitSession string) ApiCreateResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiCreateResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.CreateResourceRoleExecute(r) +} + +/* +CreateResourceRole Create Resource Role + +Creates a new role associated with the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiCreateResourceRoleRequest +*/ +func (a *ResourceRolesApiService) CreateResourceRole(ctx context.Context, projId string, envId string, resourceId string) ApiCreateResourceRoleRequest { + return ApiCreateResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) CreateResourceRoleExecute(r ApiCreateResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.CreateResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceRoleCreate == nil { + return localVarReturnValue, nil, reportError("resourceRoleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceRoleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + permitSession *string +} + +func (r ApiDeleteResourceRoleRequest) PermitSession(permitSession string) ApiDeleteResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiDeleteResourceRoleRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceRoleExecute(r) +} + +/* +DeleteResourceRole Delete Resource Role + +Deletes the role and all its related data. +This includes any permissions granted to said role. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiDeleteResourceRoleRequest +*/ +func (a *ResourceRolesApiService) DeleteResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiDeleteResourceRoleRequest { + return ApiDeleteResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +func (a *ResourceRolesApiService) DeleteResourceRoleExecute(r ApiDeleteResourceRoleRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.DeleteResourceRole") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + permitSession *string +} + +func (r ApiGetResourceRoleRequest) PermitSession(permitSession string) ApiGetResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiGetResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.GetResourceRoleExecute(r) +} + +/* +GetResourceRole Get Resource Role + +Gets a single role defined on the resource, if such role exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiGetResourceRoleRequest +*/ +func (a *ResourceRolesApiService) GetResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiGetResourceRoleRequest { + return ApiGetResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) GetResourceRoleExecute(r ApiGetResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.GetResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetResourceRoleAncestorsRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + permitSession *string +} + +func (r ApiGetResourceRoleAncestorsRequest) PermitSession(permitSession string) ApiGetResourceRoleAncestorsRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiGetResourceRoleAncestorsRequest) Execute() (*models.ResourceRoleList, *http.Response, error) { + return r.ApiService.GetResourceRoleAncestorsExecute(r) +} + +/* +GetResourceRoleAncestors Get Resource Role Ancestors + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiGetResourceRoleAncestorsRequest +*/ +func (a *ResourceRolesApiService) GetResourceRoleAncestors(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiGetResourceRoleAncestorsRequest { + return ApiGetResourceRoleAncestorsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleList +func (a *ResourceRolesApiService) GetResourceRoleAncestorsExecute(r ApiGetResourceRoleAncestorsRequest) (*models.ResourceRoleList, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleList + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.GetResourceRoleAncestors") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/ancestors" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiGetResourceRoleDescendantsRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + permitSession *string +} + +func (r ApiGetResourceRoleDescendantsRequest) PermitSession(permitSession string) ApiGetResourceRoleDescendantsRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiGetResourceRoleDescendantsRequest) Execute() (*models.ResourceRoleList, *http.Response, error) { + return r.ApiService.GetResourceRoleDescendantsExecute(r) +} + +/* +GetResourceRoleDescendants Get Resource Role Descendants + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiGetResourceRoleDescendantsRequest +*/ +func (a *ResourceRolesApiService) GetResourceRoleDescendants(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiGetResourceRoleDescendantsRequest { + return ApiGetResourceRoleDescendantsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleList +func (a *ResourceRolesApiService) GetResourceRoleDescendantsExecute(r ApiGetResourceRoleDescendantsRequest) (*models.ResourceRoleList, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleList + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.GetResourceRoleDescendants") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/descendants" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourceRolesRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + page *int32 + perPage *int32 + permitSession *string +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourceRolesRequest) Page(page int32) ApiListResourceRolesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourceRolesRequest) PerPage(perPage int32) ApiListResourceRolesRequest { + r.perPage = &perPage + return r +} + +func (r ApiListResourceRolesRequest) PermitSession(permitSession string) ApiListResourceRolesRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiListResourceRolesRequest) Execute() ([]models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.ListResourceRolesExecute(r) +} + +/* +ListResourceRoles List Resource Roles + +Lists all the roles defined on the resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiListResourceRolesRequest +*/ +func (a *ResourceRolesApiService) ListResourceRoles(ctx context.Context, projId string, envId string, resourceId string) ApiListResourceRolesRequest { + return ApiListResourceRolesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return []ResourceRoleRead +func (a *ResourceRolesApiService) ListResourceRolesExecute(r ApiListResourceRolesRequest) ([]models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.ListResourceRoles") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } else { + var defaultValue int32 = 1 + r.page = &defaultValue + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } else { + var defaultValue int32 = 30 + r.perPage = &defaultValue + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiRemoveParentResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + parentRoleId string + permitSession *string +} + +func (r ApiRemoveParentResourceRoleRequest) PermitSession(permitSession string) ApiRemoveParentResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiRemoveParentResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.RemoveParentResourceRoleExecute(r) +} + +/* +RemoveParentResourceRole Remove Parent Role + +This endpoint is part of the role hierarchy feature. + +Removes `parent_role_id` from the list of parent roles of role with id `role_id`. +In other words, `role_id` will no longer be automatically assigned permissions +that are granted to `parent_role_id`. + +We can say the `role_id` **not longer extends** `parent_role_id` or **no longer inherits** from `parent_role_id`. + +Both roles must be defined on the same resource, identified by id `resource_id`. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @param parentRoleId Either the unique id of the parent role, or the URL-friendly key of the parent role (i.e: the \"slug\"). + @return ApiRemoveParentResourceRoleRequest +*/ +func (a *ResourceRolesApiService) RemoveParentResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string, parentRoleId string) ApiRemoveParentResourceRoleRequest { + return ApiRemoveParentResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + parentRoleId: parentRoleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) RemoveParentResourceRoleExecute(r ApiRemoveParentResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.RemoveParentResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/parents/{parent_role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"parent_role_id"+"}", url.PathEscape(parameterValueToString(r.parentRoleId, "parentRoleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiRemovePermissionsFromResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + removeRolePermissions *models.RemoveRolePermissions + permitSession *string +} + +func (r ApiRemovePermissionsFromResourceRoleRequest) RemoveRolePermissions(removeRolePermissions models.RemoveRolePermissions) ApiRemovePermissionsFromResourceRoleRequest { + r.removeRolePermissions = &removeRolePermissions + return r +} + +func (r ApiRemovePermissionsFromResourceRoleRequest) PermitSession(permitSession string) ApiRemovePermissionsFromResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiRemovePermissionsFromResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.RemovePermissionsFromResourceRoleExecute(r) +} + +/* +RemovePermissionsFromResourceRole Remove Permissions from Role + +Remove permissions from role. + +If some of the permissions specified are already unassigned, will skip them. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiRemovePermissionsFromResourceRoleRequest +*/ +func (a *ResourceRolesApiService) RemovePermissionsFromResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiRemovePermissionsFromResourceRoleRequest { + return ApiRemovePermissionsFromResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) RemovePermissionsFromResourceRoleExecute(r ApiRemovePermissionsFromResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.RemovePermissionsFromResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}/permissions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.removeRolePermissions == nil { + return localVarReturnValue, nil, reportError("removeRolePermissions is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.removeRolePermissions + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateResourceRoleRequest struct { + ctx context.Context + ApiService *ResourceRolesApiService + projId string + envId string + resourceId string + roleId string + resourceRoleUpdate *models.ResourceRoleUpdate + permitSession *string +} + +func (r ApiUpdateResourceRoleRequest) ResourceRoleUpdate(resourceRoleUpdate models.ResourceRoleUpdate) ApiUpdateResourceRoleRequest { + r.resourceRoleUpdate = &resourceRoleUpdate + return r +} + +func (r ApiUpdateResourceRoleRequest) PermitSession(permitSession string) ApiUpdateResourceRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiUpdateResourceRoleRequest) Execute() (*models.ResourceRoleRead, *http.Response, error) { + return r.ApiService.UpdateResourceRoleExecute(r) +} + +/* +UpdateResourceRole Update Resource Role + +Partially updates the role defined on a resource. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiUpdateResourceRoleRequest +*/ +func (a *ResourceRolesApiService) UpdateResourceRole(ctx context.Context, projId string, envId string, resourceId string, roleId string) ApiUpdateResourceRoleRequest { + return ApiUpdateResourceRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return ResourceRoleRead +func (a *ResourceRolesApiService) UpdateResourceRoleExecute(r ApiUpdateResourceRoleRequest) (*models.ResourceRoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceRolesApiService.UpdateResourceRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterValueToString(r.resourceId, "resourceId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterValueToString(r.roleId, "roleId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceRoleUpdate == nil { + return localVarReturnValue, nil, reportError("resourceRoleUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceRoleUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resources.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resources.go new file mode 100644 index 00000000..fc3b516d --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_resources.go @@ -0,0 +1,816 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// ResourcesApiService ResourcesApi service +type ResourcesApiService service + +type ApiCreateResourceRequest struct { + ctx context.Context + ApiService *ResourcesApiService + projId string + envId string + resourceCreate *models.ResourceCreate +} + +func (r ApiCreateResourceRequest) ResourceCreate(resourceCreate models.ResourceCreate) ApiCreateResourceRequest { + r.resourceCreate = &resourceCreate + return r +} + +func (r ApiCreateResourceRequest) Execute() (*models.ResourceRead, *http.Response, error) { + return r.ApiService.CreateResourceExecute(r) +} + +/* +CreateResource Create Resource + +Creates a new resource (a type of object you may protect with permissions). + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateResourceRequest +*/ +func (a *ResourcesApiService) CreateResource(ctx context.Context, projId string, envId string) ApiCreateResourceRequest { + return ApiCreateResourceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ResourceRead +func (a *ResourcesApiService) CreateResourceExecute(r ApiCreateResourceRequest) (*models.ResourceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourcesApiService.CreateResource") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceCreate == nil { + return localVarReturnValue, nil, reportError("resourceCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteResourceRequest struct { + ctx context.Context + ApiService *ResourcesApiService + projId string + envId string + resourceId string +} + +func (r ApiDeleteResourceRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteResourceExecute(r) +} + +/* +DeleteResource Delete Resource + +Deletes the resource and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiDeleteResourceRequest +*/ +func (a *ResourcesApiService) DeleteResource(ctx context.Context, projId string, envId string, resourceId string) ApiDeleteResourceRequest { + return ApiDeleteResourceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +func (a *ResourcesApiService) DeleteResourceExecute(r ApiDeleteResourceRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourcesApiService.DeleteResource") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetResourceRequest struct { + ctx context.Context + ApiService *ResourcesApiService + projId string + envId string + resourceId string +} + +func (r ApiGetResourceRequest) Execute() (*models.ResourceRead, *http.Response, error) { + return r.ApiService.GetResourceExecute(r) +} + +/* +GetResource Get Resource + +Gets a single resource, if such resource exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiGetResourceRequest +*/ +func (a *ResourcesApiService) GetResource(ctx context.Context, projId string, envId string, resourceId string) ApiGetResourceRequest { + return ApiGetResourceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceRead +func (a *ResourcesApiService) GetResourceExecute(r ApiGetResourceRequest) (*models.ResourceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourcesApiService.GetResource") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListResourcesRequest struct { + ctx context.Context + ApiService *ResourcesApiService + projId string + envId string + search *string + includeBuiltIn *bool + page *int32 + perPage *int32 +} + +// Text search for the object name or key +func (r ApiListResourcesRequest) Search(search string) ApiListResourcesRequest { + r.search = &search + return r +} + +// Whether to include or exclude built-in resources, default is False +func (r ApiListResourcesRequest) IncludeBuiltIn(includeBuiltIn bool) ApiListResourcesRequest { + r.includeBuiltIn = &includeBuiltIn + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListResourcesRequest) Page(page int32) ApiListResourcesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListResourcesRequest) PerPage(perPage int32) ApiListResourcesRequest { + r.perPage = &perPage + return r +} + +func (r ApiListResourcesRequest) Execute() ([]models.ResourceRead, *http.Response, error) { + return r.ApiService.ListResourcesExecute(r) +} + +/* +ListResources List Resources + +Lists all the resources defined in your schema. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListResourcesRequest +*/ +func (a *ResourcesApiService) ListResources(ctx context.Context, projId string, envId string) ApiListResourcesRequest { + return ApiListResourcesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []ResourceRead +func (a *ResourcesApiService) ListResourcesExecute(r ApiListResourcesRequest) ([]models.ResourceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourcesApiService.ListResources") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.search != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "search", r.search, "") + } + if r.includeBuiltIn != nil { + localVarQueryParams.Add("include_built_in", parameterToString(*r.includeBuiltIn, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiReplaceResourceRequest struct { + ctx context.Context + ApiService *ResourcesApiService + projId string + envId string + resourceId string + resourceReplace *models.ResourceReplace +} + +func (r ApiReplaceResourceRequest) ResourceReplace(resourceReplace models.ResourceReplace) ApiReplaceResourceRequest { + r.resourceReplace = &resourceReplace + return r +} + +func (r ApiReplaceResourceRequest) Execute() (*models.ResourceRead, *http.Response, error) { + return r.ApiService.ReplaceResourceExecute(r) +} + +/* +ReplaceResource Replace Resource + +Completely replaces the resource definition. + +- If the resource key is changed, all role and permissions assignments for the the resource will be revoked. +- If the resource key is unchanged, but some actions are removed or renamed from the resource definition, +role and permissions assignments for these actions will be revoked. + +TODO: we need to decide if we are auto-revoking, or if we are rejecting the PUT completely while there are permissions that can be affected. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiReplaceResourceRequest +*/ +func (a *ResourcesApiService) ReplaceResource(ctx context.Context, projId string, envId string, resourceId string) ApiReplaceResourceRequest { + return ApiReplaceResourceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceRead +func (a *ResourcesApiService) ReplaceResourceExecute(r ApiReplaceResourceRequest) (*models.ResourceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourcesApiService.ReplaceResource") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceReplace == nil { + return localVarReturnValue, nil, reportError("resourceReplace is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceReplace + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateResourceRequest struct { + ctx context.Context + ApiService *ResourcesApiService + projId string + envId string + resourceId string + resourceUpdate *models.ResourceUpdate +} + +func (r ApiUpdateResourceRequest) ResourceUpdate(resourceUpdate models.ResourceUpdate) ApiUpdateResourceRequest { + r.resourceUpdate = &resourceUpdate + return r +} + +func (r ApiUpdateResourceRequest) Execute() (*models.ResourceRead, *http.Response, error) { + return r.ApiService.UpdateResourceExecute(r) +} + +/* +UpdateResource Update Resource + +Partially updates the resource definition. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param resourceId Either the unique id of the resource, or the URL-friendly key of the resource (i.e: the \"slug\"). + @return ApiUpdateResourceRequest +*/ +func (a *ResourcesApiService) UpdateResource(ctx context.Context, projId string, envId string, resourceId string) ApiUpdateResourceRequest { + return ApiUpdateResourceRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + resourceId: resourceId, + } +} + +// Execute executes the request +// +// @return ResourceRead +func (a *ResourcesApiService) UpdateResourceExecute(r ApiUpdateResourceRequest) (*models.ResourceRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourcesApiService.UpdateResource") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/resources/{resource_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"resource_id"+"}", url.PathEscape(parameterToString(r.resourceId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceUpdate == nil { + return localVarReturnValue, nil, reportError("resourceUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_role_assignments.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_role_assignments.go new file mode 100644 index 00000000..4404c7ad --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_role_assignments.go @@ -0,0 +1,771 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io" + "net/http" + "net/url" + "strings" +) + +// RoleAssignmentsApiService RoleAssignmentsAPI service +type RoleAssignmentsApiService service + +type ApiAssignRoleRequest struct { + ctx context.Context + ApiService *RoleAssignmentsApiService + projId string + envId string + roleAssignmentCreate *models.RoleAssignmentCreate + permitSession *string +} + +func (r ApiAssignRoleRequest) RoleAssignmentCreate(roleAssignmentCreate models.RoleAssignmentCreate) ApiAssignRoleRequest { + r.roleAssignmentCreate = &roleAssignmentCreate + return r +} + +func (r ApiAssignRoleRequest) PermitSession(permitSession string) ApiAssignRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiAssignRoleRequest) Execute() (*models.RoleAssignmentRead, *http.Response, error) { + return r.ApiService.AssignRoleExecute(r) +} + +/* +AssignRole Assign Role + +Assigns a role to a user within a tenant. + +The tenant defines the scope of the assignment. In other words, the role is effective only within the tenant. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiAssignRoleRequest +*/ +func (a *RoleAssignmentsApiService) AssignRole(ctx context.Context, projId string, envId string) ApiAssignRoleRequest { + return ApiAssignRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return RoleAssignmentRead +func (a *RoleAssignmentsApiService) AssignRoleExecute(r ApiAssignRoleRequest) (*models.RoleAssignmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleAssignmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RoleAssignmentsApiService.AssignRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/role_assignments" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.roleAssignmentCreate == nil { + return localVarReturnValue, nil, reportError("roleAssignmentCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.roleAssignmentCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiBulkAssignRoleRequest struct { + ctx context.Context + ApiService *RoleAssignmentsApiService + projId string + envId string + roleAssignmentCreate *[]models.RoleAssignmentCreate + permitSession *string +} + +func (r ApiBulkAssignRoleRequest) RoleAssignmentCreate(roleAssignmentCreate []models.RoleAssignmentCreate) ApiBulkAssignRoleRequest { + r.roleAssignmentCreate = &roleAssignmentCreate + return r +} + +func (r ApiBulkAssignRoleRequest) PermitSession(permitSession string) ApiBulkAssignRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiBulkAssignRoleRequest) Execute() (*models.BulkRoleAssignmentReport, *http.Response, error) { + return r.ApiService.BulkAssignRoleExecute(r) +} + +/* +BulkAssignRole Bulk Assign Role + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiBulkAssignRoleRequest +*/ +func (a *RoleAssignmentsApiService) BulkAssignRole(ctx context.Context, projId string, envId string) ApiBulkAssignRoleRequest { + return ApiBulkAssignRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return BulkRoleAssignmentReport +func (a *RoleAssignmentsApiService) BulkAssignRoleExecute(r ApiBulkAssignRoleRequest) (*models.BulkRoleAssignmentReport, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.BulkRoleAssignmentReport + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RoleAssignmentsApiService.BulkAssignRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/role_assignments/bulk" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.roleAssignmentCreate == nil { + return localVarReturnValue, nil, reportError("roleAssignmentCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.roleAssignmentCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiBulkUnassignRoleRequest struct { + ctx context.Context + ApiService *RoleAssignmentsApiService + projId string + envId string + roleAssignmentRemove *[]models.RoleAssignmentRemove + permitSession *string +} + +func (r ApiBulkUnassignRoleRequest) RoleAssignmentRemove(roleAssignmentRemove []models.RoleAssignmentRemove) ApiBulkUnassignRoleRequest { + r.roleAssignmentRemove = &roleAssignmentRemove + return r +} + +func (r ApiBulkUnassignRoleRequest) PermitSession(permitSession string) ApiBulkUnassignRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiBulkUnassignRoleRequest) Execute() (*models.BulkRoleUnAssignmentReport, *http.Response, error) { + return r.ApiService.BulkUnassignRoleExecute(r) +} + +/* +BulkUnassignRole Bulk Unassign Role + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiBulkUnassignRoleRequest +*/ +func (a *RoleAssignmentsApiService) BulkUnassignRole(ctx context.Context, projId string, envId string) ApiBulkUnassignRoleRequest { + return ApiBulkUnassignRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return BulkRoleUnAssignmentReport +func (a *RoleAssignmentsApiService) BulkUnassignRoleExecute(r ApiBulkUnassignRoleRequest) (*models.BulkRoleUnAssignmentReport, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.BulkRoleUnAssignmentReport + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RoleAssignmentsApiService.BulkUnassignRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/role_assignments/bulk" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.roleAssignmentRemove == nil { + return localVarReturnValue, nil, reportError("roleAssignmentRemove is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.roleAssignmentRemove + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListRoleAssignmentsRequest struct { + ctx context.Context + ApiService *RoleAssignmentsApiService + projId string + envId string + user *string + role *string + tenant *string + resource *string + resourceInstance *string + detailed *bool + page *int32 + perPage *int32 + permitSession *string +} + +// optional user filter, will only return role assignments granted to this user. +func (r ApiListRoleAssignmentsRequest) User(user string) ApiListRoleAssignmentsRequest { + r.user = &user + return r +} + +// optional role filter, will only return role assignments granting this role. +func (r ApiListRoleAssignmentsRequest) Role(role string) ApiListRoleAssignmentsRequest { + r.role = &role + return r +} + +// optional tenant filter, will only return role assignments granted in that tenant. +func (r ApiListRoleAssignmentsRequest) Tenant(tenant string) ApiListRoleAssignmentsRequest { + r.tenant = &tenant + return r +} + +// optional resource **type** filter, will only return role assignments granted on that resource type. +func (r ApiListRoleAssignmentsRequest) Resource(resource string) ApiListRoleAssignmentsRequest { + r.resource = &resource + return r +} + +// optional resource instance filter, will only return role assignments granted on that resource instance. +func (r ApiListRoleAssignmentsRequest) ResourceInstance(resourceInstance string) ApiListRoleAssignmentsRequest { + r.resourceInstance = &resourceInstance + return r +} + +// Whether to return full details about the user, tenant and role +func (r ApiListRoleAssignmentsRequest) Detailed(detailed bool) ApiListRoleAssignmentsRequest { + r.detailed = &detailed + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListRoleAssignmentsRequest) Page(page int32) ApiListRoleAssignmentsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListRoleAssignmentsRequest) PerPage(perPage int32) ApiListRoleAssignmentsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListRoleAssignmentsRequest) PermitSession(permitSession string) ApiListRoleAssignmentsRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiListRoleAssignmentsRequest) Execute() (*models.ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet, *http.Response, error) { + return r.ApiService.ListRoleAssignmentsExecute(r) +} + +/* +ListRoleAssignments List Role Assignments + +Lists the role assignments defined within an environment. + +- If the `user` filter is present, will only return the role assignments of that user. +- If the `tenant` filter is present, will only return the role assignments in that tenant. +- If the `role` filter is present, will only return role assignments that are granting that role. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListRoleAssignmentsRequest +*/ +func (a *RoleAssignmentsApiService) ListRoleAssignments(ctx context.Context, projId string, envId string) ApiListRoleAssignmentsRequest { + return ApiListRoleAssignmentsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet +func (a *RoleAssignmentsApiService) ListRoleAssignmentsExecute(r ApiListRoleAssignmentsRequest) (*models.ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResponseListRoleAssignmentsV2FactsProjIdEnvIdRoleAssignmentsGet + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RoleAssignmentsApiService.ListRoleAssignments") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/role_assignments" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.user != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "user", r.user, "") + } + if r.role != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "role", r.role, "") + } + if r.tenant != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "tenant", r.tenant, "") + } + if r.resource != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "resource", r.resource, "") + } + if r.resourceInstance != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "resource_instance", r.resourceInstance, "") + } + if r.detailed != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "detailed", r.detailed, "") + } else { + var defaultValue bool = false + r.detailed = &defaultValue + } + if r.page != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "page", r.page, "") + } else { + var defaultValue int32 = 1 + r.page = &defaultValue + } + if r.perPage != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "per_page", r.perPage, "") + } else { + var defaultValue int32 = 30 + r.perPage = &defaultValue + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUnassignRoleRequest struct { + ctx context.Context + ApiService *RoleAssignmentsApiService + projId string + envId string + roleAssignmentRemove *models.RoleAssignmentRemove + permitSession *string +} + +func (r ApiUnassignRoleRequest) RoleAssignmentRemove(roleAssignmentRemove models.RoleAssignmentRemove) ApiUnassignRoleRequest { + r.roleAssignmentRemove = &roleAssignmentRemove + return r +} + +func (r ApiUnassignRoleRequest) PermitSession(permitSession string) ApiUnassignRoleRequest { + r.permitSession = &permitSession + return r +} + +func (r ApiUnassignRoleRequest) Execute() (*http.Response, error) { + return r.ApiService.UnassignRoleExecute(r) +} + +/* +UnassignRole Unassign Role + +Unassigns a user role within a tenant. + +The tenant defines the scope of the assignment. In other words, the role is effective only within the tenant. + +If the role is not actually assigned, will return 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiUnassignRoleRequest +*/ +func (a *RoleAssignmentsApiService) UnassignRole(ctx context.Context, projId string, envId string) ApiUnassignRoleRequest { + return ApiUnassignRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +func (a *RoleAssignmentsApiService) UnassignRoleExecute(r ApiUnassignRoleRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RoleAssignmentsApiService.UnassignRole") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/role_assignments" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterValueToString(r.projId, "projId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterValueToString(r.envId, "envId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.roleAssignmentRemove == nil { + return nil, reportError("roleAssignmentRemove is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.roleAssignmentRemove + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_roles.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_roles.go new file mode 100644 index 00000000..75e59516 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_roles.go @@ -0,0 +1,1208 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// RolesApiService RolesApi service +type RolesApiService service + +type ApiAddParentRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string + parentRoleId string +} + +func (r ApiAddParentRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.AddParentRoleExecute(r) +} + +/* +AddParentRole Add Parent Role + +This endpoint is part of the role hierarchy feature. + +Makes role with id `role_id` extend the role with id `parent_role_id`. +In other words, `role_id` will automatically be assigned any permissions +that are granted to `parent_role_id`. + +We can say the `role_id` **extends** `parent_role_id` or **inherits** from `parent_role_id`. + +If `role_id` is already an ancestor of `parent_role_id`, +the request will fail with HTTP 400 to prevent a cycle in the role hierarchy. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @param parentRoleId Either the unique id of the parent role, or the URL-friendly key of the parent role (i.e: the \"slug\"). + @return ApiAddParentRoleRequest +*/ +func (a *RolesApiService) AddParentRole(ctx context.Context, projId string, envId string, roleId string, parentRoleId string) ApiAddParentRoleRequest { + return ApiAddParentRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + parentRoleId: parentRoleId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) AddParentRoleExecute(r ApiAddParentRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.AddParentRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}/parents/{parent_role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"parent_role_id"+"}", url.PathEscape(parameterToString(r.parentRoleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiAssignPermissionsToRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string + addRolePermissions *models.AddRolePermissions +} + +func (r ApiAssignPermissionsToRoleRequest) AddRolePermissions(addRolePermissions models.AddRolePermissions) ApiAssignPermissionsToRoleRequest { + r.addRolePermissions = &addRolePermissions + return r +} + +func (r ApiAssignPermissionsToRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.AssignPermissionsToRoleExecute(r) +} + +/* +AssignPermissionsToRole Assign Permissions To Role + +Assign permissions to role. + +If some of the permissions specified are already unassigned, will skip them. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiAssignPermissionsToRoleRequest +*/ +func (a *RolesApiService) AssignPermissionsToRole(ctx context.Context, projId string, envId string, roleId string) ApiAssignPermissionsToRoleRequest { + return ApiAssignPermissionsToRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) AssignPermissionsToRoleExecute(r ApiAssignPermissionsToRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.AssignPermissionsToRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}/permissions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.addRolePermissions == nil { + return localVarReturnValue, nil, reportError("addRolePermissions is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.addRolePermissions + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiCreateRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleCreate *models.RoleCreate +} + +func (r ApiCreateRoleRequest) RoleCreate(roleCreate models.RoleCreate) ApiCreateRoleRequest { + r.roleCreate = &roleCreate + return r +} + +func (r ApiCreateRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.CreateRoleExecute(r) +} + +/* +CreateRole Create Role + +Creates a new tenant role. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateRoleRequest +*/ +func (a *RolesApiService) CreateRole(ctx context.Context, projId string, envId string) ApiCreateRoleRequest { + return ApiCreateRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) CreateRoleExecute(r ApiCreateRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.CreateRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.roleCreate == nil { + return localVarReturnValue, nil, reportError("roleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.roleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string +} + +func (r ApiDeleteRoleRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteRoleExecute(r) +} + +/* +DeleteRole Delete Role + +Deletes a tenant role and all its related data. +This includes any permissions granted to said role. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiDeleteRoleRequest +*/ +func (a *RolesApiService) DeleteRole(ctx context.Context, projId string, envId string, roleId string) ApiDeleteRoleRequest { + return ApiDeleteRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + } +} + +// Execute executes the request +func (a *RolesApiService) DeleteRoleExecute(r ApiDeleteRoleRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.DeleteRole") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string +} + +func (r ApiGetRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.GetRoleExecute(r) +} + +/* +GetRole Get Role + +Gets a single tenant role, if such role exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiGetRoleRequest +*/ +func (a *RolesApiService) GetRole(ctx context.Context, projId string, envId string, roleId string) ApiGetRoleRequest { + return ApiGetRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) GetRoleExecute(r ApiGetRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.GetRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListRolesRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + attributesFilter map[string]interface{} + page *int32 + perPage *int32 +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListRolesRequest) Page(page int32) ApiListRolesRequest { + r.page = &page + return r +} + +// AttributeFilters on the result of the tenant list +func (r ApiListRolesRequest) AttributesFilter(attributesFilter map[string]interface{}) ApiListRolesRequest { + r.attributesFilter = attributesFilter + return r +} + +// The number of results per page (max 100). +func (r ApiListRolesRequest) PerPage(perPage int32) ApiListRolesRequest { + r.perPage = &perPage + return r +} + +func (r ApiListRolesRequest) Execute() ([]models.RoleRead, *http.Response, error) { + return r.ApiService.ListRolesExecute(r) +} + +/* +ListRoles List Roles + +Lists all tenant roles. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListRolesRequest +*/ +func (a *RolesApiService) ListRoles(ctx context.Context, projId string, envId string) ApiListRolesRequest { + return ApiListRolesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []RoleRead +func (a *RolesApiService) ListRolesExecute(r ApiListRolesRequest) ([]models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.RoleRead + ) + const attributeFilterPrefix = "attr_" + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.ListRoles") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.attributesFilter != nil { + for k, v := range r.attributesFilter { + localVarQueryParams.Add(attributeFilterPrefix+k, parameterToString(v, "")) + } + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiRemoveParentRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string + parentRoleId string +} + +func (r ApiRemoveParentRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.RemoveParentRoleExecute(r) +} + +/* +RemoveParentRole Remove Parent Role + +This endpoint is part of the role hierarchy feature. + +Removes `parent_role_id` from the list of parent roles of role with id `role_id`. +In other words, `role_id` will no longer be automatically assigned permissions +that are granted to `parent_role_id`. + +We can say the `role_id` **not longer extends** `parent_role_id` or **no longer inherits** from `parent_role_id`. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @param parentRoleId Either the unique id of the parent role, or the URL-friendly key of the parent role (i.e: the \"slug\"). + @return ApiRemoveParentRoleRequest +*/ +func (a *RolesApiService) RemoveParentRole(ctx context.Context, projId string, envId string, roleId string, parentRoleId string) ApiRemoveParentRoleRequest { + return ApiRemoveParentRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + parentRoleId: parentRoleId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) RemoveParentRoleExecute(r ApiRemoveParentRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.RemoveParentRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}/parents/{parent_role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"parent_role_id"+"}", url.PathEscape(parameterToString(r.parentRoleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiRemovePermissionsFromRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string + removeRolePermissions *models.RemoveRolePermissions +} + +func (r ApiRemovePermissionsFromRoleRequest) RemoveRolePermissions(removeRolePermissions models.RemoveRolePermissions) ApiRemovePermissionsFromRoleRequest { + r.removeRolePermissions = &removeRolePermissions + return r +} + +func (r ApiRemovePermissionsFromRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.RemovePermissionsFromRoleExecute(r) +} + +/* +RemovePermissionsFromRole Remove Permissions From Role + +Remove permissions from role. + +If some of the permissions specified are already unassigned, will skip them. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiRemovePermissionsFromRoleRequest +*/ +func (a *RolesApiService) RemovePermissionsFromRole(ctx context.Context, projId string, envId string, roleId string) ApiRemovePermissionsFromRoleRequest { + return ApiRemovePermissionsFromRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) RemovePermissionsFromRoleExecute(r ApiRemovePermissionsFromRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.RemovePermissionsFromRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}/permissions" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.removeRolePermissions == nil { + return localVarReturnValue, nil, reportError("removeRolePermissions is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.removeRolePermissions + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateRoleRequest struct { + ctx context.Context + ApiService *RolesApiService + projId string + envId string + roleId string + roleUpdate *models.RoleUpdate +} + +func (r ApiUpdateRoleRequest) RoleUpdate(roleUpdate models.RoleUpdate) ApiUpdateRoleRequest { + r.roleUpdate = &roleUpdate + return r +} + +func (r ApiUpdateRoleRequest) Execute() (*models.RoleRead, *http.Response, error) { + return r.ApiService.UpdateRoleExecute(r) +} + +/* +UpdateRole Update Role + +Partially updates a tenant role. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param roleId Either the unique id of the role, or the URL-friendly key of the role (i.e: the \"slug\"). + @return ApiUpdateRoleRequest +*/ +func (a *RolesApiService) UpdateRole(ctx context.Context, projId string, envId string, roleId string) ApiUpdateRoleRequest { + return ApiUpdateRoleRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + roleId: roleId, + } +} + +// Execute executes the request +// +// @return RoleRead +func (a *RolesApiService) UpdateRoleExecute(r ApiUpdateRoleRequest) (*models.RoleRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "RolesApiService.UpdateRole") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/roles/{role_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"role_id"+"}", url.PathEscape(parameterToString(r.roleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.roleUpdate == nil { + return localVarReturnValue, nil, reportError("roleUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.roleUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_tenants.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_tenants.go new file mode 100644 index 00000000..9d5f0acb --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_tenants.go @@ -0,0 +1,946 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// TenantsApiService TenantsApi service +type TenantsApiService service + +type ApiCreateTenantRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + envId string + tenantCreate *models.TenantCreate +} + +func (r ApiCreateTenantRequest) TenantCreate(tenantCreate models.TenantCreate) ApiCreateTenantRequest { + r.tenantCreate = &tenantCreate + return r +} + +func (r ApiCreateTenantRequest) Execute() (*models.TenantRead, *http.Response, error) { + return r.ApiService.CreateTenantExecute(r) +} + +/* +CreateTenant Create Tenant + +Creates a new tenant inside the Permit.io system. + +If the tenant is already created: will return 200 instead of 201, +and will return the existing tenant object in the response body. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateTenantRequest +*/ +func (a *TenantsApiService) CreateTenant(ctx context.Context, projId string, envId string) ApiCreateTenantRequest { + return ApiCreateTenantRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return TenantRead +func (a *TenantsApiService) CreateTenantExecute(r ApiCreateTenantRequest) (*models.TenantRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.TenantRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.CreateTenant") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.tenantCreate == nil { + return localVarReturnValue, nil, reportError("tenantCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.tenantCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteTenantRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + envId string + tenantId string +} + +func (r ApiDeleteTenantRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteTenantExecute(r) +} + +/* +DeleteTenant Delete Tenant + +Deletes the tenant and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param tenantId Either the unique id of the tenant, or the URL-friendly key of the tenant (i.e: the \"slug\"). + @return ApiDeleteTenantRequest +*/ +func (a *TenantsApiService) DeleteTenant(ctx context.Context, projId string, envId string, tenantId string) ApiDeleteTenantRequest { + return ApiDeleteTenantRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + tenantId: tenantId, + } +} + +// Execute executes the request +func (a *TenantsApiService) DeleteTenantExecute(r ApiDeleteTenantRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.DeleteTenant") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants/{tenant_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"tenant_id"+"}", url.PathEscape(parameterToString(r.tenantId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiDeleteTenantUserRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + envId string + tenantId string + userId string +} + +func (r ApiDeleteTenantUserRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteTenantUserExecute(r) +} + +/* +DeleteTenantUser Delete Tenant User + +Deletes a user under a tenant. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param tenantId Either the unique id of the tenant, or the URL-friendly key of the tenant (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiDeleteTenantUserRequest +*/ +func (a *TenantsApiService) DeleteTenantUser(ctx context.Context, projId string, envId string, tenantId string, userId string) ApiDeleteTenantUserRequest { + return ApiDeleteTenantUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + tenantId: tenantId, + userId: userId, + } +} + +// Execute executes the request +func (a *TenantsApiService) DeleteTenantUserExecute(r ApiDeleteTenantUserRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.DeleteTenantUser") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants/{tenant_id}/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"tenant_id"+"}", url.PathEscape(parameterToString(r.tenantId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetTenantRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + envId string + tenantId string +} + +func (r ApiGetTenantRequest) Execute() (*models.TenantRead, *http.Response, error) { + return r.ApiService.GetTenantExecute(r) +} + +/* +GetTenant Get Tenant + +Gets a tenant, if such tenant exists. Otherwise returns 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param tenantId Either the unique id of the tenant, or the URL-friendly key of the tenant (i.e: the \"slug\"). + @return ApiGetTenantRequest +*/ +func (a *TenantsApiService) GetTenant(ctx context.Context, projId string, envId string, tenantId string) ApiGetTenantRequest { + return ApiGetTenantRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + tenantId: tenantId, + } +} + +// Execute executes the request +// +// @return TenantRead +func (a *TenantsApiService) GetTenantExecute(r ApiGetTenantRequest) (*models.TenantRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.TenantRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.GetTenant") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants/{tenant_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"tenant_id"+"}", url.PathEscape(parameterToString(r.tenantId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListTenantUsersRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + tenantId string + envId string + search *string + page *int32 + perPage *int32 +} + +// Text search for the email field +func (r ApiListTenantUsersRequest) Search(search string) ApiListTenantUsersRequest { + r.search = &search + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListTenantUsersRequest) Page(page int32) ApiListTenantUsersRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListTenantUsersRequest) PerPage(perPage int32) ApiListTenantUsersRequest { + r.perPage = &perPage + return r +} + +func (r ApiListTenantUsersRequest) Execute() (*models.PaginatedResultUserRead, *http.Response, error) { + return r.ApiService.ListTenantUsersExecute(r) +} + +/* +ListTenantUsers List Tenant Users + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param tenantId Either the unique id of the tenant, or the URL-friendly key of the tenant (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListTenantUsersRequest +*/ +func (a *TenantsApiService) ListTenantUsers(ctx context.Context, projId string, tenantId string, envId string) ApiListTenantUsersRequest { + return ApiListTenantUsersRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + tenantId: tenantId, + envId: envId, + } +} + +// Execute executes the request +// +// @return PaginatedResultUserRead +func (a *TenantsApiService) ListTenantUsersExecute(r ApiListTenantUsersRequest) (*models.PaginatedResultUserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultUserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.ListTenantUsers") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants/{tenant_id}/users" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"tenant_id"+"}", url.PathEscape(parameterToString(r.tenantId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.search != nil { + localVarQueryParams.Add("search", parameterToString(*r.search, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListTenantsRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + envId string + search *string + attributesFilter map[string]interface{} + page *int32 + perPage *int32 +} + +// Text search for the tenant name or key +func (r ApiListTenantsRequest) Search(search string) ApiListTenantsRequest { + r.search = &search + return r +} + +// Filter for tenant with specific attributes +func (r ApiListTenantsRequest) AttributeFilter(attributesFilter map[string]interface{}) ApiListTenantsRequest { + r.attributesFilter = attributesFilter + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListTenantsRequest) Page(page int32) ApiListTenantsRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListTenantsRequest) PerPage(perPage int32) ApiListTenantsRequest { + r.perPage = &perPage + return r +} + +func (r ApiListTenantsRequest) Execute() ([]models.TenantRead, *http.Response, error) { + return r.ApiService.ListTenantsExecute(r) +} + +/* +ListTenants List Tenants + +Lists all the tenants defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListTenantsRequest +*/ +func (a *TenantsApiService) ListTenants(ctx context.Context, projId string, envId string) ApiListTenantsRequest { + return ApiListTenantsRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []TenantRead +func (a *TenantsApiService) ListTenantsExecute(r ApiListTenantsRequest) ([]models.TenantRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.TenantRead + ) + const attributeFilterPrefix = "attr_" + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.ListTenants") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.attributesFilter != nil { + for k, v := range r.attributesFilter { + localVarQueryParams.Add(attributeFilterPrefix+k, parameterToString(v, "")) + } + } + if r.search != nil { + localVarQueryParams.Add("search", parameterToString(*r.search, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateTenantRequest struct { + ctx context.Context + ApiService *TenantsApiService + projId string + envId string + tenantId string + tenantUpdate *models.TenantUpdate +} + +func (r ApiUpdateTenantRequest) TenantUpdate(tenantUpdate models.TenantUpdate) ApiUpdateTenantRequest { + r.tenantUpdate = &tenantUpdate + return r +} + +func (r ApiUpdateTenantRequest) Execute() (*models.TenantRead, *http.Response, error) { + return r.ApiService.UpdateTenantExecute(r) +} + +/* +UpdateTenant Update Tenant + +Partially updates the tenant definition. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param tenantId Either the unique id of the tenant, or the URL-friendly key of the tenant (i.e: the \"slug\"). + @return ApiUpdateTenantRequest +*/ +func (a *TenantsApiService) UpdateTenant(ctx context.Context, projId string, envId string, tenantId string) ApiUpdateTenantRequest { + return ApiUpdateTenantRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + tenantId: tenantId, + } +} + +// Execute executes the request +// +// @return TenantRead +func (a *TenantsApiService) UpdateTenantExecute(r ApiUpdateTenantRequest) (*models.TenantRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.TenantRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "TenantsApiService.UpdateTenant") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/tenants/{tenant_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"tenant_id"+"}", url.PathEscape(parameterToString(r.tenantId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.tenantUpdate == nil { + return localVarReturnValue, nil, reportError("tenantUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.tenantUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_user_attributes.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_user_attributes.go new file mode 100644 index 00000000..5d48a716 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_user_attributes.go @@ -0,0 +1,725 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// UserAttributesApiService UserAttributesApi service +type UserAttributesApiService service + +type ApiCreateUserAttributeRequest struct { + ctx context.Context + ApiService *UserAttributesApiService + projId string + envId string + resourceAttributeCreate *models.ResourceAttributeCreate + resourceId *string +} + +func (r ApiCreateUserAttributeRequest) ResourceAttributeCreate(resourceAttributeCreate models.ResourceAttributeCreate) ApiCreateUserAttributeRequest { + r.resourceAttributeCreate = &resourceAttributeCreate + return r +} + +func (r ApiCreateUserAttributeRequest) ResourceId(resourceId string) ApiCreateUserAttributeRequest { + r.resourceId = &resourceId + return r +} + +func (r ApiCreateUserAttributeRequest) Execute() (*models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.CreateUserAttributeExecute(r) +} + +/* +CreateUserAttribute Create User Attribute + +Creates a new attribute for the User resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateUserAttributeRequest +*/ +func (a *UserAttributesApiService) CreateUserAttribute(ctx context.Context, projId string, envId string) ApiCreateUserAttributeRequest { + return ApiCreateUserAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return ResourceAttributeRead +func (a *UserAttributesApiService) CreateUserAttributeExecute(r ApiCreateUserAttributeRequest) (*models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserAttributesApiService.CreateUserAttribute") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/users/attributes" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceAttributeCreate == nil { + return localVarReturnValue, nil, reportError("resourceAttributeCreate is required and must be specified") + } + + if r.resourceId != nil { + localVarQueryParams.Add("resource_id", parameterToString(*r.resourceId, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceAttributeCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteUserAttributeRequest struct { + ctx context.Context + ApiService *UserAttributesApiService + projId string + envId string + attributeId string + resourceId *string + page *int32 + perPage *int32 +} + +func (r ApiDeleteUserAttributeRequest) ResourceId(resourceId string) ApiDeleteUserAttributeRequest { + r.resourceId = &resourceId + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiDeleteUserAttributeRequest) Page(page int32) ApiDeleteUserAttributeRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiDeleteUserAttributeRequest) PerPage(perPage int32) ApiDeleteUserAttributeRequest { + r.perPage = &perPage + return r +} + +func (r ApiDeleteUserAttributeRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteUserAttributeExecute(r) +} + +/* +DeleteUserAttribute Delete User Attribute + +Deletes the attribute and all its related data. + +Note: If the attribute is used by policies, removing it will cause the +attribute to evaluate as `undefined`. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param attributeId Either the unique id of the attribute, or the URL-friendly key of the attribute (i.e: the \"slug\"). + @return ApiDeleteUserAttributeRequest +*/ +func (a *UserAttributesApiService) DeleteUserAttribute(ctx context.Context, projId string, envId string, attributeId string) ApiDeleteUserAttributeRequest { + return ApiDeleteUserAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + attributeId: attributeId, + } +} + +// Execute executes the request +func (a *UserAttributesApiService) DeleteUserAttributeExecute(r ApiDeleteUserAttributeRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserAttributesApiService.DeleteUserAttribute") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/users/attributes/{attribute_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"attribute_id"+"}", url.PathEscape(parameterToString(r.attributeId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.resourceId != nil { + localVarQueryParams.Add("resource_id", parameterToString(*r.resourceId, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetUserAttributeRequest struct { + ctx context.Context + ApiService *UserAttributesApiService + projId string + envId string + attributeId string + resourceId *string +} + +func (r ApiGetUserAttributeRequest) ResourceId(resourceId string) ApiGetUserAttributeRequest { + r.resourceId = &resourceId + return r +} + +func (r ApiGetUserAttributeRequest) Execute() (*models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.GetUserAttributeExecute(r) +} + +/* +GetUserAttribute Get User Attribute + +Gets a single attribute defined on the User resource, if such attribute exists. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param attributeId Either the unique id of the attribute, or the URL-friendly key of the attribute (i.e: the \"slug\"). + @return ApiGetUserAttributeRequest +*/ +func (a *UserAttributesApiService) GetUserAttribute(ctx context.Context, projId string, envId string, attributeId string) ApiGetUserAttributeRequest { + return ApiGetUserAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + attributeId: attributeId, + } +} + +// Execute executes the request +// +// @return ResourceAttributeRead +func (a *UserAttributesApiService) GetUserAttributeExecute(r ApiGetUserAttributeRequest) (*models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserAttributesApiService.GetUserAttribute") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/users/attributes/{attribute_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"attribute_id"+"}", url.PathEscape(parameterToString(r.attributeId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.resourceId != nil { + localVarQueryParams.Add("resource_id", parameterToString(*r.resourceId, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListUserAttributesRequest struct { + ctx context.Context + ApiService *UserAttributesApiService + projId string + envId string + resourceId *string + page *int32 + perPage *int32 +} + +func (r ApiListUserAttributesRequest) ResourceId(resourceId string) ApiListUserAttributesRequest { + r.resourceId = &resourceId + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListUserAttributesRequest) Page(page int32) ApiListUserAttributesRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListUserAttributesRequest) PerPage(perPage int32) ApiListUserAttributesRequest { + r.perPage = &perPage + return r +} + +func (r ApiListUserAttributesRequest) Execute() ([]models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.ListUserAttributesExecute(r) +} + +/* +ListUserAttributes List User Attributes + +Lists all the attributes defined on the User resource. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListUserAttributesRequest +*/ +func (a *UserAttributesApiService) ListUserAttributes(ctx context.Context, projId string, envId string) ApiListUserAttributesRequest { + return ApiListUserAttributesRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return []ResourceAttributeRead +func (a *UserAttributesApiService) ListUserAttributesExecute(r ApiListUserAttributesRequest) ([]models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserAttributesApiService.ListUserAttributes") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/users/attributes" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.resourceId != nil { + localVarQueryParams.Add("resource_id", parameterToString(*r.resourceId, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateUserAttributeRequest struct { + ctx context.Context + ApiService *UserAttributesApiService + projId string + envId string + attributeId string + resourceAttributeUpdate *models.ResourceAttributeUpdate + resourceId *string +} + +func (r ApiUpdateUserAttributeRequest) ResourceAttributeUpdate(resourceAttributeUpdate models.ResourceAttributeUpdate) ApiUpdateUserAttributeRequest { + r.resourceAttributeUpdate = &resourceAttributeUpdate + return r +} + +func (r ApiUpdateUserAttributeRequest) ResourceId(resourceId string) ApiUpdateUserAttributeRequest { + r.resourceId = &resourceId + return r +} + +func (r ApiUpdateUserAttributeRequest) Execute() (*models.ResourceAttributeRead, *http.Response, error) { + return r.ApiService.UpdateUserAttributeExecute(r) +} + +/* +UpdateUserAttribute Update User Attribute + +Partially updates the attribute defined on the User resource. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param attributeId Either the unique id of the attribute, or the URL-friendly key of the attribute (i.e: the \"slug\"). + @return ApiUpdateUserAttributeRequest +*/ +func (a *UserAttributesApiService) UpdateUserAttribute(ctx context.Context, projId string, envId string, attributeId string) ApiUpdateUserAttributeRequest { + return ApiUpdateUserAttributeRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + attributeId: attributeId, + } +} + +// Execute executes the request +// +// @return ResourceAttributeRead +func (a *UserAttributesApiService) UpdateUserAttributeExecute(r ApiUpdateUserAttributeRequest) (*models.ResourceAttributeRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.ResourceAttributeRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserAttributesApiService.UpdateUserAttribute") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/schema/{proj_id}/{env_id}/users/attributes/{attribute_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"attribute_id"+"}", url.PathEscape(parameterToString(r.attributeId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.resourceAttributeUpdate == nil { + return localVarReturnValue, nil, reportError("resourceAttributeUpdate is required and must be specified") + } + + if r.resourceId != nil { + localVarQueryParams.Add("resource_id", parameterToString(*r.resourceId, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.resourceAttributeUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/api_users.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_users.go new file mode 100644 index 00000000..ec4ac801 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/api_users.go @@ -0,0 +1,1074 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "github.com/permitio/permit-golang/pkg/models" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// UsersApiService UsersApi service +type UsersApiService service + +type ApiAssignRoleToUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userId string + userRoleCreate *models.UserRoleCreate +} + +func (r ApiAssignRoleToUserRequest) UserRoleCreate(userRoleCreate models.UserRoleCreate) ApiAssignRoleToUserRequest { + r.userRoleCreate = &userRoleCreate + return r +} + +func (r ApiAssignRoleToUserRequest) Execute() (*models.RoleAssignmentRead, *http.Response, error) { + return r.ApiService.AssignRoleToUserExecute(r) +} + +/* +AssignRoleToUser Assign Role To User + +Assigns a role to the user within the tenant. + +The tenant defines the scope of the assignment. In other words, the role is effective only within the tenant. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiAssignRoleToUserRequest +*/ +func (a *UsersApiService) AssignRoleToUser(ctx context.Context, projId string, envId string, userId string) ApiAssignRoleToUserRequest { + return ApiAssignRoleToUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +// +// @return RoleAssignmentRead +func (a *UsersApiService) AssignRoleToUserExecute(r ApiAssignRoleToUserRequest) (*models.RoleAssignmentRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.RoleAssignmentRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.AssignRoleToUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users/{user_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.userRoleCreate == nil { + return localVarReturnValue, nil, reportError("userRoleCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.userRoleCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiCreateUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userCreate *models.UserCreate +} + +func (r ApiCreateUserRequest) UserCreate(userCreate models.UserCreate) ApiCreateUserRequest { + r.userCreate = &userCreate + return r +} + +func (r ApiCreateUserRequest) Execute() (*models.UserRead, *http.Response, error) { + return r.ApiService.CreateUserExecute(r) +} + +/* +CreateUser Create User + +Creates a new user inside the Permit.io system, from that point forward +you may run permission checks on that user. + +If the user is already created: will return 200 instead of 201, +and will return the existing user object in the response body. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiCreateUserRequest +*/ +func (a *UsersApiService) CreateUser(ctx context.Context, projId string, envId string) ApiCreateUserRequest { + return ApiCreateUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return UserRead +func (a *UsersApiService) CreateUserExecute(r ApiCreateUserRequest) (*models.UserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.CreateUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.userCreate == nil { + return localVarReturnValue, nil, reportError("userCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.userCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiDeleteUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userId string +} + +func (r ApiDeleteUserRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteUserExecute(r) +} + +/* +DeleteUser Delete User + +Deletes the user and all its related data. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiDeleteUserRequest +*/ +func (a *UsersApiService) DeleteUser(ctx context.Context, projId string, envId string, userId string) ApiDeleteUserRequest { + return ApiDeleteUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +func (a *UsersApiService) DeleteUserExecute(r ApiDeleteUserRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.DeleteUser") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiGetUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userId string +} + +func (r ApiGetUserRequest) Execute() (*models.UserRead, *http.Response, error) { + return r.ApiService.GetUserExecute(r) +} + +/* +GetUser Get User + +Gets a user, if such user exists. Otherwise returns 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiGetUserRequest +*/ +func (a *UsersApiService) GetUser(ctx context.Context, projId string, envId string, userId string) ApiGetUserRequest { + return ApiGetUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +// +// @return UserRead +func (a *UsersApiService) GetUserExecute(r ApiGetUserRequest) (*models.UserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.GetUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiListUsersRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + search *string + page *int32 + perPage *int32 +} + +// Text search for the email field +func (r ApiListUsersRequest) Search(search string) ApiListUsersRequest { + r.search = &search + return r +} + +// Page number of the results to fetch, starting at 1. +func (r ApiListUsersRequest) Page(page int32) ApiListUsersRequest { + r.page = &page + return r +} + +// The number of results per page (max 100). +func (r ApiListUsersRequest) PerPage(perPage int32) ApiListUsersRequest { + r.perPage = &perPage + return r +} + +func (r ApiListUsersRequest) Execute() (*models.PaginatedResultUserRead, *http.Response, error) { + return r.ApiService.ListUsersExecute(r) +} + +/* +ListUsers List Users + +Lists all the users defined within an environment. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @return ApiListUsersRequest +*/ +func (a *UsersApiService) ListUsers(ctx context.Context, projId string, envId string) ApiListUsersRequest { + return ApiListUsersRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + } +} + +// Execute executes the request +// +// @return PaginatedResultUserRead +func (a *UsersApiService) ListUsersExecute(r ApiListUsersRequest) (*models.PaginatedResultUserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.PaginatedResultUserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.ListUsers") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + if r.search != nil { + localVarQueryParams.Add("search", parameterToString(*r.search, "")) + } + if r.page != nil { + localVarQueryParams.Add("page", parameterToString(*r.page, "")) + } + if r.perPage != nil { + localVarQueryParams.Add("per_page", parameterToString(*r.perPage, "")) + } + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiReplaceUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userId string + userCreate *models.UserCreate +} + +func (r ApiReplaceUserRequest) UserCreate(userCreate models.UserCreate) ApiReplaceUserRequest { + r.userCreate = &userCreate + return r +} + +func (r ApiReplaceUserRequest) Execute() (*models.UserRead, *http.Response, error) { + return r.ApiService.ReplaceUserExecute(r) +} + +/* +ReplaceUser Replace User + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiReplaceUserRequest +*/ +func (a *UsersApiService) ReplaceUser(ctx context.Context, projId string, envId string, userId string) ApiReplaceUserRequest { + return ApiReplaceUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +// +// @return UserRead +func (a *UsersApiService) ReplaceUserExecute(r ApiReplaceUserRequest) (*models.UserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.ReplaceUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.userCreate == nil { + return localVarReturnValue, nil, reportError("userCreate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.userCreate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUnassignRoleFromUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userId string + userRoleRemove *models.UserRoleRemove +} + +func (r ApiUnassignRoleFromUserRequest) UserRoleRemove(userRoleRemove models.UserRoleRemove) ApiUnassignRoleFromUserRequest { + r.userRoleRemove = &userRoleRemove + return r +} + +func (r ApiUnassignRoleFromUserRequest) Execute() (*models.UserRead, *http.Response, error) { + return r.ApiService.UnassignRoleFromUserExecute(r) +} + +/* +UnassignRoleFromUser Unassign Role From User + +Unassigns the role from the user within the tenant. + +The tenant defines the scope of the assignment. In other words, the role is effective only within the tenant. + +If the role is not actually assigned, will return 404. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiUnassignRoleFromUserRequest +*/ +func (a *UsersApiService) UnassignRoleFromUser(ctx context.Context, projId string, envId string, userId string) ApiUnassignRoleFromUserRequest { + return ApiUnassignRoleFromUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +// +// @return UserRead +func (a *UsersApiService) UnassignRoleFromUserExecute(r ApiUnassignRoleFromUserRequest) (*models.UserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.UnassignRoleFromUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users/{user_id}/roles" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.userRoleRemove == nil { + return localVarReturnValue, nil, reportError("userRoleRemove is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.userRoleRemove + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiUpdateUserRequest struct { + ctx context.Context + ApiService *UsersApiService + projId string + envId string + userId string + userUpdate *models.UserUpdate +} + +func (r ApiUpdateUserRequest) UserUpdate(userUpdate models.UserUpdate) ApiUpdateUserRequest { + r.userUpdate = &userUpdate + return r +} + +func (r ApiUpdateUserRequest) Execute() (*models.UserRead, *http.Response, error) { + return r.ApiService.UpdateUserExecute(r) +} + +/* +UpdateUser Update User + +Partially updates the user definition. +Fields that will be provided will be completely overwritten. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projId Either the unique id of the project, or the URL-friendly key of the project (i.e: the \"slug\"). + @param envId Either the unique id of the environment, or the URL-friendly key of the environment (i.e: the \"slug\"). + @param userId Either the unique id of the user, or the URL-friendly key of the user (i.e: the \"slug\"). + @return ApiUpdateUserRequest +*/ +func (a *UsersApiService) UpdateUser(ctx context.Context, projId string, envId string, userId string) ApiUpdateUserRequest { + return ApiUpdateUserRequest{ + ApiService: a, + ctx: ctx, + projId: projId, + envId: envId, + userId: userId, + } +} + +// Execute executes the request +// +// @return UserRead +func (a *UsersApiService) UpdateUserExecute(r ApiUpdateUserRequest) (*models.UserRead, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPatch + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *models.UserRead + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UsersApiService.UpdateUser") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/v2/facts/{proj_id}/{env_id}/users/{user_id}" + localVarPath = strings.Replace(localVarPath, "{"+"proj_id"+"}", url.PathEscape(parameterToString(r.projId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"env_id"+"}", url.PathEscape(parameterToString(r.envId, "")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"user_id"+"}", url.PathEscape(parameterToString(r.userId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.userUpdate == nil { + return localVarReturnValue, nil, reportError("userUpdate is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.userUpdate + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 422 { + var v models.HTTPValidationError + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v) + newErr.model = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/client.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/client.go new file mode 100644 index 00000000..0cf1d242 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/client.go @@ -0,0 +1,742 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "github.com/permitio/permit-golang/pkg/models" + "io" + "io/ioutil" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) + xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) +) + +// APIClient manages communication with the Permit.io API API v2.0.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + APIKeysApi *APIKeysApiService + AuthenticationApi *AuthenticationApiService + ConditionSetRulesApi *ConditionSetRulesApiService + ConditionSetsApi *ConditionSetsApiService + DecisionLogsApi *DecisionLogsApiService + DecisionLogsIngressApi *DecisionLogsIngressApiService + DefaultApi *DefaultApiService + ElementsConfigsApi *ElementsConfigsApiService + ElementsDataApi *ElementsDataApiService + EnvironmentsApi *EnvironmentsApiService + ImplicitGrantsApi *ImplicitGrantsAPIService + InstructionsApi *InstructionsApiService + MembersApi *MembersApiService + OPALDataApi *OPALDataApiService + OrganizationsApi *OrganizationsApiService + PolicyApi *PolicyApiService + PolicyDecisionPointsApi *PolicyDecisionPointsApiService + PolicyGitRepositoriesApi *PolicyGitRepositoriesApiService + ProjectsApi *ProjectsApiService + ProxyConfigAPI *ProxyConfigAPIService + RelationshipTuplesApi *RelationshipTuplesAPIService + ResourceActionGroupsApi *ResourceActionGroupsApiService + ResourceActionsApi *ResourceActionsApiService + ResourceAttributesApi *ResourceAttributesApiService + ResourceInstancesApi *ResourceInstancesApiService + ResourceRelations *ResourceRelationsAPIService + ResourceRoles *ResourceRolesApiService + ResourcesApi *ResourcesApiService + RoleAssignmentsApi *RoleAssignmentsApiService + RolesApi *RolesApiService + TenantsApi *TenantsApiService + UserAttributesApi *UserAttributesApiService + UsersApi *UsersApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.APIKeysApi = (*APIKeysApiService)(&c.common) + c.AuthenticationApi = (*AuthenticationApiService)(&c.common) + c.ConditionSetRulesApi = (*ConditionSetRulesApiService)(&c.common) + c.ConditionSetsApi = (*ConditionSetsApiService)(&c.common) + c.DecisionLogsApi = (*DecisionLogsApiService)(&c.common) + c.DecisionLogsIngressApi = (*DecisionLogsIngressApiService)(&c.common) + c.DefaultApi = (*DefaultApiService)(&c.common) + c.ElementsConfigsApi = (*ElementsConfigsApiService)(&c.common) + c.ElementsDataApi = (*ElementsDataApiService)(&c.common) + c.EnvironmentsApi = (*EnvironmentsApiService)(&c.common) + c.ImplicitGrantsApi = (*ImplicitGrantsAPIService)(&c.common) + c.InstructionsApi = (*InstructionsApiService)(&c.common) + c.MembersApi = (*MembersApiService)(&c.common) + c.OPALDataApi = (*OPALDataApiService)(&c.common) + c.OrganizationsApi = (*OrganizationsApiService)(&c.common) + c.PolicyApi = (*PolicyApiService)(&c.common) + c.PolicyDecisionPointsApi = (*PolicyDecisionPointsApiService)(&c.common) + c.PolicyGitRepositoriesApi = (*PolicyGitRepositoriesApiService)(&c.common) + c.ProjectsApi = (*ProjectsApiService)(&c.common) + c.ProxyConfigAPI = (*ProxyConfigAPIService)(&c.common) + c.RelationshipTuplesApi = (*RelationshipTuplesAPIService)(&c.common) + c.ResourceActionGroupsApi = (*ResourceActionGroupsApiService)(&c.common) + c.ResourceActionsApi = (*ResourceActionsApiService)(&c.common) + c.ResourceAttributesApi = (*ResourceAttributesApiService)(&c.common) + c.ResourceInstancesApi = (*ResourceInstancesApiService)(&c.common) + c.ResourceRelations = (*ResourceRelationsAPIService)(&c.common) + c.ResourceRoles = (*ResourceRolesApiService)(&c.common) + c.ResourcesApi = (*ResourcesApiService)(&c.common) + c.RoleAssignmentsApi = (*RoleAssignmentsApiService)(&c.common) + c.RolesApi = (*RolesApiService)(&c.common) + c.TenantsApi = (*TenantsApiService)(&c.common) + c.UserAttributesApi = (*UserAttributesApiService)(&c.common) + c.UsersApi = (*UsersApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insensitive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.EqualFold(a, needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("expected %s to be of type %s but received %s", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } else if t, ok := obj.(time.Time); ok { + return t.Format(time.RFC3339) + } + + return fmt.Sprintf("%v", obj) +} + +// helper for converting interface{} parameters to json strings +func parameterToJson(obj interface{}) (string, error) { + jsonBuf, err := json.Marshal(obj) + if err != nil { + return "", err + } + return string(jsonBuf), err +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + if c.cfg.Debug { + dump, err := httputil.DumpRequestOut(request, true) + if err != nil { + return nil, err + } + log.Printf("\n%s\n", string(dump)) + } + + resp, err := c.cfg.HTTPClient.Do(request) + if err != nil { + return resp, err + } + + if c.cfg.Debug { + dump, err := httputil.DumpResponse(resp, true) + if err != nil { + return resp, err + } + log.Printf("\n%s\n", string(dump)) + } + return resp, err +} + +// Allow modification of underlying config for alternate implementations and testing +// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior +func (c *APIClient) GetConfig() *Configuration { + return c.cfg +} + +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + formFiles []formFile) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } + } + } + + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers[h] = []string{v} + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if f, ok := v.(**os.File); ok { + *f, err = ioutil.TempFile("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + if err != nil { + return + } + _, err = (*f).Seek(0, io.SeekStart) + return + } + if xmlCheck.MatchString(contentType) { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } + if jsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err != nil { + return err + } + } else { + return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(filepath.Clean(path)) + if err != nil { + return err + } + err = file.Close() + if err != nil { + return err + } + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if fp, ok := body.(**os.File); ok { + _, err = bodyBuf.ReadFrom(*fp) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + err = xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } else { + expires = now.Add(lifetime) + } + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericOpenAPIError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericOpenAPIError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericOpenAPIError) Model() interface{} { + return e.model +} + +// format error message using title and detail when model implements rfc7807 +func formatErrorMessage(status string, v interface{}) string { + + str := "" + metaValue := reflect.ValueOf(v).Elem() + + field := metaValue.FieldByName("Title") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s", field.Interface()) + } + + field = metaValue.FieldByName("Detail") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s (%s)", str, field.Interface()) + } + + // status title (detail) + return fmt.Sprintf("%s %s", status, str) +} + +func parameterValueToString(obj interface{}, key string) string { + if reflect.TypeOf(obj).Kind() != reflect.Ptr { + return fmt.Sprintf("%v", obj) + } + var param, ok = obj.(models.MappedNullable) + if !ok { + return "" + } + dataMap, err := param.ToMap() + if err != nil { + return "" + } + return fmt.Sprintf("%v", dataMap[key]) +} + +// parameterAddToHeaderOrQuery adds the provided object to the request header or url query +// supporting deep object syntax +func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, collectionType string) { + var v = reflect.ValueOf(obj) + var value = "" + if v == reflect.ValueOf(nil) { + value = "null" + } else { + switch v.Kind() { + case reflect.Invalid: + value = "invalid" + + case reflect.Struct: + if t, ok := obj.(models.MappedNullable); ok { + dataMap, err := t.ToMap() + if err != nil { + return + } + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, collectionType) + return + } + if t, ok := obj.(time.Time); ok { + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339), collectionType) + return + } + value = v.Type().String() + " value" + case reflect.Slice: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + var lenIndValue = indValue.Len() + for i := 0; i < lenIndValue; i++ { + var arrayValue = indValue.Index(i) + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, arrayValue.Interface(), collectionType) + } + return + + case reflect.Map: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + iter := indValue.MapRange() + for iter.Next() { + k, v := iter.Key(), iter.Value() + parameterAddToHeaderOrQuery(headerOrQueryParams, fmt.Sprintf("%s[%s]", keyPrefix, k.String()), v.Interface(), collectionType) + } + return + + case reflect.Interface: + fallthrough + case reflect.Ptr: + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, v.Elem().Interface(), collectionType) + return + + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + value = strconv.FormatInt(v.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + value = strconv.FormatUint(v.Uint(), 10) + case reflect.Float32, reflect.Float64: + value = strconv.FormatFloat(v.Float(), 'g', -1, 32) + case reflect.Bool: + value = strconv.FormatBool(v.Bool()) + case reflect.String: + value = v.String() + default: + value = v.Type().String() + " value" + } + } + + switch valuesMap := headerOrQueryParams.(type) { + case url.Values: + if collectionType == "csv" && valuesMap.Get(keyPrefix) != "" { + valuesMap.Set(keyPrefix, valuesMap.Get(keyPrefix)+","+value) + } else { + valuesMap.Add(keyPrefix, value) + } + break + case map[string]string: + valuesMap[keyPrefix] = value + break + } +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/configuration.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/configuration.go new file mode 100644 index 00000000..907ed492 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/configuration.go @@ -0,0 +1,229 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKeys takes a string apikey as authentication for the request + ContextAPIKeys = contextKey("apiKeys") + + // ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request. + ContextHttpSignatureAuth = contextKey("httpsignature") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "", + Description: "No description provided", + }, + }, + OperationServers: map[string]ServerConfigurations{}, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/openapi/response.go b/vendor/github.com/permitio/permit-golang/pkg/openapi/response.go new file mode 100644 index 00000000..e78b5572 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/openapi/response.go @@ -0,0 +1,47 @@ +/* +Permit.io API + + Authorization as a service + +API version: 2.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResponse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/vendor/github.com/permitio/permit-golang/pkg/permit/permit.go b/vendor/github.com/permitio/permit-golang/pkg/permit/permit.go new file mode 100644 index 00000000..01ed1c21 --- /dev/null +++ b/vendor/github.com/permitio/permit-golang/pkg/permit/permit.go @@ -0,0 +1,67 @@ +package permit + +import ( + "context" + + "github.com/permitio/permit-golang/pkg/api" + config "github.com/permitio/permit-golang/pkg/config" + "github.com/permitio/permit-golang/pkg/enforcement" + "github.com/permitio/permit-golang/pkg/models" +) + +type Client struct { + config config.PermitConfig + Api *api.PermitApiClient + Elements *api.Elements + enforcement *enforcement.PermitEnforcer +} + +var New = NewPermit + +func NewPermit(config config.PermitConfig) *Client { + apiClient := api.NewPermitApiClient(&config) + enforcerClient := enforcement.NewPermitEnforcerClient(&config) + return &Client{ + config: config, + Api: apiClient, + Elements: apiClient.Elements, + enforcement: enforcerClient, + } +} + +func (c *Client) SyncUser(ctx context.Context, user models.UserCreate) (*models.UserRead, error) { + return c.Api.Users.SyncUser(ctx, user) +} +func (c *Client) Check(user enforcement.User, action enforcement.Action, resource enforcement.Resource) (bool, error) { + return c.enforcement.Check(user, action, resource) +} + +func (c *Client) BulkCheck(requests ...enforcement.CheckRequest) ([]bool, error) { + return c.enforcement.BulkCheck(requests...) +} + +func (c *Client) FilterObjects(user enforcement.User, action enforcement.Action, context map[string]string, resources ...enforcement.ResourceI) ([]enforcement.ResourceI, error) { + return c.enforcement.FilterObjects(user, action, context, resources...) +} + +func (c *Client) AllTenantsCheck(user enforcement.User, action enforcement.Action, resource enforcement.Resource) ([]enforcement.TenantDetails, error) { + return c.enforcement.AllTenantsCheck(user, action, resource) +} + +func (c *Client) GetUserPermissions(user enforcement.User, tenants ...string) (enforcement.UserPermissions, error) { + return c.enforcement.GetUserPermissions(user, tenants...) +} + +func (c *Client) GetUserPermissionsWithOptions(user enforcement.User, opts ...enforcement.UserPermissionsOption) (enforcement.UserPermissions, error) { + return c.enforcement.GetUserPermissionsWithOptions(user, opts...) +} + +type PermitInterface interface { + Check(user enforcement.User, action enforcement.Action, resource enforcement.Resource) (bool, error) + BulkCheck(requests ...enforcement.CheckRequest) ([]bool, error) + FilterObjects(user enforcement.User, action enforcement.Action, context map[string]string, resources ...enforcement.ResourceI) ([]enforcement.ResourceI, error) + AllTenantsCheck(user enforcement.User, action enforcement.Action, resource enforcement.Resource) ([]enforcement.TenantDetails, error) + GetUserPermissions(user enforcement.User, tenants ...string) (enforcement.UserPermissions, error) + GetUserPermissionsWithOptions(user enforcement.User, opts ...enforcement.UserPermissionsOption) (enforcement.UserPermissions, error) + SyncUser(ctx context.Context, user models.UserCreate) (*models.UserRead, error) +} diff --git a/vendor/go.uber.org/zap/.codecov.yml b/vendor/go.uber.org/zap/.codecov.yml new file mode 100644 index 00000000..8e5ca7d3 --- /dev/null +++ b/vendor/go.uber.org/zap/.codecov.yml @@ -0,0 +1,17 @@ +coverage: + range: 80..100 + round: down + precision: 2 + + status: + project: # measuring the overall project coverage + default: # context, you can create multiple ones with custom titles + enabled: yes # must be yes|true to enable this status + target: 95% # specify the target coverage for each commit status + # option: "auto" (must increase from parent commit or pull request base) + # option: "X%" a static target percentage to hit + if_not_found: success # if parent is not found report status as success, error, or failure + if_ci_failed: error # if ci fails report status as success, error, or failure +ignore: + - internal/readme/readme.go + diff --git a/vendor/go.uber.org/zap/.gitignore b/vendor/go.uber.org/zap/.gitignore new file mode 100644 index 00000000..da9d9d00 --- /dev/null +++ b/vendor/go.uber.org/zap/.gitignore @@ -0,0 +1,32 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test +vendor + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +*.pprof +*.out +*.log + +/bin +cover.out +cover.html diff --git a/vendor/go.uber.org/zap/.golangci.yml b/vendor/go.uber.org/zap/.golangci.yml new file mode 100644 index 00000000..fbc6df79 --- /dev/null +++ b/vendor/go.uber.org/zap/.golangci.yml @@ -0,0 +1,77 @@ +output: + # Make output more digestible with quickfix in vim/emacs/etc. + sort-results: true + print-issued-lines: false + +linters: + # We'll track the golangci-lint default linters manually + # instead of letting them change without our control. + disable-all: true + enable: + # golangci-lint defaults: + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - unused + + # Our own extras: + - gofmt + - nolintlint # lints nolint directives + - revive + +linters-settings: + govet: + # These govet checks are disabled by default, but they're useful. + enable: + - niliness + - reflectvaluecompare + - sortslice + - unusedwrite + + errcheck: + exclude-functions: + # These methods can not fail. + # They operate on an in-memory buffer. + - (*go.uber.org/zap/buffer.Buffer).Write + - (*go.uber.org/zap/buffer.Buffer).WriteByte + - (*go.uber.org/zap/buffer.Buffer).WriteString + + - (*go.uber.org/zap/zapio.Writer).Close + - (*go.uber.org/zap/zapio.Writer).Sync + - (*go.uber.org/zap/zapio.Writer).Write + # Write to zapio.Writer cannot fail, + # so io.WriteString on it cannot fail. + - io.WriteString(*go.uber.org/zap/zapio.Writer) + + # Writing a plain string to a fmt.State cannot fail. + - io.WriteString(fmt.State) + +issues: + # Print all issues reported by all linters. + max-issues-per-linter: 0 + max-same-issues: 0 + + # Don't ignore some of the issues that golangci-lint considers okay. + # This includes documenting all exported entities. + exclude-use-default: false + + exclude-rules: + # Don't warn on unused parameters. + # Parameter names are useful; replacing them with '_' is undesirable. + - linters: [revive] + text: 'unused-parameter: parameter \S+ seems to be unused, consider removing or renaming it as _' + + # staticcheck already has smarter checks for empty blocks. + # revive's empty-block linter has false positives. + # For example, as of writing this, the following is not allowed. + # for foo() { } + - linters: [revive] + text: 'empty-block: this block is empty, you can remove it' + + # Ignore logger.Sync() errcheck failures in example_test.go + # since those are intended to be uncomplicated examples. + - linters: [errcheck] + path: example_test.go + text: 'Error return value of `logger.Sync` is not checked' diff --git a/vendor/go.uber.org/zap/.readme.tmpl b/vendor/go.uber.org/zap/.readme.tmpl new file mode 100644 index 00000000..92aa65d6 --- /dev/null +++ b/vendor/go.uber.org/zap/.readme.tmpl @@ -0,0 +1,109 @@ +# :zap: zap [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] + +Blazing fast, structured, leveled logging in Go. + +## Installation + +`go get -u go.uber.org/zap` + +Note that zap only supports the two most recent minor versions of Go. + +## Quick Start + +In contexts where performance is nice, but not critical, use the +`SugaredLogger`. It's 4-10x faster than other structured logging +packages and includes both structured and `printf`-style APIs. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() // flushes buffer, if any +sugar := logger.Sugar() +sugar.Infow("failed to fetch URL", + // Structured context as loosely typed key-value pairs. + "url", url, + "attempt", 3, + "backoff", time.Second, +) +sugar.Infof("Failed to fetch URL: %s", url) +``` + +When performance and type safety are critical, use the `Logger`. It's even +faster than the `SugaredLogger` and allocates far less, but it only supports +structured logging. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() +logger.Info("failed to fetch URL", + // Structured context as strongly typed Field values. + zap.String("url", url), + zap.Int("attempt", 3), + zap.Duration("backoff", time.Second), +) +``` + +See the [documentation][doc] and [FAQ](FAQ.md) for more details. + +## Performance + +For applications that log in the hot path, reflection-based serialization and +string formatting are prohibitively expensive — they're CPU-intensive +and make many small allocations. Put differently, using `encoding/json` and +`fmt.Fprintf` to log tons of `interface{}`s makes your application slow. + +Zap takes a different approach. It includes a reflection-free, zero-allocation +JSON encoder, and the base `Logger` strives to avoid serialization overhead +and allocations wherever possible. By building the high-level `SugaredLogger` +on that foundation, zap lets users *choose* when they need to count every +allocation and when they'd prefer a more familiar, loosely typed API. + +As measured by its own [benchmarking suite][], not only is zap more performant +than comparable structured logging packages — it's also faster than the +standard library. Like all benchmarks, take these with a grain of salt.[1](#footnote-versions) + +Log a message and 10 fields: + +{{.BenchmarkAddingFields}} + +Log a message with a logger that already has 10 fields of context: + +{{.BenchmarkAccumulatedContext}} + +Log a static string, without any context or `printf`-style templating: + +{{.BenchmarkWithoutFields}} + +## Development Status: Stable + +All APIs are finalized, and no breaking changes will be made in the 1.x series +of releases. Users of semver-aware dependency management systems should pin +zap to `^1`. + +## Contributing + +We encourage and support an active, healthy community of contributors — +including you! Details are in the [contribution guide](CONTRIBUTING.md) and +the [code of conduct](CODE_OF_CONDUCT.md). The zap maintainers keep an eye on +issues and pull requests, but you can also report any negative conduct to +oss-conduct@uber.com. That email list is a private, safe space; even the zap +maintainers don't have access, so don't hesitate to hold us to a high +standard. + +
+ +Released under the [MIT License](LICENSE.txt). + +1 In particular, keep in mind that we may be +benchmarking against slightly older versions of other packages. Versions are +pinned in the [benchmarks/go.mod][] file. [↩](#anchor-versions) + +[doc-img]: https://pkg.go.dev/badge/go.uber.org/zap +[doc]: https://pkg.go.dev/go.uber.org/zap +[ci-img]: https://github.com/uber-go/zap/actions/workflows/go.yml/badge.svg +[ci]: https://github.com/uber-go/zap/actions/workflows/go.yml +[cov-img]: https://codecov.io/gh/uber-go/zap/branch/master/graph/badge.svg +[cov]: https://codecov.io/gh/uber-go/zap +[benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks +[benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod + diff --git a/vendor/go.uber.org/zap/CHANGELOG.md b/vendor/go.uber.org/zap/CHANGELOG.md new file mode 100644 index 00000000..11b46597 --- /dev/null +++ b/vendor/go.uber.org/zap/CHANGELOG.md @@ -0,0 +1,671 @@ +# Changelog +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## 1.26.0 (14 Sep 2023) +Enhancements: +* [#1319][]: Add `WithLazy` method to `Logger` which lazily evaluates the structured +context. +* [#1350][]: String encoding is much (~50%) faster now. + +Thanks to @jquirke, @cdvr1993 for their contributions to this release. + +[#1319]: https://github.com/uber-go/zap/pull/1319 +[#1350]: https://github.com/uber-go/zap/pull/1350 + +## 1.25.0 (1 Aug 2023) + +This release contains several improvements including performance, API additions, +and two new experimental packages whose APIs are unstable and may change in the +future. + +Enhancements: +* [#1246][]: Add `zap/exp/zapslog` package for integration with slog. +* [#1273][]: Add `Name` to `Logger` which returns the Logger's name if one is set. +* [#1281][]: Add `zap/exp/expfield` package which contains helper methods +`Str` and `Strs` for constructing String-like zap.Fields. +* [#1310][]: Reduce stack size on `Any`. + +Thanks to @knight42, @dzakaammar, @bcspragu, and @rexywork for their contributions +to this release. + +[#1246]: https://github.com/uber-go/zap/pull/1246 +[#1273]: https://github.com/uber-go/zap/pull/1273 +[#1281]: https://github.com/uber-go/zap/pull/1281 +[#1310]: https://github.com/uber-go/zap/pull/1310 + +## 1.24.0 (30 Nov 2022) + +Enhancements: +* [#1148][]: Add `Level` to both `Logger` and `SugaredLogger` that reports the + current minimum enabled log level. +* [#1185][]: `SugaredLogger` turns errors to zap.Error automatically. + +Thanks to @Abirdcfly, @craigpastro, @nnnkkk7, and @sashamelentyev for their +contributions to this release. + +[#1148]: https://github.coml/uber-go/zap/pull/1148 +[#1185]: https://github.coml/uber-go/zap/pull/1185 + +## 1.23.0 (24 Aug 2022) + +Enhancements: +* [#1147][]: Add a `zapcore.LevelOf` function to determine the level of a + `LevelEnabler` or `Core`. +* [#1155][]: Add `zap.Stringers` field constructor to log arrays of objects + that implement `String() string`. + +[#1147]: https://github.com/uber-go/zap/pull/1147 +[#1155]: https://github.com/uber-go/zap/pull/1155 + +## 1.22.0 (8 Aug 2022) + +Enhancements: +* [#1071][]: Add `zap.Objects` and `zap.ObjectValues` field constructors to log + arrays of objects. With these two constructors, you don't need to implement + `zapcore.ArrayMarshaler` for use with `zap.Array` if those objects implement + `zapcore.ObjectMarshaler`. +* [#1079][]: Add `SugaredLogger.WithOptions` to build a copy of an existing + `SugaredLogger` with the provided options applied. +* [#1080][]: Add `*ln` variants to `SugaredLogger` for each log level. + These functions provide a string joining behavior similar to `fmt.Println`. +* [#1088][]: Add `zap.WithFatalHook` option to control the behavior of the + logger for `Fatal`-level log entries. This defaults to exiting the program. +* [#1108][]: Add a `zap.Must` function that you can use with `NewProduction` or + `NewDevelopment` to panic if the system was unable to build the logger. +* [#1118][]: Add a `Logger.Log` method that allows specifying the log level for + a statement dynamically. + +Thanks to @cardil, @craigpastro, @sashamelentyev, @shota3506, and @zhupeijun +for their contributions to this release. + +[#1071]: https://github.com/uber-go/zap/pull/1071 +[#1079]: https://github.com/uber-go/zap/pull/1079 +[#1080]: https://github.com/uber-go/zap/pull/1080 +[#1088]: https://github.com/uber-go/zap/pull/1088 +[#1108]: https://github.com/uber-go/zap/pull/1108 +[#1118]: https://github.com/uber-go/zap/pull/1118 + +## 1.21.0 (7 Feb 2022) + +Enhancements: +* [#1047][]: Add `zapcore.ParseLevel` to parse a `Level` from a string. +* [#1048][]: Add `zap.ParseAtomicLevel` to parse an `AtomicLevel` from a + string. + +Bugfixes: +* [#1058][]: Fix panic in JSON encoder when `EncodeLevel` is unset. + +Other changes: +* [#1052][]: Improve encoding performance when the `AddCaller` and + `AddStacktrace` options are used together. + +[#1047]: https://github.com/uber-go/zap/pull/1047 +[#1048]: https://github.com/uber-go/zap/pull/1048 +[#1052]: https://github.com/uber-go/zap/pull/1052 +[#1058]: https://github.com/uber-go/zap/pull/1058 + +Thanks to @aerosol and @Techassi for their contributions to this release. + +## 1.20.0 (4 Jan 2022) + +Enhancements: +* [#989][]: Add `EncoderConfig.SkipLineEnding` flag to disable adding newline + characters between log statements. +* [#1039][]: Add `EncoderConfig.NewReflectedEncoder` field to customize JSON + encoding of reflected log fields. + +Bugfixes: +* [#1011][]: Fix inaccurate precision when encoding complex64 as JSON. +* [#554][], [#1017][]: Close JSON namespaces opened in `MarshalLogObject` + methods when the methods return. +* [#1033][]: Avoid panicking in Sampler core if `thereafter` is zero. + +Other changes: +* [#1028][]: Drop support for Go < 1.15. + +[#554]: https://github.com/uber-go/zap/pull/554 +[#989]: https://github.com/uber-go/zap/pull/989 +[#1011]: https://github.com/uber-go/zap/pull/1011 +[#1017]: https://github.com/uber-go/zap/pull/1017 +[#1028]: https://github.com/uber-go/zap/pull/1028 +[#1033]: https://github.com/uber-go/zap/pull/1033 +[#1039]: https://github.com/uber-go/zap/pull/1039 + +Thanks to @psrajat, @lruggieri, @sammyrnycreal for their contributions to this release. + +## 1.19.1 (8 Sep 2021) + +Bugfixes: +* [#1001][]: JSON: Fix complex number encoding with negative imaginary part. Thanks to @hemantjadon. +* [#1003][]: JSON: Fix inaccurate precision when encoding float32. + +[#1001]: https://github.com/uber-go/zap/pull/1001 +[#1003]: https://github.com/uber-go/zap/pull/1003 + +## 1.19.0 (9 Aug 2021) + +Enhancements: +* [#975][]: Avoid panicking in Sampler core if the level is out of bounds. +* [#984][]: Reduce the size of BufferedWriteSyncer by aligning the fields + better. + +[#975]: https://github.com/uber-go/zap/pull/975 +[#984]: https://github.com/uber-go/zap/pull/984 + +Thanks to @lancoLiu and @thockin for their contributions to this release. + +## 1.18.1 (28 Jun 2021) + +Bugfixes: +* [#974][]: Fix nil dereference in logger constructed by `zap.NewNop`. + +[#974]: https://github.com/uber-go/zap/pull/974 + +## 1.18.0 (28 Jun 2021) + +Enhancements: +* [#961][]: Add `zapcore.BufferedWriteSyncer`, a new `WriteSyncer` that buffers + messages in-memory and flushes them periodically. +* [#971][]: Add `zapio.Writer` to use a Zap logger as an `io.Writer`. +* [#897][]: Add `zap.WithClock` option to control the source of time via the + new `zapcore.Clock` interface. +* [#949][]: Avoid panicking in `zap.SugaredLogger` when arguments of `*w` + methods don't match expectations. +* [#943][]: Add support for filtering by level or arbitrary matcher function to + `zaptest/observer`. +* [#691][]: Comply with `io.StringWriter` and `io.ByteWriter` in Zap's + `buffer.Buffer`. + +Thanks to @atrn0, @ernado, @heyanfu, @hnlq715, @zchee +for their contributions to this release. + +[#691]: https://github.com/uber-go/zap/pull/691 +[#897]: https://github.com/uber-go/zap/pull/897 +[#943]: https://github.com/uber-go/zap/pull/943 +[#949]: https://github.com/uber-go/zap/pull/949 +[#961]: https://github.com/uber-go/zap/pull/961 +[#971]: https://github.com/uber-go/zap/pull/971 + +## 1.17.0 (25 May 2021) + +Bugfixes: +* [#867][]: Encode `` for nil `error` instead of a panic. +* [#931][], [#936][]: Update minimum version constraints to address + vulnerabilities in dependencies. + +Enhancements: +* [#865][]: Improve alignment of fields of the Logger struct, reducing its + size from 96 to 80 bytes. +* [#881][]: Support `grpclog.LoggerV2` in zapgrpc. +* [#903][]: Support URL-encoded POST requests to the AtomicLevel HTTP handler + with the `application/x-www-form-urlencoded` content type. +* [#912][]: Support multi-field encoding with `zap.Inline`. +* [#913][]: Speed up SugaredLogger for calls with a single string. +* [#928][]: Add support for filtering by field name to `zaptest/observer`. + +Thanks to @ash2k, @FMLS, @jimmystewpot, @Oncilla, @tsoslow, @tylitianrui, @withshubh, and @wziww for their contributions to this release. + +[#865]: https://github.com/uber-go/zap/pull/865 +[#867]: https://github.com/uber-go/zap/pull/867 +[#881]: https://github.com/uber-go/zap/pull/881 +[#903]: https://github.com/uber-go/zap/pull/903 +[#912]: https://github.com/uber-go/zap/pull/912 +[#913]: https://github.com/uber-go/zap/pull/913 +[#928]: https://github.com/uber-go/zap/pull/928 +[#931]: https://github.com/uber-go/zap/pull/931 +[#936]: https://github.com/uber-go/zap/pull/936 + +## 1.16.0 (1 Sep 2020) + +Bugfixes: +* [#828][]: Fix missing newline in IncreaseLevel error messages. +* [#835][]: Fix panic in JSON encoder when encoding times or durations + without specifying a time or duration encoder. +* [#843][]: Honor CallerSkip when taking stack traces. +* [#862][]: Fix the default file permissions to use `0666` and rely on the umask instead. +* [#854][]: Encode `` for nil `Stringer` instead of a panic error log. + +Enhancements: +* [#629][]: Added `zapcore.TimeEncoderOfLayout` to easily create time encoders + for custom layouts. +* [#697][]: Added support for a configurable delimiter in the console encoder. +* [#852][]: Optimize console encoder by pooling the underlying JSON encoder. +* [#844][]: Add ability to include the calling function as part of logs. +* [#843][]: Add `StackSkip` for including truncated stacks as a field. +* [#861][]: Add options to customize Fatal behaviour for better testability. + +Thanks to @SteelPhase, @tmshn, @lixingwang, @wyxloading, @moul, @segevfiner, @andy-retailnext and @jcorbin for their contributions to this release. + +[#629]: https://github.com/uber-go/zap/pull/629 +[#697]: https://github.com/uber-go/zap/pull/697 +[#828]: https://github.com/uber-go/zap/pull/828 +[#835]: https://github.com/uber-go/zap/pull/835 +[#843]: https://github.com/uber-go/zap/pull/843 +[#844]: https://github.com/uber-go/zap/pull/844 +[#852]: https://github.com/uber-go/zap/pull/852 +[#854]: https://github.com/uber-go/zap/pull/854 +[#861]: https://github.com/uber-go/zap/pull/861 +[#862]: https://github.com/uber-go/zap/pull/862 + +## 1.15.0 (23 Apr 2020) + +Bugfixes: +* [#804][]: Fix handling of `Time` values out of `UnixNano` range. +* [#812][]: Fix `IncreaseLevel` being reset after a call to `With`. + +Enhancements: +* [#806][]: Add `WithCaller` option to supersede the `AddCaller` option. This + allows disabling annotation of log entries with caller information if + previously enabled with `AddCaller`. +* [#813][]: Deprecate `NewSampler` constructor in favor of + `NewSamplerWithOptions` which supports a `SamplerHook` option. This option + adds support for monitoring sampling decisions through a hook. + +Thanks to @danielbprice for their contributions to this release. + +[#804]: https://github.com/uber-go/zap/pull/804 +[#812]: https://github.com/uber-go/zap/pull/812 +[#806]: https://github.com/uber-go/zap/pull/806 +[#813]: https://github.com/uber-go/zap/pull/813 + +## 1.14.1 (14 Mar 2020) + +Bugfixes: +* [#791][]: Fix panic on attempting to build a logger with an invalid Config. +* [#795][]: Vendoring Zap with `go mod vendor` no longer includes Zap's + development-time dependencies. +* [#799][]: Fix issue introduced in 1.14.0 that caused invalid JSON output to + be generated for arrays of `time.Time` objects when using string-based time + formats. + +Thanks to @YashishDua for their contributions to this release. + +[#791]: https://github.com/uber-go/zap/pull/791 +[#795]: https://github.com/uber-go/zap/pull/795 +[#799]: https://github.com/uber-go/zap/pull/799 + +## 1.14.0 (20 Feb 2020) + +Enhancements: +* [#771][]: Optimize calls for disabled log levels. +* [#773][]: Add millisecond duration encoder. +* [#775][]: Add option to increase the level of a logger. +* [#786][]: Optimize time formatters using `Time.AppendFormat` where possible. + +Thanks to @caibirdme for their contributions to this release. + +[#771]: https://github.com/uber-go/zap/pull/771 +[#773]: https://github.com/uber-go/zap/pull/773 +[#775]: https://github.com/uber-go/zap/pull/775 +[#786]: https://github.com/uber-go/zap/pull/786 + +## 1.13.0 (13 Nov 2019) + +Enhancements: +* [#758][]: Add `Intp`, `Stringp`, and other similar `*p` field constructors + to log pointers to primitives with support for `nil` values. + +Thanks to @jbizzle for their contributions to this release. + +[#758]: https://github.com/uber-go/zap/pull/758 + +## 1.12.0 (29 Oct 2019) + +Enhancements: +* [#751][]: Migrate to Go modules. + +[#751]: https://github.com/uber-go/zap/pull/751 + +## 1.11.0 (21 Oct 2019) + +Enhancements: +* [#725][]: Add `zapcore.OmitKey` to omit keys in an `EncoderConfig`. +* [#736][]: Add `RFC3339` and `RFC3339Nano` time encoders. + +Thanks to @juicemia, @uhthomas for their contributions to this release. + +[#725]: https://github.com/uber-go/zap/pull/725 +[#736]: https://github.com/uber-go/zap/pull/736 + +## 1.10.0 (29 Apr 2019) + +Bugfixes: +* [#657][]: Fix `MapObjectEncoder.AppendByteString` not adding value as a + string. +* [#706][]: Fix incorrect call depth to determine caller in Go 1.12. + +Enhancements: +* [#610][]: Add `zaptest.WrapOptions` to wrap `zap.Option` for creating test + loggers. +* [#675][]: Don't panic when encoding a String field. +* [#704][]: Disable HTML escaping for JSON objects encoded using the + reflect-based encoder. + +Thanks to @iaroslav-ciupin, @lelenanam, @joa, @NWilson for their contributions +to this release. + +[#657]: https://github.com/uber-go/zap/pull/657 +[#706]: https://github.com/uber-go/zap/pull/706 +[#610]: https://github.com/uber-go/zap/pull/610 +[#675]: https://github.com/uber-go/zap/pull/675 +[#704]: https://github.com/uber-go/zap/pull/704 + +## v1.9.1 (06 Aug 2018) + +Bugfixes: + +* [#614][]: MapObjectEncoder should not ignore empty slices. + +[#614]: https://github.com/uber-go/zap/pull/614 + +## v1.9.0 (19 Jul 2018) + +Enhancements: +* [#602][]: Reduce number of allocations when logging with reflection. +* [#572][], [#606][]: Expose a registry for third-party logging sinks. + +Thanks to @nfarah86, @AlekSi, @JeanMertz, @philippgille, @etsangsplk, and +@dimroc for their contributions to this release. + +[#602]: https://github.com/uber-go/zap/pull/602 +[#572]: https://github.com/uber-go/zap/pull/572 +[#606]: https://github.com/uber-go/zap/pull/606 + +## v1.8.0 (13 Apr 2018) + +Enhancements: +* [#508][]: Make log level configurable when redirecting the standard + library's logger. +* [#518][]: Add a logger that writes to a `*testing.TB`. +* [#577][]: Add a top-level alias for `zapcore.Field` to clean up GoDoc. + +Bugfixes: +* [#574][]: Add a missing import comment to `go.uber.org/zap/buffer`. + +Thanks to @DiSiqueira and @djui for their contributions to this release. + +[#508]: https://github.com/uber-go/zap/pull/508 +[#518]: https://github.com/uber-go/zap/pull/518 +[#577]: https://github.com/uber-go/zap/pull/577 +[#574]: https://github.com/uber-go/zap/pull/574 + +## v1.7.1 (25 Sep 2017) + +Bugfixes: +* [#504][]: Store strings when using AddByteString with the map encoder. + +[#504]: https://github.com/uber-go/zap/pull/504 + +## v1.7.0 (21 Sep 2017) + +Enhancements: + +* [#487][]: Add `NewStdLogAt`, which extends `NewStdLog` by allowing the user + to specify the level of the logged messages. + +[#487]: https://github.com/uber-go/zap/pull/487 + +## v1.6.0 (30 Aug 2017) + +Enhancements: + +* [#491][]: Omit zap stack frames from stacktraces. +* [#490][]: Add a `ContextMap` method to observer logs for simpler + field validation in tests. + +[#490]: https://github.com/uber-go/zap/pull/490 +[#491]: https://github.com/uber-go/zap/pull/491 + +## v1.5.0 (22 Jul 2017) + +Enhancements: + +* [#460][] and [#470][]: Support errors produced by `go.uber.org/multierr`. +* [#465][]: Support user-supplied encoders for logger names. + +Bugfixes: + +* [#477][]: Fix a bug that incorrectly truncated deep stacktraces. + +Thanks to @richard-tunein and @pavius for their contributions to this release. + +[#477]: https://github.com/uber-go/zap/pull/477 +[#465]: https://github.com/uber-go/zap/pull/465 +[#460]: https://github.com/uber-go/zap/pull/460 +[#470]: https://github.com/uber-go/zap/pull/470 + +## v1.4.1 (08 Jun 2017) + +This release fixes two bugs. + +Bugfixes: + +* [#435][]: Support a variety of case conventions when unmarshaling levels. +* [#444][]: Fix a panic in the observer. + +[#435]: https://github.com/uber-go/zap/pull/435 +[#444]: https://github.com/uber-go/zap/pull/444 + +## v1.4.0 (12 May 2017) + +This release adds a few small features and is fully backward-compatible. + +Enhancements: + +* [#424][]: Add a `LineEnding` field to `EncoderConfig`, allowing users to + override the Unix-style default. +* [#425][]: Preserve time zones when logging times. +* [#431][]: Make `zap.AtomicLevel` implement `fmt.Stringer`, which makes a + variety of operations a bit simpler. + +[#424]: https://github.com/uber-go/zap/pull/424 +[#425]: https://github.com/uber-go/zap/pull/425 +[#431]: https://github.com/uber-go/zap/pull/431 + +## v1.3.0 (25 Apr 2017) + +This release adds an enhancement to zap's testing helpers as well as the +ability to marshal an AtomicLevel. It is fully backward-compatible. + +Enhancements: + +* [#415][]: Add a substring-filtering helper to zap's observer. This is + particularly useful when testing the `SugaredLogger`. +* [#416][]: Make `AtomicLevel` implement `encoding.TextMarshaler`. + +[#415]: https://github.com/uber-go/zap/pull/415 +[#416]: https://github.com/uber-go/zap/pull/416 + +## v1.2.0 (13 Apr 2017) + +This release adds a gRPC compatibility wrapper. It is fully backward-compatible. + +Enhancements: + +* [#402][]: Add a `zapgrpc` package that wraps zap's Logger and implements + `grpclog.Logger`. + +[#402]: https://github.com/uber-go/zap/pull/402 + +## v1.1.0 (31 Mar 2017) + +This release fixes two bugs and adds some enhancements to zap's testing helpers. +It is fully backward-compatible. + +Bugfixes: + +* [#385][]: Fix caller path trimming on Windows. +* [#396][]: Fix a panic when attempting to use non-existent directories with + zap's configuration struct. + +Enhancements: + +* [#386][]: Add filtering helpers to zaptest's observing logger. + +Thanks to @moitias for contributing to this release. + +[#385]: https://github.com/uber-go/zap/pull/385 +[#396]: https://github.com/uber-go/zap/pull/396 +[#386]: https://github.com/uber-go/zap/pull/386 + +## v1.0.0 (14 Mar 2017) + +This is zap's first stable release. All exported APIs are now final, and no +further breaking changes will be made in the 1.x release series. Anyone using a +semver-aware dependency manager should now pin to `^1`. + +Breaking changes: + +* [#366][]: Add byte-oriented APIs to encoders to log UTF-8 encoded text without + casting from `[]byte` to `string`. +* [#364][]: To support buffering outputs, add `Sync` methods to `zapcore.Core`, + `zap.Logger`, and `zap.SugaredLogger`. +* [#371][]: Rename the `testutils` package to `zaptest`, which is less likely to + clash with other testing helpers. + +Bugfixes: + +* [#362][]: Make the ISO8601 time formatters fixed-width, which is friendlier + for tab-separated console output. +* [#369][]: Remove the automatic locks in `zapcore.NewCore`, which allows zap to + work with concurrency-safe `WriteSyncer` implementations. +* [#347][]: Stop reporting errors when trying to `fsync` standard out on Linux + systems. +* [#373][]: Report the correct caller from zap's standard library + interoperability wrappers. + +Enhancements: + +* [#348][]: Add a registry allowing third-party encodings to work with zap's + built-in `Config`. +* [#327][]: Make the representation of logger callers configurable (like times, + levels, and durations). +* [#376][]: Allow third-party encoders to use their own buffer pools, which + removes the last performance advantage that zap's encoders have over plugins. +* [#346][]: Add `CombineWriteSyncers`, a convenience function to tee multiple + `WriteSyncer`s and lock the result. +* [#365][]: Make zap's stacktraces compatible with mid-stack inlining (coming in + Go 1.9). +* [#372][]: Export zap's observing logger as `zaptest/observer`. This makes it + easier for particularly punctilious users to unit test their application's + logging. + +Thanks to @suyash, @htrendev, @flisky, @Ulexus, and @skipor for their +contributions to this release. + +[#366]: https://github.com/uber-go/zap/pull/366 +[#364]: https://github.com/uber-go/zap/pull/364 +[#371]: https://github.com/uber-go/zap/pull/371 +[#362]: https://github.com/uber-go/zap/pull/362 +[#369]: https://github.com/uber-go/zap/pull/369 +[#347]: https://github.com/uber-go/zap/pull/347 +[#373]: https://github.com/uber-go/zap/pull/373 +[#348]: https://github.com/uber-go/zap/pull/348 +[#327]: https://github.com/uber-go/zap/pull/327 +[#376]: https://github.com/uber-go/zap/pull/376 +[#346]: https://github.com/uber-go/zap/pull/346 +[#365]: https://github.com/uber-go/zap/pull/365 +[#372]: https://github.com/uber-go/zap/pull/372 + +## v1.0.0-rc.3 (7 Mar 2017) + +This is the third release candidate for zap's stable release. There are no +breaking changes. + +Bugfixes: + +* [#339][]: Byte slices passed to `zap.Any` are now correctly treated as binary blobs + rather than `[]uint8`. + +Enhancements: + +* [#307][]: Users can opt into colored output for log levels. +* [#353][]: In addition to hijacking the output of the standard library's + package-global logging functions, users can now construct a zap-backed + `log.Logger` instance. +* [#311][]: Frames from common runtime functions and some of zap's internal + machinery are now omitted from stacktraces. + +Thanks to @ansel1 and @suyash for their contributions to this release. + +[#339]: https://github.com/uber-go/zap/pull/339 +[#307]: https://github.com/uber-go/zap/pull/307 +[#353]: https://github.com/uber-go/zap/pull/353 +[#311]: https://github.com/uber-go/zap/pull/311 + +## v1.0.0-rc.2 (21 Feb 2017) + +This is the second release candidate for zap's stable release. It includes two +breaking changes. + +Breaking changes: + +* [#316][]: Zap's global loggers are now fully concurrency-safe + (previously, users had to ensure that `ReplaceGlobals` was called before the + loggers were in use). However, they must now be accessed via the `L()` and + `S()` functions. Users can update their projects with + + ``` + gofmt -r "zap.L -> zap.L()" -w . + gofmt -r "zap.S -> zap.S()" -w . + ``` +* [#309][] and [#317][]: RC1 was mistakenly shipped with invalid + JSON and YAML struct tags on all config structs. This release fixes the tags + and adds static analysis to prevent similar bugs in the future. + +Bugfixes: + +* [#321][]: Redirecting the standard library's `log` output now + correctly reports the logger's caller. + +Enhancements: + +* [#325][] and [#333][]: Zap now transparently supports non-standard, rich + errors like those produced by `github.com/pkg/errors`. +* [#326][]: Though `New(nil)` continues to return a no-op logger, `NewNop()` is + now preferred. Users can update their projects with `gofmt -r 'zap.New(nil) -> + zap.NewNop()' -w .`. +* [#300][]: Incorrectly importing zap as `github.com/uber-go/zap` now returns a + more informative error. + +Thanks to @skipor and @chapsuk for their contributions to this release. + +[#316]: https://github.com/uber-go/zap/pull/316 +[#309]: https://github.com/uber-go/zap/pull/309 +[#317]: https://github.com/uber-go/zap/pull/317 +[#321]: https://github.com/uber-go/zap/pull/321 +[#325]: https://github.com/uber-go/zap/pull/325 +[#333]: https://github.com/uber-go/zap/pull/333 +[#326]: https://github.com/uber-go/zap/pull/326 +[#300]: https://github.com/uber-go/zap/pull/300 + +## v1.0.0-rc.1 (14 Feb 2017) + +This is the first release candidate for zap's stable release. There are multiple +breaking changes and improvements from the pre-release version. Most notably: + +* **Zap's import path is now "go.uber.org/zap"** — all users will + need to update their code. +* User-facing types and functions remain in the `zap` package. Code relevant + largely to extension authors is now in the `zapcore` package. +* The `zapcore.Core` type makes it easy for third-party packages to use zap's + internals but provide a different user-facing API. +* `Logger` is now a concrete type instead of an interface. +* A less verbose (though slower) logging API is included by default. +* Package-global loggers `L` and `S` are included. +* A human-friendly console encoder is included. +* A declarative config struct allows common logger configurations to be managed + as configuration instead of code. +* Sampling is more accurate, and doesn't depend on the standard library's shared + timer heap. + +## v0.1.0-beta.1 (6 Feb 2017) + +This is a minor version, tagged to allow users to pin to the pre-1.0 APIs and +upgrade at their leisure. Since this is the first tagged release, there are no +backward compatibility concerns and all functionality is new. + +Early zap adopters should pin to the 0.1.x minor version until they're ready to +upgrade to the upcoming stable release. diff --git a/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md b/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..e327d9aa --- /dev/null +++ b/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md @@ -0,0 +1,75 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, +body size, disability, ethnicity, gender identity and expression, level of +experience, nationality, personal appearance, race, religion, or sexual +identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an +appointed representative at an online or offline event. Representation of a +project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at oss-conduct@uber.com. The project +team will review and investigate all complaints, and will respond in a way +that it deems appropriate to the circumstances. The project team is obligated +to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at +[http://contributor-covenant.org/version/1/4][version]. + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/go.uber.org/zap/CONTRIBUTING.md b/vendor/go.uber.org/zap/CONTRIBUTING.md new file mode 100644 index 00000000..ea02f3ca --- /dev/null +++ b/vendor/go.uber.org/zap/CONTRIBUTING.md @@ -0,0 +1,70 @@ +# Contributing + +We'd love your help making zap the very best structured logging library in Go! + +If you'd like to add new exported APIs, please [open an issue][open-issue] +describing your proposal — discussing API changes ahead of time makes +pull request review much smoother. In your issue, pull request, and any other +communications, please remember to treat your fellow contributors with +respect! We take our [code of conduct](CODE_OF_CONDUCT.md) seriously. + +Note that you'll need to sign [Uber's Contributor License Agreement][cla] +before we can accept any of your contributions. If necessary, a bot will remind +you to accept the CLA when you open your pull request. + +## Setup + +[Fork][fork], then clone the repository: + +```bash +mkdir -p $GOPATH/src/go.uber.org +cd $GOPATH/src/go.uber.org +git clone git@github.com:your_github_username/zap.git +cd zap +git remote add upstream https://github.com/uber-go/zap.git +git fetch upstream +``` + +Make sure that the tests and the linters pass: + +```bash +make test +make lint +``` + +## Making Changes + +Start by creating a new branch for your changes: + +```bash +cd $GOPATH/src/go.uber.org/zap +git checkout master +git fetch upstream +git rebase upstream/master +git checkout -b cool_new_feature +``` + +Make your changes, then ensure that `make lint` and `make test` still pass. If +you're satisfied with your changes, push them to your fork. + +```bash +git push origin cool_new_feature +``` + +Then use the GitHub UI to open a pull request. + +At this point, you're waiting on us to review your changes. We _try_ to respond +to issues and pull requests within a few business days, and we may suggest some +improvements or alternatives. Once your changes are approved, one of the +project maintainers will merge them. + +We're much more likely to approve your changes if you: + +- Add tests for new functionality. +- Write a [good commit message][commit-message]. +- Maintain backward compatibility. + +[fork]: https://github.com/uber-go/zap/fork +[open-issue]: https://github.com/uber-go/zap/issues/new +[cla]: https://cla-assistant.io/uber-go/zap +[commit-message]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html diff --git a/vendor/go.uber.org/zap/FAQ.md b/vendor/go.uber.org/zap/FAQ.md new file mode 100644 index 00000000..b183b20b --- /dev/null +++ b/vendor/go.uber.org/zap/FAQ.md @@ -0,0 +1,164 @@ +# Frequently Asked Questions + +## Design + +### Why spend so much effort on logger performance? + +Of course, most applications won't notice the impact of a slow logger: they +already take tens or hundreds of milliseconds for each operation, so an extra +millisecond doesn't matter. + +On the other hand, why *not* make structured logging fast? The `SugaredLogger` +isn't any harder to use than other logging packages, and the `Logger` makes +structured logging possible in performance-sensitive contexts. Across a fleet +of Go microservices, making each application even slightly more efficient adds +up quickly. + +### Why aren't `Logger` and `SugaredLogger` interfaces? + +Unlike the familiar `io.Writer` and `http.Handler`, `Logger` and +`SugaredLogger` interfaces would include *many* methods. As [Rob Pike points +out][go-proverbs], "The bigger the interface, the weaker the abstraction." +Interfaces are also rigid — *any* change requires releasing a new major +version, since it breaks all third-party implementations. + +Making the `Logger` and `SugaredLogger` concrete types doesn't sacrifice much +abstraction, and it lets us add methods without introducing breaking changes. +Your applications should define and depend upon an interface that includes +just the methods you use. + +### Why are some of my logs missing? + +Logs are dropped intentionally by zap when sampling is enabled. The production +configuration (as returned by `NewProductionConfig()` enables sampling which will +cause repeated logs within a second to be sampled. See more details on why sampling +is enabled in [Why sample application logs](https://github.com/uber-go/zap/blob/master/FAQ.md#why-sample-application-logs). + +### Why sample application logs? + +Applications often experience runs of errors, either because of a bug or +because of a misbehaving user. Logging errors is usually a good idea, but it +can easily make this bad situation worse: not only is your application coping +with a flood of errors, it's also spending extra CPU cycles and I/O logging +those errors. Since writes are typically serialized, logging limits throughput +when you need it most. + +Sampling fixes this problem by dropping repetitive log entries. Under normal +conditions, your application writes out every entry. When similar entries are +logged hundreds or thousands of times each second, though, zap begins dropping +duplicates to preserve throughput. + +### Why do the structured logging APIs take a message in addition to fields? + +Subjectively, we find it helpful to accompany structured context with a brief +description. This isn't critical during development, but it makes debugging +and operating unfamiliar systems much easier. + +More concretely, zap's sampling algorithm uses the message to identify +duplicate entries. In our experience, this is a practical middle ground +between random sampling (which often drops the exact entry that you need while +debugging) and hashing the complete entry (which is prohibitively expensive). + +### Why include package-global loggers? + +Since so many other logging packages include a global logger, many +applications aren't designed to accept loggers as explicit parameters. +Changing function signatures is often a breaking change, so zap includes +global loggers to simplify migration. + +Avoid them where possible. + +### Why include dedicated Panic and Fatal log levels? + +In general, application code should handle errors gracefully instead of using +`panic` or `os.Exit`. However, every rule has exceptions, and it's common to +crash when an error is truly unrecoverable. To avoid losing any information +— especially the reason for the crash — the logger must flush any +buffered entries before the process exits. + +Zap makes this easy by offering `Panic` and `Fatal` logging methods that +automatically flush before exiting. Of course, this doesn't guarantee that +logs will never be lost, but it eliminates a common error. + +See the discussion in uber-go/zap#207 for more details. + +### What's `DPanic`? + +`DPanic` stands for "panic in development." In development, it logs at +`PanicLevel`; otherwise, it logs at `ErrorLevel`. `DPanic` makes it easier to +catch errors that are theoretically possible, but shouldn't actually happen, +*without* crashing in production. + +If you've ever written code like this, you need `DPanic`: + +```go +if err != nil { + panic(fmt.Sprintf("shouldn't ever get here: %v", err)) +} +``` + +## Installation + +### What does the error `expects import "go.uber.org/zap"` mean? + +Either zap was installed incorrectly or you're referencing the wrong package +name in your code. + +Zap's source code happens to be hosted on GitHub, but the [import +path][import-path] is `go.uber.org/zap`. This gives us, the project +maintainers, the freedom to move the source code if necessary. However, it +means that you need to take a little care when installing and using the +package. + +If you follow two simple rules, everything should work: install zap with `go +get -u go.uber.org/zap`, and always import it in your code with `import +"go.uber.org/zap"`. Your code shouldn't contain *any* references to +`github.com/uber-go/zap`. + +## Usage + +### Does zap support log rotation? + +Zap doesn't natively support rotating log files, since we prefer to leave this +to an external program like `logrotate`. + +However, it's easy to integrate a log rotation package like +[`gopkg.in/natefinch/lumberjack.v2`][lumberjack] as a `zapcore.WriteSyncer`. + +```go +// lumberjack.Logger is already safe for concurrent use, so we don't need to +// lock it. +w := zapcore.AddSync(&lumberjack.Logger{ + Filename: "/var/log/myapp/foo.log", + MaxSize: 500, // megabytes + MaxBackups: 3, + MaxAge: 28, // days +}) +core := zapcore.NewCore( + zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), + w, + zap.InfoLevel, +) +logger := zap.New(core) +``` + +## Extensions + +We'd love to support every logging need within zap itself, but we're only +familiar with a handful of log ingestion systems, flag-parsing packages, and +the like. Rather than merging code that we can't effectively debug and +support, we'd rather grow an ecosystem of zap extensions. + +We're aware of the following extensions, but haven't used them ourselves: + +| Package | Integration | +| --- | --- | +| `github.com/tchap/zapext` | Sentry, syslog | +| `github.com/fgrosse/zaptest` | Ginkgo | +| `github.com/blendle/zapdriver` | Stackdriver | +| `github.com/moul/zapgorm` | Gorm | +| `github.com/moul/zapfilter` | Advanced filtering rules | + +[go-proverbs]: https://go-proverbs.github.io/ +[import-path]: https://golang.org/cmd/go/#hdr-Remote_import_paths +[lumberjack]: https://godoc.org/gopkg.in/natefinch/lumberjack.v2 diff --git a/vendor/go.uber.org/zap/LICENSE.txt b/vendor/go.uber.org/zap/LICENSE.txt new file mode 100644 index 00000000..6652bed4 --- /dev/null +++ b/vendor/go.uber.org/zap/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2016-2017 Uber Technologies, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/go.uber.org/zap/Makefile b/vendor/go.uber.org/zap/Makefile new file mode 100644 index 00000000..eb1cee53 --- /dev/null +++ b/vendor/go.uber.org/zap/Makefile @@ -0,0 +1,76 @@ +# Directory containing the Makefile. +PROJECT_ROOT = $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) + +export GOBIN ?= $(PROJECT_ROOT)/bin +export PATH := $(GOBIN):$(PATH) + +GOVULNCHECK = $(GOBIN)/govulncheck +BENCH_FLAGS ?= -cpuprofile=cpu.pprof -memprofile=mem.pprof -benchmem + +# Directories containing independent Go modules. +MODULE_DIRS = . ./exp ./benchmarks ./zapgrpc/internal/test + +# Directories that we want to track coverage for. +COVER_DIRS = . ./exp + +.PHONY: all +all: lint test + +.PHONY: lint +lint: golangci-lint tidy-lint license-lint + +.PHONY: golangci-lint +golangci-lint: + @$(foreach mod,$(MODULE_DIRS), \ + (cd $(mod) && \ + echo "[lint] golangci-lint: $(mod)" && \ + golangci-lint run --path-prefix $(mod)) &&) true + +.PHONY: tidy +tidy: + @$(foreach dir,$(MODULE_DIRS), \ + (cd $(dir) && go mod tidy) &&) true + +.PHONY: tidy-lint +tidy-lint: + @$(foreach mod,$(MODULE_DIRS), \ + (cd $(mod) && \ + echo "[lint] tidy: $(mod)" && \ + go mod tidy && \ + git diff --exit-code -- go.mod go.sum) &&) true + + +.PHONY: license-lint +license-lint: + ./checklicense.sh + +$(GOVULNCHECK): + cd tools && go install golang.org/x/vuln/cmd/govulncheck + +.PHONY: test +test: + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && go test -race ./...) &&) true + +.PHONY: cover +cover: + @$(foreach dir,$(COVER_DIRS), ( \ + cd $(dir) && \ + go test -race -coverprofile=cover.out -coverpkg=./... ./... \ + && go tool cover -html=cover.out -o cover.html) &&) true + +.PHONY: bench +BENCH ?= . +bench: + @$(foreach dir,$(MODULE_DIRS), ( \ + cd $(dir) && \ + go list ./... | xargs -n1 go test -bench=$(BENCH) -run="^$$" $(BENCH_FLAGS) \ + ) &&) true + +.PHONY: updatereadme +updatereadme: + rm -f README.md + cat .readme.tmpl | go run internal/readme/readme.go > README.md + +.PHONY: vulncheck +vulncheck: $(GOVULNCHECK) + $(GOVULNCHECK) ./... diff --git a/vendor/go.uber.org/zap/README.md b/vendor/go.uber.org/zap/README.md new file mode 100644 index 00000000..9de08927 --- /dev/null +++ b/vendor/go.uber.org/zap/README.md @@ -0,0 +1,137 @@ +# :zap: zap [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] + +Blazing fast, structured, leveled logging in Go. + +## Installation + +`go get -u go.uber.org/zap` + +Note that zap only supports the two most recent minor versions of Go. + +## Quick Start + +In contexts where performance is nice, but not critical, use the +`SugaredLogger`. It's 4-10x faster than other structured logging +packages and includes both structured and `printf`-style APIs. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() // flushes buffer, if any +sugar := logger.Sugar() +sugar.Infow("failed to fetch URL", + // Structured context as loosely typed key-value pairs. + "url", url, + "attempt", 3, + "backoff", time.Second, +) +sugar.Infof("Failed to fetch URL: %s", url) +``` + +When performance and type safety are critical, use the `Logger`. It's even +faster than the `SugaredLogger` and allocates far less, but it only supports +structured logging. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() +logger.Info("failed to fetch URL", + // Structured context as strongly typed Field values. + zap.String("url", url), + zap.Int("attempt", 3), + zap.Duration("backoff", time.Second), +) +``` + +See the [documentation][doc] and [FAQ](FAQ.md) for more details. + +## Performance + +For applications that log in the hot path, reflection-based serialization and +string formatting are prohibitively expensive — they're CPU-intensive +and make many small allocations. Put differently, using `encoding/json` and +`fmt.Fprintf` to log tons of `interface{}`s makes your application slow. + +Zap takes a different approach. It includes a reflection-free, zero-allocation +JSON encoder, and the base `Logger` strives to avoid serialization overhead +and allocations wherever possible. By building the high-level `SugaredLogger` +on that foundation, zap lets users *choose* when they need to count every +allocation and when they'd prefer a more familiar, loosely typed API. + +As measured by its own [benchmarking suite][], not only is zap more performant +than comparable structured logging packages — it's also faster than the +standard library. Like all benchmarks, take these with a grain of salt.[1](#footnote-versions) + +Log a message and 10 fields: + +| Package | Time | Time % to zap | Objects Allocated | +| :------ | :--: | :-----------: | :---------------: | +| :zap: zap | 1744 ns/op | +0% | 5 allocs/op +| :zap: zap (sugared) | 2483 ns/op | +42% | 10 allocs/op +| zerolog | 918 ns/op | -47% | 1 allocs/op +| go-kit | 5590 ns/op | +221% | 57 allocs/op +| slog | 5640 ns/op | +223% | 40 allocs/op +| apex/log | 21184 ns/op | +1115% | 63 allocs/op +| logrus | 24338 ns/op | +1296% | 79 allocs/op +| log15 | 26054 ns/op | +1394% | 74 allocs/op + +Log a message with a logger that already has 10 fields of context: + +| Package | Time | Time % to zap | Objects Allocated | +| :------ | :--: | :-----------: | :---------------: | +| :zap: zap | 193 ns/op | +0% | 0 allocs/op +| :zap: zap (sugared) | 227 ns/op | +18% | 1 allocs/op +| zerolog | 81 ns/op | -58% | 0 allocs/op +| slog | 322 ns/op | +67% | 0 allocs/op +| go-kit | 5377 ns/op | +2686% | 56 allocs/op +| apex/log | 19518 ns/op | +10013% | 53 allocs/op +| log15 | 19812 ns/op | +10165% | 70 allocs/op +| logrus | 21997 ns/op | +11297% | 68 allocs/op + +Log a static string, without any context or `printf`-style templating: + +| Package | Time | Time % to zap | Objects Allocated | +| :------ | :--: | :-----------: | :---------------: | +| :zap: zap | 165 ns/op | +0% | 0 allocs/op +| :zap: zap (sugared) | 212 ns/op | +28% | 1 allocs/op +| zerolog | 95 ns/op | -42% | 0 allocs/op +| slog | 296 ns/op | +79% | 0 allocs/op +| go-kit | 415 ns/op | +152% | 9 allocs/op +| standard library | 422 ns/op | +156% | 2 allocs/op +| apex/log | 1601 ns/op | +870% | 5 allocs/op +| logrus | 3017 ns/op | +1728% | 23 allocs/op +| log15 | 3469 ns/op | +2002% | 20 allocs/op + +## Development Status: Stable + +All APIs are finalized, and no breaking changes will be made in the 1.x series +of releases. Users of semver-aware dependency management systems should pin +zap to `^1`. + +## Contributing + +We encourage and support an active, healthy community of contributors — +including you! Details are in the [contribution guide](CONTRIBUTING.md) and +the [code of conduct](CODE_OF_CONDUCT.md). The zap maintainers keep an eye on +issues and pull requests, but you can also report any negative conduct to +oss-conduct@uber.com. That email list is a private, safe space; even the zap +maintainers don't have access, so don't hesitate to hold us to a high +standard. + +
+ +Released under the [MIT License](LICENSE.txt). + +1 In particular, keep in mind that we may be +benchmarking against slightly older versions of other packages. Versions are +pinned in the [benchmarks/go.mod][] file. [↩](#anchor-versions) + +[doc-img]: https://pkg.go.dev/badge/go.uber.org/zap +[doc]: https://pkg.go.dev/go.uber.org/zap +[ci-img]: https://github.com/uber-go/zap/actions/workflows/go.yml/badge.svg +[ci]: https://github.com/uber-go/zap/actions/workflows/go.yml +[cov-img]: https://codecov.io/gh/uber-go/zap/branch/master/graph/badge.svg +[cov]: https://codecov.io/gh/uber-go/zap +[benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks +[benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod + diff --git a/vendor/go.uber.org/zap/array.go b/vendor/go.uber.org/zap/array.go new file mode 100644 index 00000000..abfccb56 --- /dev/null +++ b/vendor/go.uber.org/zap/array.go @@ -0,0 +1,447 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "fmt" + "time" + + "go.uber.org/zap/zapcore" +) + +// Array constructs a field with the given key and ArrayMarshaler. It provides +// a flexible, but still type-safe and efficient, way to add array-like types +// to the logging context. The struct's MarshalLogArray method is called lazily. +func Array(key string, val zapcore.ArrayMarshaler) Field { + return Field{Key: key, Type: zapcore.ArrayMarshalerType, Interface: val} +} + +// Bools constructs a field that carries a slice of bools. +func Bools(key string, bs []bool) Field { + return Array(key, bools(bs)) +} + +// ByteStrings constructs a field that carries a slice of []byte, each of which +// must be UTF-8 encoded text. +func ByteStrings(key string, bss [][]byte) Field { + return Array(key, byteStringsArray(bss)) +} + +// Complex128s constructs a field that carries a slice of complex numbers. +func Complex128s(key string, nums []complex128) Field { + return Array(key, complex128s(nums)) +} + +// Complex64s constructs a field that carries a slice of complex numbers. +func Complex64s(key string, nums []complex64) Field { + return Array(key, complex64s(nums)) +} + +// Durations constructs a field that carries a slice of time.Durations. +func Durations(key string, ds []time.Duration) Field { + return Array(key, durations(ds)) +} + +// Float64s constructs a field that carries a slice of floats. +func Float64s(key string, nums []float64) Field { + return Array(key, float64s(nums)) +} + +// Float32s constructs a field that carries a slice of floats. +func Float32s(key string, nums []float32) Field { + return Array(key, float32s(nums)) +} + +// Ints constructs a field that carries a slice of integers. +func Ints(key string, nums []int) Field { + return Array(key, ints(nums)) +} + +// Int64s constructs a field that carries a slice of integers. +func Int64s(key string, nums []int64) Field { + return Array(key, int64s(nums)) +} + +// Int32s constructs a field that carries a slice of integers. +func Int32s(key string, nums []int32) Field { + return Array(key, int32s(nums)) +} + +// Int16s constructs a field that carries a slice of integers. +func Int16s(key string, nums []int16) Field { + return Array(key, int16s(nums)) +} + +// Int8s constructs a field that carries a slice of integers. +func Int8s(key string, nums []int8) Field { + return Array(key, int8s(nums)) +} + +// Objects constructs a field with the given key, holding a list of the +// provided objects that can be marshaled by Zap. +// +// Note that these objects must implement zapcore.ObjectMarshaler directly. +// That is, if you're trying to marshal a []Request, the MarshalLogObject +// method must be declared on the Request type, not its pointer (*Request). +// If it's on the pointer, use ObjectValues. +// +// Given an object that implements MarshalLogObject on the value receiver, you +// can log a slice of those objects with Objects like so: +// +// type Author struct{ ... } +// func (a Author) MarshalLogObject(enc zapcore.ObjectEncoder) error +// +// var authors []Author = ... +// logger.Info("loading article", zap.Objects("authors", authors)) +// +// Similarly, given a type that implements MarshalLogObject on its pointer +// receiver, you can log a slice of pointers to that object with Objects like +// so: +// +// type Request struct{ ... } +// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error +// +// var requests []*Request = ... +// logger.Info("sending requests", zap.Objects("requests", requests)) +// +// If instead, you have a slice of values of such an object, use the +// ObjectValues constructor. +// +// var requests []Request = ... +// logger.Info("sending requests", zap.ObjectValues("requests", requests)) +func Objects[T zapcore.ObjectMarshaler](key string, values []T) Field { + return Array(key, objects[T](values)) +} + +type objects[T zapcore.ObjectMarshaler] []T + +func (os objects[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for _, o := range os { + if err := arr.AppendObject(o); err != nil { + return err + } + } + return nil +} + +// ObjectMarshalerPtr is a constraint that specifies that the given type +// implements zapcore.ObjectMarshaler on a pointer receiver. +type ObjectMarshalerPtr[T any] interface { + *T + zapcore.ObjectMarshaler +} + +// ObjectValues constructs a field with the given key, holding a list of the +// provided objects, where pointers to these objects can be marshaled by Zap. +// +// Note that pointers to these objects must implement zapcore.ObjectMarshaler. +// That is, if you're trying to marshal a []Request, the MarshalLogObject +// method must be declared on the *Request type, not the value (Request). +// If it's on the value, use Objects. +// +// Given an object that implements MarshalLogObject on the pointer receiver, +// you can log a slice of those objects with ObjectValues like so: +// +// type Request struct{ ... } +// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error +// +// var requests []Request = ... +// logger.Info("sending requests", zap.ObjectValues("requests", requests)) +// +// If instead, you have a slice of pointers of such an object, use the Objects +// field constructor. +// +// var requests []*Request = ... +// logger.Info("sending requests", zap.Objects("requests", requests)) +func ObjectValues[T any, P ObjectMarshalerPtr[T]](key string, values []T) Field { + return Array(key, objectValues[T, P](values)) +} + +type objectValues[T any, P ObjectMarshalerPtr[T]] []T + +func (os objectValues[T, P]) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range os { + // It is necessary for us to explicitly reference the "P" type. + // We cannot simply pass "&os[i]" to AppendObject because its type + // is "*T", which the type system does not consider as + // implementing ObjectMarshaler. + // Only the type "P" satisfies ObjectMarshaler, which we have + // to convert "*T" to explicitly. + var p P = &os[i] + if err := arr.AppendObject(p); err != nil { + return err + } + } + return nil +} + +// Strings constructs a field that carries a slice of strings. +func Strings(key string, ss []string) Field { + return Array(key, stringArray(ss)) +} + +// Stringers constructs a field with the given key, holding a list of the +// output provided by the value's String method +// +// Given an object that implements String on the value receiver, you +// can log a slice of those objects with Objects like so: +// +// type Request struct{ ... } +// func (a Request) String() string +// +// var requests []Request = ... +// logger.Info("sending requests", zap.Stringers("requests", requests)) +// +// Note that these objects must implement fmt.Stringer directly. +// That is, if you're trying to marshal a []Request, the String method +// must be declared on the Request type, not its pointer (*Request). +func Stringers[T fmt.Stringer](key string, values []T) Field { + return Array(key, stringers[T](values)) +} + +type stringers[T fmt.Stringer] []T + +func (os stringers[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for _, o := range os { + arr.AppendString(o.String()) + } + return nil +} + +// Times constructs a field that carries a slice of time.Times. +func Times(key string, ts []time.Time) Field { + return Array(key, times(ts)) +} + +// Uints constructs a field that carries a slice of unsigned integers. +func Uints(key string, nums []uint) Field { + return Array(key, uints(nums)) +} + +// Uint64s constructs a field that carries a slice of unsigned integers. +func Uint64s(key string, nums []uint64) Field { + return Array(key, uint64s(nums)) +} + +// Uint32s constructs a field that carries a slice of unsigned integers. +func Uint32s(key string, nums []uint32) Field { + return Array(key, uint32s(nums)) +} + +// Uint16s constructs a field that carries a slice of unsigned integers. +func Uint16s(key string, nums []uint16) Field { + return Array(key, uint16s(nums)) +} + +// Uint8s constructs a field that carries a slice of unsigned integers. +func Uint8s(key string, nums []uint8) Field { + return Array(key, uint8s(nums)) +} + +// Uintptrs constructs a field that carries a slice of pointer addresses. +func Uintptrs(key string, us []uintptr) Field { + return Array(key, uintptrs(us)) +} + +// Errors constructs a field that carries a slice of errors. +func Errors(key string, errs []error) Field { + return Array(key, errArray(errs)) +} + +type bools []bool + +func (bs bools) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range bs { + arr.AppendBool(bs[i]) + } + return nil +} + +type byteStringsArray [][]byte + +func (bss byteStringsArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range bss { + arr.AppendByteString(bss[i]) + } + return nil +} + +type complex128s []complex128 + +func (nums complex128s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendComplex128(nums[i]) + } + return nil +} + +type complex64s []complex64 + +func (nums complex64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendComplex64(nums[i]) + } + return nil +} + +type durations []time.Duration + +func (ds durations) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range ds { + arr.AppendDuration(ds[i]) + } + return nil +} + +type float64s []float64 + +func (nums float64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendFloat64(nums[i]) + } + return nil +} + +type float32s []float32 + +func (nums float32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendFloat32(nums[i]) + } + return nil +} + +type ints []int + +func (nums ints) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt(nums[i]) + } + return nil +} + +type int64s []int64 + +func (nums int64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt64(nums[i]) + } + return nil +} + +type int32s []int32 + +func (nums int32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt32(nums[i]) + } + return nil +} + +type int16s []int16 + +func (nums int16s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt16(nums[i]) + } + return nil +} + +type int8s []int8 + +func (nums int8s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt8(nums[i]) + } + return nil +} + +type stringArray []string + +func (ss stringArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range ss { + arr.AppendString(ss[i]) + } + return nil +} + +type times []time.Time + +func (ts times) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range ts { + arr.AppendTime(ts[i]) + } + return nil +} + +type uints []uint + +func (nums uints) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint(nums[i]) + } + return nil +} + +type uint64s []uint64 + +func (nums uint64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint64(nums[i]) + } + return nil +} + +type uint32s []uint32 + +func (nums uint32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint32(nums[i]) + } + return nil +} + +type uint16s []uint16 + +func (nums uint16s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint16(nums[i]) + } + return nil +} + +type uint8s []uint8 + +func (nums uint8s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint8(nums[i]) + } + return nil +} + +type uintptrs []uintptr + +func (nums uintptrs) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUintptr(nums[i]) + } + return nil +} diff --git a/vendor/go.uber.org/zap/buffer/buffer.go b/vendor/go.uber.org/zap/buffer/buffer.go new file mode 100644 index 00000000..27fb5cd5 --- /dev/null +++ b/vendor/go.uber.org/zap/buffer/buffer.go @@ -0,0 +1,146 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package buffer provides a thin wrapper around a byte slice. Unlike the +// standard library's bytes.Buffer, it supports a portion of the strconv +// package's zero-allocation formatters. +package buffer // import "go.uber.org/zap/buffer" + +import ( + "strconv" + "time" +) + +const _size = 1024 // by default, create 1 KiB buffers + +// Buffer is a thin wrapper around a byte slice. It's intended to be pooled, so +// the only way to construct one is via a Pool. +type Buffer struct { + bs []byte + pool Pool +} + +// AppendByte writes a single byte to the Buffer. +func (b *Buffer) AppendByte(v byte) { + b.bs = append(b.bs, v) +} + +// AppendBytes writes a single byte to the Buffer. +func (b *Buffer) AppendBytes(v []byte) { + b.bs = append(b.bs, v...) +} + +// AppendString writes a string to the Buffer. +func (b *Buffer) AppendString(s string) { + b.bs = append(b.bs, s...) +} + +// AppendInt appends an integer to the underlying buffer (assuming base 10). +func (b *Buffer) AppendInt(i int64) { + b.bs = strconv.AppendInt(b.bs, i, 10) +} + +// AppendTime appends the time formatted using the specified layout. +func (b *Buffer) AppendTime(t time.Time, layout string) { + b.bs = t.AppendFormat(b.bs, layout) +} + +// AppendUint appends an unsigned integer to the underlying buffer (assuming +// base 10). +func (b *Buffer) AppendUint(i uint64) { + b.bs = strconv.AppendUint(b.bs, i, 10) +} + +// AppendBool appends a bool to the underlying buffer. +func (b *Buffer) AppendBool(v bool) { + b.bs = strconv.AppendBool(b.bs, v) +} + +// AppendFloat appends a float to the underlying buffer. It doesn't quote NaN +// or +/- Inf. +func (b *Buffer) AppendFloat(f float64, bitSize int) { + b.bs = strconv.AppendFloat(b.bs, f, 'f', -1, bitSize) +} + +// Len returns the length of the underlying byte slice. +func (b *Buffer) Len() int { + return len(b.bs) +} + +// Cap returns the capacity of the underlying byte slice. +func (b *Buffer) Cap() int { + return cap(b.bs) +} + +// Bytes returns a mutable reference to the underlying byte slice. +func (b *Buffer) Bytes() []byte { + return b.bs +} + +// String returns a string copy of the underlying byte slice. +func (b *Buffer) String() string { + return string(b.bs) +} + +// Reset resets the underlying byte slice. Subsequent writes re-use the slice's +// backing array. +func (b *Buffer) Reset() { + b.bs = b.bs[:0] +} + +// Write implements io.Writer. +func (b *Buffer) Write(bs []byte) (int, error) { + b.bs = append(b.bs, bs...) + return len(bs), nil +} + +// WriteByte writes a single byte to the Buffer. +// +// Error returned is always nil, function signature is compatible +// with bytes.Buffer and bufio.Writer +func (b *Buffer) WriteByte(v byte) error { + b.AppendByte(v) + return nil +} + +// WriteString writes a string to the Buffer. +// +// Error returned is always nil, function signature is compatible +// with bytes.Buffer and bufio.Writer +func (b *Buffer) WriteString(s string) (int, error) { + b.AppendString(s) + return len(s), nil +} + +// TrimNewline trims any final "\n" byte from the end of the buffer. +func (b *Buffer) TrimNewline() { + if i := len(b.bs) - 1; i >= 0 { + if b.bs[i] == '\n' { + b.bs = b.bs[:i] + } + } +} + +// Free returns the Buffer to its Pool. +// +// Callers must not retain references to the Buffer after calling Free. +func (b *Buffer) Free() { + b.pool.put(b) +} diff --git a/vendor/go.uber.org/zap/buffer/pool.go b/vendor/go.uber.org/zap/buffer/pool.go new file mode 100644 index 00000000..84632336 --- /dev/null +++ b/vendor/go.uber.org/zap/buffer/pool.go @@ -0,0 +1,53 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package buffer + +import ( + "go.uber.org/zap/internal/pool" +) + +// A Pool is a type-safe wrapper around a sync.Pool. +type Pool struct { + p *pool.Pool[*Buffer] +} + +// NewPool constructs a new Pool. +func NewPool() Pool { + return Pool{ + p: pool.New(func() *Buffer { + return &Buffer{ + bs: make([]byte, 0, _size), + } + }), + } +} + +// Get retrieves a Buffer from the pool, creating one if necessary. +func (p Pool) Get() *Buffer { + buf := p.p.Get() + buf.Reset() + buf.pool = p + return buf +} + +func (p Pool) put(buf *Buffer) { + p.p.Put(buf) +} diff --git a/vendor/go.uber.org/zap/checklicense.sh b/vendor/go.uber.org/zap/checklicense.sh new file mode 100644 index 00000000..345ac8b8 --- /dev/null +++ b/vendor/go.uber.org/zap/checklicense.sh @@ -0,0 +1,17 @@ +#!/bin/bash -e + +ERROR_COUNT=0 +while read -r file +do + case "$(head -1 "${file}")" in + *"Copyright (c) "*" Uber Technologies, Inc.") + # everything's cool + ;; + *) + echo "$file is missing license header." + (( ERROR_COUNT++ )) + ;; + esac +done < <(git ls-files "*\.go") + +exit $ERROR_COUNT diff --git a/vendor/go.uber.org/zap/config.go b/vendor/go.uber.org/zap/config.go new file mode 100644 index 00000000..e76e4e64 --- /dev/null +++ b/vendor/go.uber.org/zap/config.go @@ -0,0 +1,330 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "errors" + "sort" + "time" + + "go.uber.org/zap/zapcore" +) + +// SamplingConfig sets a sampling strategy for the logger. Sampling caps the +// global CPU and I/O load that logging puts on your process while attempting +// to preserve a representative subset of your logs. +// +// If specified, the Sampler will invoke the Hook after each decision. +// +// Values configured here are per-second. See zapcore.NewSamplerWithOptions for +// details. +type SamplingConfig struct { + Initial int `json:"initial" yaml:"initial"` + Thereafter int `json:"thereafter" yaml:"thereafter"` + Hook func(zapcore.Entry, zapcore.SamplingDecision) `json:"-" yaml:"-"` +} + +// Config offers a declarative way to construct a logger. It doesn't do +// anything that can't be done with New, Options, and the various +// zapcore.WriteSyncer and zapcore.Core wrappers, but it's a simpler way to +// toggle common options. +// +// Note that Config intentionally supports only the most common options. More +// unusual logging setups (logging to network connections or message queues, +// splitting output between multiple files, etc.) are possible, but require +// direct use of the zapcore package. For sample code, see the package-level +// BasicConfiguration and AdvancedConfiguration examples. +// +// For an example showing runtime log level changes, see the documentation for +// AtomicLevel. +type Config struct { + // Level is the minimum enabled logging level. Note that this is a dynamic + // level, so calling Config.Level.SetLevel will atomically change the log + // level of all loggers descended from this config. + Level AtomicLevel `json:"level" yaml:"level"` + // Development puts the logger in development mode, which changes the + // behavior of DPanicLevel and takes stacktraces more liberally. + Development bool `json:"development" yaml:"development"` + // DisableCaller stops annotating logs with the calling function's file + // name and line number. By default, all logs are annotated. + DisableCaller bool `json:"disableCaller" yaml:"disableCaller"` + // DisableStacktrace completely disables automatic stacktrace capturing. By + // default, stacktraces are captured for WarnLevel and above logs in + // development and ErrorLevel and above in production. + DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"` + // Sampling sets a sampling policy. A nil SamplingConfig disables sampling. + Sampling *SamplingConfig `json:"sampling" yaml:"sampling"` + // Encoding sets the logger's encoding. Valid values are "json" and + // "console", as well as any third-party encodings registered via + // RegisterEncoder. + Encoding string `json:"encoding" yaml:"encoding"` + // EncoderConfig sets options for the chosen encoder. See + // zapcore.EncoderConfig for details. + EncoderConfig zapcore.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"` + // OutputPaths is a list of URLs or file paths to write logging output to. + // See Open for details. + OutputPaths []string `json:"outputPaths" yaml:"outputPaths"` + // ErrorOutputPaths is a list of URLs to write internal logger errors to. + // The default is standard error. + // + // Note that this setting only affects internal errors; for sample code that + // sends error-level logs to a different location from info- and debug-level + // logs, see the package-level AdvancedConfiguration example. + ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"` + // InitialFields is a collection of fields to add to the root logger. + InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"` +} + +// NewProductionEncoderConfig returns an opinionated EncoderConfig for +// production environments. +// +// Messages encoded with this configuration will be JSON-formatted +// and will have the following keys by default: +// +// - "level": The logging level (e.g. "info", "error"). +// - "ts": The current time in number of seconds since the Unix epoch. +// - "msg": The message passed to the log statement. +// - "caller": If available, a short path to the file and line number +// where the log statement was issued. +// The logger configuration determines whether this field is captured. +// - "stacktrace": If available, a stack trace from the line +// where the log statement was issued. +// The logger configuration determines whether this field is captured. +// +// By default, the following formats are used for different types: +// +// - Time is formatted as floating-point number of seconds since the Unix +// epoch. +// - Duration is formatted as floating-point number of seconds. +// +// You may change these by setting the appropriate fields in the returned +// object. +// For example, use the following to change the time encoding format: +// +// cfg := zap.NewProductionEncoderConfig() +// cfg.EncodeTime = zapcore.ISO8601TimeEncoder +func NewProductionEncoderConfig() zapcore.EncoderConfig { + return zapcore.EncoderConfig{ + TimeKey: "ts", + LevelKey: "level", + NameKey: "logger", + CallerKey: "caller", + FunctionKey: zapcore.OmitKey, + MessageKey: "msg", + StacktraceKey: "stacktrace", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.LowercaseLevelEncoder, + EncodeTime: zapcore.EpochTimeEncoder, + EncodeDuration: zapcore.SecondsDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } +} + +// NewProductionConfig builds a reasonable default production logging +// configuration. +// Logging is enabled at InfoLevel and above, and uses a JSON encoder. +// Logs are written to standard error. +// Stacktraces are included on logs of ErrorLevel and above. +// DPanicLevel logs will not panic, but will write a stacktrace. +// +// Sampling is enabled at 100:100 by default, +// meaning that after the first 100 log entries +// with the same level and message in the same second, +// it will log every 100th entry +// with the same level and message in the same second. +// You may disable this behavior by setting Sampling to nil. +// +// See [NewProductionEncoderConfig] for information +// on the default encoder configuration. +func NewProductionConfig() Config { + return Config{ + Level: NewAtomicLevelAt(InfoLevel), + Development: false, + Sampling: &SamplingConfig{ + Initial: 100, + Thereafter: 100, + }, + Encoding: "json", + EncoderConfig: NewProductionEncoderConfig(), + OutputPaths: []string{"stderr"}, + ErrorOutputPaths: []string{"stderr"}, + } +} + +// NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for +// development environments. +// +// Messages encoded with this configuration will use Zap's console encoder +// intended to print human-readable output. +// It will print log messages with the following information: +// +// - The log level (e.g. "INFO", "ERROR"). +// - The time in ISO8601 format (e.g. "2017-01-01T12:00:00Z"). +// - The message passed to the log statement. +// - If available, a short path to the file and line number +// where the log statement was issued. +// The logger configuration determines whether this field is captured. +// - If available, a stacktrace from the line +// where the log statement was issued. +// The logger configuration determines whether this field is captured. +// +// By default, the following formats are used for different types: +// +// - Time is formatted in ISO8601 format (e.g. "2017-01-01T12:00:00Z"). +// - Duration is formatted as a string (e.g. "1.234s"). +// +// You may change these by setting the appropriate fields in the returned +// object. +// For example, use the following to change the time encoding format: +// +// cfg := zap.NewDevelopmentEncoderConfig() +// cfg.EncodeTime = zapcore.ISO8601TimeEncoder +func NewDevelopmentEncoderConfig() zapcore.EncoderConfig { + return zapcore.EncoderConfig{ + // Keys can be anything except the empty string. + TimeKey: "T", + LevelKey: "L", + NameKey: "N", + CallerKey: "C", + FunctionKey: zapcore.OmitKey, + MessageKey: "M", + StacktraceKey: "S", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.CapitalLevelEncoder, + EncodeTime: zapcore.ISO8601TimeEncoder, + EncodeDuration: zapcore.StringDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } +} + +// NewDevelopmentConfig builds a reasonable default development logging +// configuration. +// Logging is enabled at DebugLevel and above, and uses a console encoder. +// Logs are written to standard error. +// Stacktraces are included on logs of WarnLevel and above. +// DPanicLevel logs will panic. +// +// See [NewDevelopmentEncoderConfig] for information +// on the default encoder configuration. +func NewDevelopmentConfig() Config { + return Config{ + Level: NewAtomicLevelAt(DebugLevel), + Development: true, + Encoding: "console", + EncoderConfig: NewDevelopmentEncoderConfig(), + OutputPaths: []string{"stderr"}, + ErrorOutputPaths: []string{"stderr"}, + } +} + +// Build constructs a logger from the Config and Options. +func (cfg Config) Build(opts ...Option) (*Logger, error) { + enc, err := cfg.buildEncoder() + if err != nil { + return nil, err + } + + sink, errSink, err := cfg.openSinks() + if err != nil { + return nil, err + } + + if cfg.Level == (AtomicLevel{}) { + return nil, errors.New("missing Level") + } + + log := New( + zapcore.NewCore(enc, sink, cfg.Level), + cfg.buildOptions(errSink)..., + ) + if len(opts) > 0 { + log = log.WithOptions(opts...) + } + return log, nil +} + +func (cfg Config) buildOptions(errSink zapcore.WriteSyncer) []Option { + opts := []Option{ErrorOutput(errSink)} + + if cfg.Development { + opts = append(opts, Development()) + } + + if !cfg.DisableCaller { + opts = append(opts, AddCaller()) + } + + stackLevel := ErrorLevel + if cfg.Development { + stackLevel = WarnLevel + } + if !cfg.DisableStacktrace { + opts = append(opts, AddStacktrace(stackLevel)) + } + + if scfg := cfg.Sampling; scfg != nil { + opts = append(opts, WrapCore(func(core zapcore.Core) zapcore.Core { + var samplerOpts []zapcore.SamplerOption + if scfg.Hook != nil { + samplerOpts = append(samplerOpts, zapcore.SamplerHook(scfg.Hook)) + } + return zapcore.NewSamplerWithOptions( + core, + time.Second, + cfg.Sampling.Initial, + cfg.Sampling.Thereafter, + samplerOpts..., + ) + })) + } + + if len(cfg.InitialFields) > 0 { + fs := make([]Field, 0, len(cfg.InitialFields)) + keys := make([]string, 0, len(cfg.InitialFields)) + for k := range cfg.InitialFields { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + fs = append(fs, Any(k, cfg.InitialFields[k])) + } + opts = append(opts, Fields(fs...)) + } + + return opts +} + +func (cfg Config) openSinks() (zapcore.WriteSyncer, zapcore.WriteSyncer, error) { + sink, closeOut, err := Open(cfg.OutputPaths...) + if err != nil { + return nil, nil, err + } + errSink, _, err := Open(cfg.ErrorOutputPaths...) + if err != nil { + closeOut() + return nil, nil, err + } + return sink, errSink, nil +} + +func (cfg Config) buildEncoder() (zapcore.Encoder, error) { + return newEncoder(cfg.Encoding, cfg.EncoderConfig) +} diff --git a/vendor/go.uber.org/zap/doc.go b/vendor/go.uber.org/zap/doc.go new file mode 100644 index 00000000..3c50d7b4 --- /dev/null +++ b/vendor/go.uber.org/zap/doc.go @@ -0,0 +1,117 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package zap provides fast, structured, leveled logging. +// +// For applications that log in the hot path, reflection-based serialization +// and string formatting are prohibitively expensive - they're CPU-intensive +// and make many small allocations. Put differently, using json.Marshal and +// fmt.Fprintf to log tons of interface{} makes your application slow. +// +// Zap takes a different approach. It includes a reflection-free, +// zero-allocation JSON encoder, and the base Logger strives to avoid +// serialization overhead and allocations wherever possible. By building the +// high-level SugaredLogger on that foundation, zap lets users choose when +// they need to count every allocation and when they'd prefer a more familiar, +// loosely typed API. +// +// # Choosing a Logger +// +// In contexts where performance is nice, but not critical, use the +// SugaredLogger. It's 4-10x faster than other structured logging packages and +// supports both structured and printf-style logging. Like log15 and go-kit, +// the SugaredLogger's structured logging APIs are loosely typed and accept a +// variadic number of key-value pairs. (For more advanced use cases, they also +// accept strongly typed fields - see the SugaredLogger.With documentation for +// details.) +// +// sugar := zap.NewExample().Sugar() +// defer sugar.Sync() +// sugar.Infow("failed to fetch URL", +// "url", "http://example.com", +// "attempt", 3, +// "backoff", time.Second, +// ) +// sugar.Infof("failed to fetch URL: %s", "http://example.com") +// +// By default, loggers are unbuffered. However, since zap's low-level APIs +// allow buffering, calling Sync before letting your process exit is a good +// habit. +// +// In the rare contexts where every microsecond and every allocation matter, +// use the Logger. It's even faster than the SugaredLogger and allocates far +// less, but it only supports strongly-typed, structured logging. +// +// logger := zap.NewExample() +// defer logger.Sync() +// logger.Info("failed to fetch URL", +// zap.String("url", "http://example.com"), +// zap.Int("attempt", 3), +// zap.Duration("backoff", time.Second), +// ) +// +// Choosing between the Logger and SugaredLogger doesn't need to be an +// application-wide decision: converting between the two is simple and +// inexpensive. +// +// logger := zap.NewExample() +// defer logger.Sync() +// sugar := logger.Sugar() +// plain := sugar.Desugar() +// +// # Configuring Zap +// +// The simplest way to build a Logger is to use zap's opinionated presets: +// NewExample, NewProduction, and NewDevelopment. These presets build a logger +// with a single function call: +// +// logger, err := zap.NewProduction() +// if err != nil { +// log.Fatalf("can't initialize zap logger: %v", err) +// } +// defer logger.Sync() +// +// Presets are fine for small projects, but larger projects and organizations +// naturally require a bit more customization. For most users, zap's Config +// struct strikes the right balance between flexibility and convenience. See +// the package-level BasicConfiguration example for sample code. +// +// More unusual configurations (splitting output between files, sending logs +// to a message queue, etc.) are possible, but require direct use of +// go.uber.org/zap/zapcore. See the package-level AdvancedConfiguration +// example for sample code. +// +// # Extending Zap +// +// The zap package itself is a relatively thin wrapper around the interfaces +// in go.uber.org/zap/zapcore. Extending zap to support a new encoding (e.g., +// BSON), a new log sink (e.g., Kafka), or something more exotic (perhaps an +// exception aggregation service, like Sentry or Rollbar) typically requires +// implementing the zapcore.Encoder, zapcore.WriteSyncer, or zapcore.Core +// interfaces. See the zapcore documentation for details. +// +// Similarly, package authors can use the high-performance Encoder and Core +// implementations in the zapcore package to build their own loggers. +// +// # Frequently Asked Questions +// +// An FAQ covering everything from installation errors to design decisions is +// available at https://github.com/uber-go/zap/blob/master/FAQ.md. +package zap // import "go.uber.org/zap" diff --git a/vendor/go.uber.org/zap/encoder.go b/vendor/go.uber.org/zap/encoder.go new file mode 100644 index 00000000..caa04cee --- /dev/null +++ b/vendor/go.uber.org/zap/encoder.go @@ -0,0 +1,79 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "errors" + "fmt" + "sync" + + "go.uber.org/zap/zapcore" +) + +var ( + errNoEncoderNameSpecified = errors.New("no encoder name specified") + + _encoderNameToConstructor = map[string]func(zapcore.EncoderConfig) (zapcore.Encoder, error){ + "console": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + return zapcore.NewConsoleEncoder(encoderConfig), nil + }, + "json": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + return zapcore.NewJSONEncoder(encoderConfig), nil + }, + } + _encoderMutex sync.RWMutex +) + +// RegisterEncoder registers an encoder constructor, which the Config struct +// can then reference. By default, the "json" and "console" encoders are +// registered. +// +// Attempting to register an encoder whose name is already taken returns an +// error. +func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapcore.Encoder, error)) error { + _encoderMutex.Lock() + defer _encoderMutex.Unlock() + if name == "" { + return errNoEncoderNameSpecified + } + if _, ok := _encoderNameToConstructor[name]; ok { + return fmt.Errorf("encoder already registered for name %q", name) + } + _encoderNameToConstructor[name] = constructor + return nil +} + +func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil { + return nil, errors.New("missing EncodeTime in EncoderConfig") + } + + _encoderMutex.RLock() + defer _encoderMutex.RUnlock() + if name == "" { + return nil, errNoEncoderNameSpecified + } + constructor, ok := _encoderNameToConstructor[name] + if !ok { + return nil, fmt.Errorf("no encoder registered for name %q", name) + } + return constructor(encoderConfig) +} diff --git a/vendor/go.uber.org/zap/error.go b/vendor/go.uber.org/zap/error.go new file mode 100644 index 00000000..45f7b838 --- /dev/null +++ b/vendor/go.uber.org/zap/error.go @@ -0,0 +1,82 @@ +// Copyright (c) 2017 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "go.uber.org/zap/internal/pool" + "go.uber.org/zap/zapcore" +) + +var _errArrayElemPool = pool.New(func() *errArrayElem { + return &errArrayElem{} +}) + +// Error is shorthand for the common idiom NamedError("error", err). +func Error(err error) Field { + return NamedError("error", err) +} + +// NamedError constructs a field that lazily stores err.Error() under the +// provided key. Errors which also implement fmt.Formatter (like those produced +// by github.com/pkg/errors) will also have their verbose representation stored +// under key+"Verbose". If passed a nil error, the field is a no-op. +// +// For the common case in which the key is simply "error", the Error function +// is shorter and less repetitive. +func NamedError(key string, err error) Field { + if err == nil { + return Skip() + } + return Field{Key: key, Type: zapcore.ErrorType, Interface: err} +} + +type errArray []error + +func (errs errArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range errs { + if errs[i] == nil { + continue + } + // To represent each error as an object with an "error" attribute and + // potentially an "errorVerbose" attribute, we need to wrap it in a + // type that implements LogObjectMarshaler. To prevent this from + // allocating, pool the wrapper type. + elem := _errArrayElemPool.Get() + elem.error = errs[i] + err := arr.AppendObject(elem) + elem.error = nil + _errArrayElemPool.Put(elem) + if err != nil { + return err + } + } + return nil +} + +type errArrayElem struct { + error +} + +func (e *errArrayElem) MarshalLogObject(enc zapcore.ObjectEncoder) error { + // Re-use the error field's logic, which supports non-standard error types. + Error(e.error).AddTo(enc) + return nil +} diff --git a/vendor/go.uber.org/zap/field.go b/vendor/go.uber.org/zap/field.go new file mode 100644 index 00000000..c8dd3358 --- /dev/null +++ b/vendor/go.uber.org/zap/field.go @@ -0,0 +1,613 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "fmt" + "math" + "time" + + "go.uber.org/zap/internal/stacktrace" + "go.uber.org/zap/zapcore" +) + +// Field is an alias for Field. Aliasing this type dramatically +// improves the navigability of this package's API documentation. +type Field = zapcore.Field + +var ( + _minTimeInt64 = time.Unix(0, math.MinInt64) + _maxTimeInt64 = time.Unix(0, math.MaxInt64) +) + +// Skip constructs a no-op field, which is often useful when handling invalid +// inputs in other Field constructors. +func Skip() Field { + return Field{Type: zapcore.SkipType} +} + +// nilField returns a field which will marshal explicitly as nil. See motivation +// in https://github.com/uber-go/zap/issues/753 . If we ever make breaking +// changes and add zapcore.NilType and zapcore.ObjectEncoder.AddNil, the +// implementation here should be changed to reflect that. +func nilField(key string) Field { return Reflect(key, nil) } + +// Binary constructs a field that carries an opaque binary blob. +// +// Binary data is serialized in an encoding-appropriate format. For example, +// zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, +// use ByteString. +func Binary(key string, val []byte) Field { + return Field{Key: key, Type: zapcore.BinaryType, Interface: val} +} + +// Bool constructs a field that carries a bool. +func Bool(key string, val bool) Field { + var ival int64 + if val { + ival = 1 + } + return Field{Key: key, Type: zapcore.BoolType, Integer: ival} +} + +// Boolp constructs a field that carries a *bool. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Boolp(key string, val *bool) Field { + if val == nil { + return nilField(key) + } + return Bool(key, *val) +} + +// ByteString constructs a field that carries UTF-8 encoded text as a []byte. +// To log opaque binary blobs (which aren't necessarily valid UTF-8), use +// Binary. +func ByteString(key string, val []byte) Field { + return Field{Key: key, Type: zapcore.ByteStringType, Interface: val} +} + +// Complex128 constructs a field that carries a complex number. Unlike most +// numeric fields, this costs an allocation (to convert the complex128 to +// interface{}). +func Complex128(key string, val complex128) Field { + return Field{Key: key, Type: zapcore.Complex128Type, Interface: val} +} + +// Complex128p constructs a field that carries a *complex128. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Complex128p(key string, val *complex128) Field { + if val == nil { + return nilField(key) + } + return Complex128(key, *val) +} + +// Complex64 constructs a field that carries a complex number. Unlike most +// numeric fields, this costs an allocation (to convert the complex64 to +// interface{}). +func Complex64(key string, val complex64) Field { + return Field{Key: key, Type: zapcore.Complex64Type, Interface: val} +} + +// Complex64p constructs a field that carries a *complex64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Complex64p(key string, val *complex64) Field { + if val == nil { + return nilField(key) + } + return Complex64(key, *val) +} + +// Float64 constructs a field that carries a float64. The way the +// floating-point value is represented is encoder-dependent, so marshaling is +// necessarily lazy. +func Float64(key string, val float64) Field { + return Field{Key: key, Type: zapcore.Float64Type, Integer: int64(math.Float64bits(val))} +} + +// Float64p constructs a field that carries a *float64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Float64p(key string, val *float64) Field { + if val == nil { + return nilField(key) + } + return Float64(key, *val) +} + +// Float32 constructs a field that carries a float32. The way the +// floating-point value is represented is encoder-dependent, so marshaling is +// necessarily lazy. +func Float32(key string, val float32) Field { + return Field{Key: key, Type: zapcore.Float32Type, Integer: int64(math.Float32bits(val))} +} + +// Float32p constructs a field that carries a *float32. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Float32p(key string, val *float32) Field { + if val == nil { + return nilField(key) + } + return Float32(key, *val) +} + +// Int constructs a field with the given key and value. +func Int(key string, val int) Field { + return Int64(key, int64(val)) +} + +// Intp constructs a field that carries a *int. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Intp(key string, val *int) Field { + if val == nil { + return nilField(key) + } + return Int(key, *val) +} + +// Int64 constructs a field with the given key and value. +func Int64(key string, val int64) Field { + return Field{Key: key, Type: zapcore.Int64Type, Integer: val} +} + +// Int64p constructs a field that carries a *int64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int64p(key string, val *int64) Field { + if val == nil { + return nilField(key) + } + return Int64(key, *val) +} + +// Int32 constructs a field with the given key and value. +func Int32(key string, val int32) Field { + return Field{Key: key, Type: zapcore.Int32Type, Integer: int64(val)} +} + +// Int32p constructs a field that carries a *int32. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int32p(key string, val *int32) Field { + if val == nil { + return nilField(key) + } + return Int32(key, *val) +} + +// Int16 constructs a field with the given key and value. +func Int16(key string, val int16) Field { + return Field{Key: key, Type: zapcore.Int16Type, Integer: int64(val)} +} + +// Int16p constructs a field that carries a *int16. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int16p(key string, val *int16) Field { + if val == nil { + return nilField(key) + } + return Int16(key, *val) +} + +// Int8 constructs a field with the given key and value. +func Int8(key string, val int8) Field { + return Field{Key: key, Type: zapcore.Int8Type, Integer: int64(val)} +} + +// Int8p constructs a field that carries a *int8. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int8p(key string, val *int8) Field { + if val == nil { + return nilField(key) + } + return Int8(key, *val) +} + +// String constructs a field with the given key and value. +func String(key string, val string) Field { + return Field{Key: key, Type: zapcore.StringType, String: val} +} + +// Stringp constructs a field that carries a *string. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Stringp(key string, val *string) Field { + if val == nil { + return nilField(key) + } + return String(key, *val) +} + +// Uint constructs a field with the given key and value. +func Uint(key string, val uint) Field { + return Uint64(key, uint64(val)) +} + +// Uintp constructs a field that carries a *uint. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uintp(key string, val *uint) Field { + if val == nil { + return nilField(key) + } + return Uint(key, *val) +} + +// Uint64 constructs a field with the given key and value. +func Uint64(key string, val uint64) Field { + return Field{Key: key, Type: zapcore.Uint64Type, Integer: int64(val)} +} + +// Uint64p constructs a field that carries a *uint64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint64p(key string, val *uint64) Field { + if val == nil { + return nilField(key) + } + return Uint64(key, *val) +} + +// Uint32 constructs a field with the given key and value. +func Uint32(key string, val uint32) Field { + return Field{Key: key, Type: zapcore.Uint32Type, Integer: int64(val)} +} + +// Uint32p constructs a field that carries a *uint32. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint32p(key string, val *uint32) Field { + if val == nil { + return nilField(key) + } + return Uint32(key, *val) +} + +// Uint16 constructs a field with the given key and value. +func Uint16(key string, val uint16) Field { + return Field{Key: key, Type: zapcore.Uint16Type, Integer: int64(val)} +} + +// Uint16p constructs a field that carries a *uint16. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint16p(key string, val *uint16) Field { + if val == nil { + return nilField(key) + } + return Uint16(key, *val) +} + +// Uint8 constructs a field with the given key and value. +func Uint8(key string, val uint8) Field { + return Field{Key: key, Type: zapcore.Uint8Type, Integer: int64(val)} +} + +// Uint8p constructs a field that carries a *uint8. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint8p(key string, val *uint8) Field { + if val == nil { + return nilField(key) + } + return Uint8(key, *val) +} + +// Uintptr constructs a field with the given key and value. +func Uintptr(key string, val uintptr) Field { + return Field{Key: key, Type: zapcore.UintptrType, Integer: int64(val)} +} + +// Uintptrp constructs a field that carries a *uintptr. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uintptrp(key string, val *uintptr) Field { + if val == nil { + return nilField(key) + } + return Uintptr(key, *val) +} + +// Reflect constructs a field with the given key and an arbitrary object. It uses +// an encoding-appropriate, reflection-based function to lazily serialize nearly +// any object into the logging context, but it's relatively slow and +// allocation-heavy. Outside tests, Any is always a better choice. +// +// If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect +// includes the error message in the final log output. +func Reflect(key string, val interface{}) Field { + return Field{Key: key, Type: zapcore.ReflectType, Interface: val} +} + +// Namespace creates a named, isolated scope within the logger's context. All +// subsequent fields will be added to the new namespace. +// +// This helps prevent key collisions when injecting loggers into sub-components +// or third-party libraries. +func Namespace(key string) Field { + return Field{Key: key, Type: zapcore.NamespaceType} +} + +// Stringer constructs a field with the given key and the output of the value's +// String method. The Stringer's String method is called lazily. +func Stringer(key string, val fmt.Stringer) Field { + return Field{Key: key, Type: zapcore.StringerType, Interface: val} +} + +// Time constructs a Field with the given key and value. The encoder +// controls how the time is serialized. +func Time(key string, val time.Time) Field { + if val.Before(_minTimeInt64) || val.After(_maxTimeInt64) { + return Field{Key: key, Type: zapcore.TimeFullType, Interface: val} + } + return Field{Key: key, Type: zapcore.TimeType, Integer: val.UnixNano(), Interface: val.Location()} +} + +// Timep constructs a field that carries a *time.Time. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Timep(key string, val *time.Time) Field { + if val == nil { + return nilField(key) + } + return Time(key, *val) +} + +// Stack constructs a field that stores a stacktrace of the current goroutine +// under provided key. Keep in mind that taking a stacktrace is eager and +// expensive (relatively speaking); this function both makes an allocation and +// takes about two microseconds. +func Stack(key string) Field { + return StackSkip(key, 1) // skip Stack +} + +// StackSkip constructs a field similarly to Stack, but also skips the given +// number of frames from the top of the stacktrace. +func StackSkip(key string, skip int) Field { + // Returning the stacktrace as a string costs an allocation, but saves us + // from expanding the zapcore.Field union struct to include a byte slice. Since + // taking a stacktrace is already so expensive (~10us), the extra allocation + // is okay. + return String(key, stacktrace.Take(skip+1)) // skip StackSkip +} + +// Duration constructs a field with the given key and value. The encoder +// controls how the duration is serialized. +func Duration(key string, val time.Duration) Field { + return Field{Key: key, Type: zapcore.DurationType, Integer: int64(val)} +} + +// Durationp constructs a field that carries a *time.Duration. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Durationp(key string, val *time.Duration) Field { + if val == nil { + return nilField(key) + } + return Duration(key, *val) +} + +// Object constructs a field with the given key and ObjectMarshaler. It +// provides a flexible, but still type-safe and efficient, way to add map- or +// struct-like user-defined types to the logging context. The struct's +// MarshalLogObject method is called lazily. +func Object(key string, val zapcore.ObjectMarshaler) Field { + return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val} +} + +// Inline constructs a Field that is similar to Object, but it +// will add the elements of the provided ObjectMarshaler to the +// current namespace. +func Inline(val zapcore.ObjectMarshaler) Field { + return zapcore.Field{ + Type: zapcore.InlineMarshalerType, + Interface: val, + } +} + +// Dict constructs a field containing the provided key-value pairs. +// It acts similar to [Object], but with the fields specified as arguments. +func Dict(key string, val ...Field) Field { + return dictField(key, val) +} + +// We need a function with the signature (string, T) for zap.Any. +func dictField(key string, val []Field) Field { + return Object(key, dictObject(val)) +} + +type dictObject []Field + +func (d dictObject) MarshalLogObject(enc zapcore.ObjectEncoder) error { + for _, f := range d { + f.AddTo(enc) + } + return nil +} + +// We discovered an issue where zap.Any can cause a performance degradation +// when used in new goroutines. +// +// This happens because the compiler assigns 4.8kb (one zap.Field per arm of +// switch statement) of stack space for zap.Any when it takes the form: +// +// switch v := v.(type) { +// case string: +// return String(key, v) +// case int: +// return Int(key, v) +// // ... +// default: +// return Reflect(key, v) +// } +// +// To avoid this, we use the type switch to assign a value to a single local variable +// and then call a function on it. +// The local variable is just a function reference so it doesn't allocate +// when converted to an interface{}. +// +// A fair bit of experimentation went into this. +// See also: +// +// - https://github.com/uber-go/zap/pull/1301 +// - https://github.com/uber-go/zap/pull/1303 +// - https://github.com/uber-go/zap/pull/1304 +// - https://github.com/uber-go/zap/pull/1305 +// - https://github.com/uber-go/zap/pull/1308 +type anyFieldC[T any] func(string, T) Field + +func (f anyFieldC[T]) Any(key string, val any) Field { + v, _ := val.(T) + // val is guaranteed to be a T, except when it's nil. + return f(key, v) +} + +// Any takes a key and an arbitrary value and chooses the best way to represent +// them as a field, falling back to a reflection-based approach only if +// necessary. +// +// Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between +// them. To minimize surprises, []byte values are treated as binary blobs, byte +// values are treated as uint8, and runes are always treated as integers. +func Any(key string, value interface{}) Field { + var c interface{ Any(string, any) Field } + + switch value.(type) { + case zapcore.ObjectMarshaler: + c = anyFieldC[zapcore.ObjectMarshaler](Object) + case zapcore.ArrayMarshaler: + c = anyFieldC[zapcore.ArrayMarshaler](Array) + case []Field: + c = anyFieldC[[]Field](dictField) + case bool: + c = anyFieldC[bool](Bool) + case *bool: + c = anyFieldC[*bool](Boolp) + case []bool: + c = anyFieldC[[]bool](Bools) + case complex128: + c = anyFieldC[complex128](Complex128) + case *complex128: + c = anyFieldC[*complex128](Complex128p) + case []complex128: + c = anyFieldC[[]complex128](Complex128s) + case complex64: + c = anyFieldC[complex64](Complex64) + case *complex64: + c = anyFieldC[*complex64](Complex64p) + case []complex64: + c = anyFieldC[[]complex64](Complex64s) + case float64: + c = anyFieldC[float64](Float64) + case *float64: + c = anyFieldC[*float64](Float64p) + case []float64: + c = anyFieldC[[]float64](Float64s) + case float32: + c = anyFieldC[float32](Float32) + case *float32: + c = anyFieldC[*float32](Float32p) + case []float32: + c = anyFieldC[[]float32](Float32s) + case int: + c = anyFieldC[int](Int) + case *int: + c = anyFieldC[*int](Intp) + case []int: + c = anyFieldC[[]int](Ints) + case int64: + c = anyFieldC[int64](Int64) + case *int64: + c = anyFieldC[*int64](Int64p) + case []int64: + c = anyFieldC[[]int64](Int64s) + case int32: + c = anyFieldC[int32](Int32) + case *int32: + c = anyFieldC[*int32](Int32p) + case []int32: + c = anyFieldC[[]int32](Int32s) + case int16: + c = anyFieldC[int16](Int16) + case *int16: + c = anyFieldC[*int16](Int16p) + case []int16: + c = anyFieldC[[]int16](Int16s) + case int8: + c = anyFieldC[int8](Int8) + case *int8: + c = anyFieldC[*int8](Int8p) + case []int8: + c = anyFieldC[[]int8](Int8s) + case string: + c = anyFieldC[string](String) + case *string: + c = anyFieldC[*string](Stringp) + case []string: + c = anyFieldC[[]string](Strings) + case uint: + c = anyFieldC[uint](Uint) + case *uint: + c = anyFieldC[*uint](Uintp) + case []uint: + c = anyFieldC[[]uint](Uints) + case uint64: + c = anyFieldC[uint64](Uint64) + case *uint64: + c = anyFieldC[*uint64](Uint64p) + case []uint64: + c = anyFieldC[[]uint64](Uint64s) + case uint32: + c = anyFieldC[uint32](Uint32) + case *uint32: + c = anyFieldC[*uint32](Uint32p) + case []uint32: + c = anyFieldC[[]uint32](Uint32s) + case uint16: + c = anyFieldC[uint16](Uint16) + case *uint16: + c = anyFieldC[*uint16](Uint16p) + case []uint16: + c = anyFieldC[[]uint16](Uint16s) + case uint8: + c = anyFieldC[uint8](Uint8) + case *uint8: + c = anyFieldC[*uint8](Uint8p) + case []byte: + c = anyFieldC[[]byte](Binary) + case uintptr: + c = anyFieldC[uintptr](Uintptr) + case *uintptr: + c = anyFieldC[*uintptr](Uintptrp) + case []uintptr: + c = anyFieldC[[]uintptr](Uintptrs) + case time.Time: + c = anyFieldC[time.Time](Time) + case *time.Time: + c = anyFieldC[*time.Time](Timep) + case []time.Time: + c = anyFieldC[[]time.Time](Times) + case time.Duration: + c = anyFieldC[time.Duration](Duration) + case *time.Duration: + c = anyFieldC[*time.Duration](Durationp) + case []time.Duration: + c = anyFieldC[[]time.Duration](Durations) + case error: + c = anyFieldC[error](NamedError) + case []error: + c = anyFieldC[[]error](Errors) + case fmt.Stringer: + c = anyFieldC[fmt.Stringer](Stringer) + default: + c = anyFieldC[any](Reflect) + } + + return c.Any(key, value) +} diff --git a/vendor/go.uber.org/zap/flag.go b/vendor/go.uber.org/zap/flag.go new file mode 100644 index 00000000..13128750 --- /dev/null +++ b/vendor/go.uber.org/zap/flag.go @@ -0,0 +1,39 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "flag" + + "go.uber.org/zap/zapcore" +) + +// LevelFlag uses the standard library's flag.Var to declare a global flag +// with the specified name, default, and usage guidance. The returned value is +// a pointer to the value of the flag. +// +// If you don't want to use the flag package's global state, you can use any +// non-nil *Level as a flag.Value with your own *flag.FlagSet. +func LevelFlag(name string, defaultLevel zapcore.Level, usage string) *zapcore.Level { + lvl := defaultLevel + flag.Var(&lvl, name, usage) + return &lvl +} diff --git a/vendor/go.uber.org/zap/glide.yaml b/vendor/go.uber.org/zap/glide.yaml new file mode 100644 index 00000000..8e1d05e9 --- /dev/null +++ b/vendor/go.uber.org/zap/glide.yaml @@ -0,0 +1,34 @@ +package: go.uber.org/zap +license: MIT +import: +- package: go.uber.org/atomic + version: ^1 +- package: go.uber.org/multierr + version: ^1 +testImport: +- package: github.com/satori/go.uuid +- package: github.com/sirupsen/logrus +- package: github.com/apex/log + subpackages: + - handlers/json +- package: github.com/go-kit/kit + subpackages: + - log +- package: github.com/stretchr/testify + subpackages: + - assert + - require +- package: gopkg.in/inconshreveable/log15.v2 +- package: github.com/mattn/goveralls +- package: github.com/pborman/uuid +- package: github.com/pkg/errors +- package: github.com/rs/zerolog +- package: golang.org/x/tools + subpackages: + - cover +- package: golang.org/x/lint + subpackages: + - golint +- package: github.com/axw/gocov + subpackages: + - gocov diff --git a/vendor/go.uber.org/zap/global.go b/vendor/go.uber.org/zap/global.go new file mode 100644 index 00000000..3cb46c9e --- /dev/null +++ b/vendor/go.uber.org/zap/global.go @@ -0,0 +1,169 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "bytes" + "fmt" + "log" + "os" + "sync" + + "go.uber.org/zap/zapcore" +) + +const ( + _stdLogDefaultDepth = 1 + _loggerWriterDepth = 2 + _programmerErrorTemplate = "You've found a bug in zap! Please file a bug at " + + "https://github.com/uber-go/zap/issues/new and reference this error: %v" +) + +var ( + _globalMu sync.RWMutex + _globalL = NewNop() + _globalS = _globalL.Sugar() +) + +// L returns the global Logger, which can be reconfigured with ReplaceGlobals. +// It's safe for concurrent use. +func L() *Logger { + _globalMu.RLock() + l := _globalL + _globalMu.RUnlock() + return l +} + +// S returns the global SugaredLogger, which can be reconfigured with +// ReplaceGlobals. It's safe for concurrent use. +func S() *SugaredLogger { + _globalMu.RLock() + s := _globalS + _globalMu.RUnlock() + return s +} + +// ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a +// function to restore the original values. It's safe for concurrent use. +func ReplaceGlobals(logger *Logger) func() { + _globalMu.Lock() + prev := _globalL + _globalL = logger + _globalS = logger.Sugar() + _globalMu.Unlock() + return func() { ReplaceGlobals(prev) } +} + +// NewStdLog returns a *log.Logger which writes to the supplied zap Logger at +// InfoLevel. To redirect the standard library's package-global logging +// functions, use RedirectStdLog instead. +func NewStdLog(l *Logger) *log.Logger { + logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) + f := logger.Info + return log.New(&loggerWriter{f}, "" /* prefix */, 0 /* flags */) +} + +// NewStdLogAt returns *log.Logger which writes to supplied zap logger at +// required level. +func NewStdLogAt(l *Logger, level zapcore.Level) (*log.Logger, error) { + logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) + logFunc, err := levelToFunc(logger, level) + if err != nil { + return nil, err + } + return log.New(&loggerWriter{logFunc}, "" /* prefix */, 0 /* flags */), nil +} + +// RedirectStdLog redirects output from the standard library's package-global +// logger to the supplied logger at InfoLevel. Since zap already handles caller +// annotations, timestamps, etc., it automatically disables the standard +// library's annotations and prefixing. +// +// It returns a function to restore the original prefix and flags and reset the +// standard library's output to os.Stderr. +func RedirectStdLog(l *Logger) func() { + f, err := redirectStdLogAt(l, InfoLevel) + if err != nil { + // Can't get here, since passing InfoLevel to redirectStdLogAt always + // works. + panic(fmt.Sprintf(_programmerErrorTemplate, err)) + } + return f +} + +// RedirectStdLogAt redirects output from the standard library's package-global +// logger to the supplied logger at the specified level. Since zap already +// handles caller annotations, timestamps, etc., it automatically disables the +// standard library's annotations and prefixing. +// +// It returns a function to restore the original prefix and flags and reset the +// standard library's output to os.Stderr. +func RedirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) { + return redirectStdLogAt(l, level) +} + +func redirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) { + flags := log.Flags() + prefix := log.Prefix() + log.SetFlags(0) + log.SetPrefix("") + logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) + logFunc, err := levelToFunc(logger, level) + if err != nil { + return nil, err + } + log.SetOutput(&loggerWriter{logFunc}) + return func() { + log.SetFlags(flags) + log.SetPrefix(prefix) + log.SetOutput(os.Stderr) + }, nil +} + +func levelToFunc(logger *Logger, lvl zapcore.Level) (func(string, ...Field), error) { + switch lvl { + case DebugLevel: + return logger.Debug, nil + case InfoLevel: + return logger.Info, nil + case WarnLevel: + return logger.Warn, nil + case ErrorLevel: + return logger.Error, nil + case DPanicLevel: + return logger.DPanic, nil + case PanicLevel: + return logger.Panic, nil + case FatalLevel: + return logger.Fatal, nil + } + return nil, fmt.Errorf("unrecognized level: %q", lvl) +} + +type loggerWriter struct { + logFunc func(msg string, fields ...Field) +} + +func (l *loggerWriter) Write(p []byte) (int, error) { + p = bytes.TrimSpace(p) + l.logFunc(string(p)) + return len(p), nil +} diff --git a/vendor/go.uber.org/zap/http_handler.go b/vendor/go.uber.org/zap/http_handler.go new file mode 100644 index 00000000..2be8f651 --- /dev/null +++ b/vendor/go.uber.org/zap/http_handler.go @@ -0,0 +1,140 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + + "go.uber.org/zap/zapcore" +) + +// ServeHTTP is a simple JSON endpoint that can report on or change the current +// logging level. +// +// # GET +// +// The GET request returns a JSON description of the current logging level like: +// +// {"level":"info"} +// +// # PUT +// +// The PUT request changes the logging level. It is perfectly safe to change the +// logging level while a program is running. Two content types are supported: +// +// Content-Type: application/x-www-form-urlencoded +// +// With this content type, the level can be provided through the request body or +// a query parameter. The log level is URL encoded like: +// +// level=debug +// +// The request body takes precedence over the query parameter, if both are +// specified. +// +// This content type is the default for a curl PUT request. Following are two +// example curl requests that both set the logging level to debug. +// +// curl -X PUT localhost:8080/log/level?level=debug +// curl -X PUT localhost:8080/log/level -d level=debug +// +// For any other content type, the payload is expected to be JSON encoded and +// look like: +// +// {"level":"info"} +// +// An example curl request could look like this: +// +// curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}' +func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if err := lvl.serveHTTP(w, r); err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, "internal error: %v", err) + } +} + +func (lvl AtomicLevel) serveHTTP(w http.ResponseWriter, r *http.Request) error { + type errorResponse struct { + Error string `json:"error"` + } + type payload struct { + Level zapcore.Level `json:"level"` + } + + enc := json.NewEncoder(w) + + switch r.Method { + case http.MethodGet: + return enc.Encode(payload{Level: lvl.Level()}) + + case http.MethodPut: + requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return enc.Encode(errorResponse{Error: err.Error()}) + } + lvl.SetLevel(requestedLvl) + return enc.Encode(payload{Level: lvl.Level()}) + + default: + w.WriteHeader(http.StatusMethodNotAllowed) + return enc.Encode(errorResponse{ + Error: "Only GET and PUT are supported.", + }) + } +} + +// Decodes incoming PUT requests and returns the requested logging level. +func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error) { + if contentType == "application/x-www-form-urlencoded" { + return decodePutURL(r) + } + return decodePutJSON(r.Body) +} + +func decodePutURL(r *http.Request) (zapcore.Level, error) { + lvl := r.FormValue("level") + if lvl == "" { + return 0, errors.New("must specify logging level") + } + var l zapcore.Level + if err := l.UnmarshalText([]byte(lvl)); err != nil { + return 0, err + } + return l, nil +} + +func decodePutJSON(body io.Reader) (zapcore.Level, error) { + var pld struct { + Level *zapcore.Level `json:"level"` + } + if err := json.NewDecoder(body).Decode(&pld); err != nil { + return 0, fmt.Errorf("malformed request body: %v", err) + } + if pld.Level == nil { + return 0, errors.New("must specify logging level") + } + return *pld.Level, nil +} diff --git a/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go b/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go new file mode 100644 index 00000000..dad583aa --- /dev/null +++ b/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go @@ -0,0 +1,31 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package bufferpool houses zap's shared internal buffer pool. Third-party +// packages can recreate the same functionality with buffers.NewPool. +package bufferpool + +import "go.uber.org/zap/buffer" + +var ( + _pool = buffer.NewPool() + // Get retrieves a buffer from the pool, creating one if necessary. + Get = _pool.Get +) diff --git a/vendor/go.uber.org/zap/internal/color/color.go b/vendor/go.uber.org/zap/internal/color/color.go new file mode 100644 index 00000000..c4d5d02a --- /dev/null +++ b/vendor/go.uber.org/zap/internal/color/color.go @@ -0,0 +1,44 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package color adds coloring functionality for TTY output. +package color + +import "fmt" + +// Foreground colors. +const ( + Black Color = iota + 30 + Red + Green + Yellow + Blue + Magenta + Cyan + White +) + +// Color represents a text color. +type Color uint8 + +// Add adds the coloring to the given string. +func (c Color) Add(s string) string { + return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s) +} diff --git a/vendor/go.uber.org/zap/internal/exit/exit.go b/vendor/go.uber.org/zap/internal/exit/exit.go new file mode 100644 index 00000000..f673f994 --- /dev/null +++ b/vendor/go.uber.org/zap/internal/exit/exit.go @@ -0,0 +1,66 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package exit provides stubs so that unit tests can exercise code that calls +// os.Exit(1). +package exit + +import "os" + +var _exit = os.Exit + +// With terminates the process by calling os.Exit(code). If the package is +// stubbed, it instead records a call in the testing spy. +func With(code int) { + _exit(code) +} + +// A StubbedExit is a testing fake for os.Exit. +type StubbedExit struct { + Exited bool + Code int + prev func(code int) +} + +// Stub substitutes a fake for the call to os.Exit(1). +func Stub() *StubbedExit { + s := &StubbedExit{prev: _exit} + _exit = s.exit + return s +} + +// WithStub runs the supplied function with Exit stubbed. It returns the stub +// used, so that users can test whether the process would have crashed. +func WithStub(f func()) *StubbedExit { + s := Stub() + defer s.Unstub() + f() + return s +} + +// Unstub restores the previous exit function. +func (se *StubbedExit) Unstub() { + _exit = se.prev +} + +func (se *StubbedExit) exit(code int) { + se.Exited = true + se.Code = code +} diff --git a/vendor/go.uber.org/zap/internal/level_enabler.go b/vendor/go.uber.org/zap/internal/level_enabler.go new file mode 100644 index 00000000..40bfed81 --- /dev/null +++ b/vendor/go.uber.org/zap/internal/level_enabler.go @@ -0,0 +1,37 @@ +// Copyright (c) 2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package internal and its subpackages hold types and functionality +// that are not part of Zap's public API. +package internal + +import "go.uber.org/zap/zapcore" + +// LeveledEnabler is an interface satisfied by LevelEnablers that are able to +// report their own level. +// +// This interface is defined to use more conveniently in tests and non-zapcore +// packages. +// This cannot be imported from zapcore because of the cyclic dependency. +type LeveledEnabler interface { + zapcore.LevelEnabler + + Level() zapcore.Level +} diff --git a/vendor/go.uber.org/zap/internal/pool/pool.go b/vendor/go.uber.org/zap/internal/pool/pool.go new file mode 100644 index 00000000..60e9d2c4 --- /dev/null +++ b/vendor/go.uber.org/zap/internal/pool/pool.go @@ -0,0 +1,58 @@ +// Copyright (c) 2023 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package pool provides internal pool utilities. +package pool + +import ( + "sync" +) + +// A Pool is a generic wrapper around [sync.Pool] to provide strongly-typed +// object pooling. +// +// Note that SA6002 (ref: https://staticcheck.io/docs/checks/#SA6002) will +// not be detected, so all internal pool use must take care to only store +// pointer types. +type Pool[T any] struct { + pool sync.Pool +} + +// New returns a new [Pool] for T, and will use fn to construct new Ts when +// the pool is empty. +func New[T any](fn func() T) *Pool[T] { + return &Pool[T]{ + pool: sync.Pool{ + New: func() any { + return fn() + }, + }, + } +} + +// Get gets a T from the pool, or creates a new one if the pool is empty. +func (p *Pool[T]) Get() T { + return p.pool.Get().(T) +} + +// Put returns x into the pool. +func (p *Pool[T]) Put(x T) { + p.pool.Put(x) +} diff --git a/vendor/go.uber.org/zap/internal/stacktrace/stack.go b/vendor/go.uber.org/zap/internal/stacktrace/stack.go new file mode 100644 index 00000000..82af7551 --- /dev/null +++ b/vendor/go.uber.org/zap/internal/stacktrace/stack.go @@ -0,0 +1,181 @@ +// Copyright (c) 2023 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package stacktrace provides support for gathering stack traces +// efficiently. +package stacktrace + +import ( + "runtime" + + "go.uber.org/zap/buffer" + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/internal/pool" +) + +var _stackPool = pool.New(func() *Stack { + return &Stack{ + storage: make([]uintptr, 64), + } +}) + +// Stack is a captured stack trace. +type Stack struct { + pcs []uintptr // program counters; always a subslice of storage + frames *runtime.Frames + + // The size of pcs varies depending on requirements: + // it will be one if the only the first frame was requested, + // and otherwise it will reflect the depth of the call stack. + // + // storage decouples the slice we need (pcs) from the slice we pool. + // We will always allocate a reasonably large storage, but we'll use + // only as much of it as we need. + storage []uintptr +} + +// Depth specifies how deep of a stack trace should be captured. +type Depth int + +const ( + // First captures only the first frame. + First Depth = iota + + // Full captures the entire call stack, allocating more + // storage for it if needed. + Full +) + +// Capture captures a stack trace of the specified depth, skipping +// the provided number of frames. skip=0 identifies the caller of +// Capture. +// +// The caller must call Free on the returned stacktrace after using it. +func Capture(skip int, depth Depth) *Stack { + stack := _stackPool.Get() + + switch depth { + case First: + stack.pcs = stack.storage[:1] + case Full: + stack.pcs = stack.storage + } + + // Unlike other "skip"-based APIs, skip=0 identifies runtime.Callers + // itself. +2 to skip captureStacktrace and runtime.Callers. + numFrames := runtime.Callers( + skip+2, + stack.pcs, + ) + + // runtime.Callers truncates the recorded stacktrace if there is no + // room in the provided slice. For the full stack trace, keep expanding + // storage until there are fewer frames than there is room. + if depth == Full { + pcs := stack.pcs + for numFrames == len(pcs) { + pcs = make([]uintptr, len(pcs)*2) + numFrames = runtime.Callers(skip+2, pcs) + } + + // Discard old storage instead of returning it to the pool. + // This will adjust the pool size over time if stack traces are + // consistently very deep. + stack.storage = pcs + stack.pcs = pcs[:numFrames] + } else { + stack.pcs = stack.pcs[:numFrames] + } + + stack.frames = runtime.CallersFrames(stack.pcs) + return stack +} + +// Free releases resources associated with this stacktrace +// and returns it back to the pool. +func (st *Stack) Free() { + st.frames = nil + st.pcs = nil + _stackPool.Put(st) +} + +// Count reports the total number of frames in this stacktrace. +// Count DOES NOT change as Next is called. +func (st *Stack) Count() int { + return len(st.pcs) +} + +// Next returns the next frame in the stack trace, +// and a boolean indicating whether there are more after it. +func (st *Stack) Next() (_ runtime.Frame, more bool) { + return st.frames.Next() +} + +// Take returns a string representation of the current stacktrace. +// +// skip is the number of frames to skip before recording the stack trace. +// skip=0 identifies the caller of Take. +func Take(skip int) string { + stack := Capture(skip+1, Full) + defer stack.Free() + + buffer := bufferpool.Get() + defer buffer.Free() + + stackfmt := NewFormatter(buffer) + stackfmt.FormatStack(stack) + return buffer.String() +} + +// Formatter formats a stack trace into a readable string representation. +type Formatter struct { + b *buffer.Buffer + nonEmpty bool // whehther we've written at least one frame already +} + +// NewFormatter builds a new Formatter. +func NewFormatter(b *buffer.Buffer) Formatter { + return Formatter{b: b} +} + +// FormatStack formats all remaining frames in the provided stacktrace -- minus +// the final runtime.main/runtime.goexit frame. +func (sf *Formatter) FormatStack(stack *Stack) { + // Note: On the last iteration, frames.Next() returns false, with a valid + // frame, but we ignore this frame. The last frame is a runtime frame which + // adds noise, since it's only either runtime.main or runtime.goexit. + for frame, more := stack.Next(); more; frame, more = stack.Next() { + sf.FormatFrame(frame) + } +} + +// FormatFrame formats the given frame. +func (sf *Formatter) FormatFrame(frame runtime.Frame) { + if sf.nonEmpty { + sf.b.AppendByte('\n') + } + sf.nonEmpty = true + sf.b.AppendString(frame.Function) + sf.b.AppendByte('\n') + sf.b.AppendByte('\t') + sf.b.AppendString(frame.File) + sf.b.AppendByte(':') + sf.b.AppendInt(int64(frame.Line)) +} diff --git a/vendor/go.uber.org/zap/level.go b/vendor/go.uber.org/zap/level.go new file mode 100644 index 00000000..155b208b --- /dev/null +++ b/vendor/go.uber.org/zap/level.go @@ -0,0 +1,153 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "sync/atomic" + + "go.uber.org/zap/internal" + "go.uber.org/zap/zapcore" +) + +const ( + // DebugLevel logs are typically voluminous, and are usually disabled in + // production. + DebugLevel = zapcore.DebugLevel + // InfoLevel is the default logging priority. + InfoLevel = zapcore.InfoLevel + // WarnLevel logs are more important than Info, but don't need individual + // human review. + WarnLevel = zapcore.WarnLevel + // ErrorLevel logs are high-priority. If an application is running smoothly, + // it shouldn't generate any error-level logs. + ErrorLevel = zapcore.ErrorLevel + // DPanicLevel logs are particularly important errors. In development the + // logger panics after writing the message. + DPanicLevel = zapcore.DPanicLevel + // PanicLevel logs a message, then panics. + PanicLevel = zapcore.PanicLevel + // FatalLevel logs a message, then calls os.Exit(1). + FatalLevel = zapcore.FatalLevel +) + +// LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler with +// an anonymous function. +// +// It's particularly useful when splitting log output between different +// outputs (e.g., standard error and standard out). For sample code, see the +// package-level AdvancedConfiguration example. +type LevelEnablerFunc func(zapcore.Level) bool + +// Enabled calls the wrapped function. +func (f LevelEnablerFunc) Enabled(lvl zapcore.Level) bool { return f(lvl) } + +// An AtomicLevel is an atomically changeable, dynamic logging level. It lets +// you safely change the log level of a tree of loggers (the root logger and +// any children created by adding context) at runtime. +// +// The AtomicLevel itself is an http.Handler that serves a JSON endpoint to +// alter its level. +// +// AtomicLevels must be created with the NewAtomicLevel constructor to allocate +// their internal atomic pointer. +type AtomicLevel struct { + l *atomic.Int32 +} + +var _ internal.LeveledEnabler = AtomicLevel{} + +// NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging +// enabled. +func NewAtomicLevel() AtomicLevel { + lvl := AtomicLevel{l: new(atomic.Int32)} + lvl.l.Store(int32(InfoLevel)) + return lvl +} + +// NewAtomicLevelAt is a convenience function that creates an AtomicLevel +// and then calls SetLevel with the given level. +func NewAtomicLevelAt(l zapcore.Level) AtomicLevel { + a := NewAtomicLevel() + a.SetLevel(l) + return a +} + +// ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII +// representation of the log level. If the provided ASCII representation is +// invalid an error is returned. +// +// This is particularly useful when dealing with text input to configure log +// levels. +func ParseAtomicLevel(text string) (AtomicLevel, error) { + a := NewAtomicLevel() + l, err := zapcore.ParseLevel(text) + if err != nil { + return a, err + } + + a.SetLevel(l) + return a, nil +} + +// Enabled implements the zapcore.LevelEnabler interface, which allows the +// AtomicLevel to be used in place of traditional static levels. +func (lvl AtomicLevel) Enabled(l zapcore.Level) bool { + return lvl.Level().Enabled(l) +} + +// Level returns the minimum enabled log level. +func (lvl AtomicLevel) Level() zapcore.Level { + return zapcore.Level(int8(lvl.l.Load())) +} + +// SetLevel alters the logging level. +func (lvl AtomicLevel) SetLevel(l zapcore.Level) { + lvl.l.Store(int32(l)) +} + +// String returns the string representation of the underlying Level. +func (lvl AtomicLevel) String() string { + return lvl.Level().String() +} + +// UnmarshalText unmarshals the text to an AtomicLevel. It uses the same text +// representations as the static zapcore.Levels ("debug", "info", "warn", +// "error", "dpanic", "panic", and "fatal"). +func (lvl *AtomicLevel) UnmarshalText(text []byte) error { + if lvl.l == nil { + lvl.l = &atomic.Int32{} + } + + var l zapcore.Level + if err := l.UnmarshalText(text); err != nil { + return err + } + + lvl.SetLevel(l) + return nil +} + +// MarshalText marshals the AtomicLevel to a byte slice. It uses the same +// text representation as the static zapcore.Levels ("debug", "info", "warn", +// "error", "dpanic", "panic", and "fatal"). +func (lvl AtomicLevel) MarshalText() (text []byte, err error) { + return lvl.Level().MarshalText() +} diff --git a/vendor/go.uber.org/zap/logger.go b/vendor/go.uber.org/zap/logger.go new file mode 100644 index 00000000..6205fe48 --- /dev/null +++ b/vendor/go.uber.org/zap/logger.go @@ -0,0 +1,432 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "fmt" + "io" + "os" + "strings" + + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/internal/stacktrace" + "go.uber.org/zap/zapcore" +) + +// A Logger provides fast, leveled, structured logging. All methods are safe +// for concurrent use. +// +// The Logger is designed for contexts in which every microsecond and every +// allocation matters, so its API intentionally favors performance and type +// safety over brevity. For most applications, the SugaredLogger strikes a +// better balance between performance and ergonomics. +type Logger struct { + core zapcore.Core + + development bool + addCaller bool + onFatal zapcore.CheckWriteHook // default is WriteThenFatal + + name string + errorOutput zapcore.WriteSyncer + + addStack zapcore.LevelEnabler + + callerSkip int + + clock zapcore.Clock +} + +// New constructs a new Logger from the provided zapcore.Core and Options. If +// the passed zapcore.Core is nil, it falls back to using a no-op +// implementation. +// +// This is the most flexible way to construct a Logger, but also the most +// verbose. For typical use cases, the highly-opinionated presets +// (NewProduction, NewDevelopment, and NewExample) or the Config struct are +// more convenient. +// +// For sample code, see the package-level AdvancedConfiguration example. +func New(core zapcore.Core, options ...Option) *Logger { + if core == nil { + return NewNop() + } + log := &Logger{ + core: core, + errorOutput: zapcore.Lock(os.Stderr), + addStack: zapcore.FatalLevel + 1, + clock: zapcore.DefaultClock, + } + return log.WithOptions(options...) +} + +// NewNop returns a no-op Logger. It never writes out logs or internal errors, +// and it never runs user-defined hooks. +// +// Using WithOptions to replace the Core or error output of a no-op Logger can +// re-enable logging. +func NewNop() *Logger { + return &Logger{ + core: zapcore.NewNopCore(), + errorOutput: zapcore.AddSync(io.Discard), + addStack: zapcore.FatalLevel + 1, + clock: zapcore.DefaultClock, + } +} + +// NewProduction builds a sensible production Logger that writes InfoLevel and +// above logs to standard error as JSON. +// +// It's a shortcut for NewProductionConfig().Build(...Option). +func NewProduction(options ...Option) (*Logger, error) { + return NewProductionConfig().Build(options...) +} + +// NewDevelopment builds a development Logger that writes DebugLevel and above +// logs to standard error in a human-friendly format. +// +// It's a shortcut for NewDevelopmentConfig().Build(...Option). +func NewDevelopment(options ...Option) (*Logger, error) { + return NewDevelopmentConfig().Build(options...) +} + +// Must is a helper that wraps a call to a function returning (*Logger, error) +// and panics if the error is non-nil. It is intended for use in variable +// initialization such as: +// +// var logger = zap.Must(zap.NewProduction()) +func Must(logger *Logger, err error) *Logger { + if err != nil { + panic(err) + } + + return logger +} + +// NewExample builds a Logger that's designed for use in zap's testable +// examples. It writes DebugLevel and above logs to standard out as JSON, but +// omits the timestamp and calling function to keep example output +// short and deterministic. +func NewExample(options ...Option) *Logger { + encoderCfg := zapcore.EncoderConfig{ + MessageKey: "msg", + LevelKey: "level", + NameKey: "logger", + EncodeLevel: zapcore.LowercaseLevelEncoder, + EncodeTime: zapcore.ISO8601TimeEncoder, + EncodeDuration: zapcore.StringDurationEncoder, + } + core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel) + return New(core).WithOptions(options...) +} + +// Sugar wraps the Logger to provide a more ergonomic, but slightly slower, +// API. Sugaring a Logger is quite inexpensive, so it's reasonable for a +// single application to use both Loggers and SugaredLoggers, converting +// between them on the boundaries of performance-sensitive code. +func (log *Logger) Sugar() *SugaredLogger { + core := log.clone() + core.callerSkip += 2 + return &SugaredLogger{core} +} + +// Named adds a new path segment to the logger's name. Segments are joined by +// periods. By default, Loggers are unnamed. +func (log *Logger) Named(s string) *Logger { + if s == "" { + return log + } + l := log.clone() + if log.name == "" { + l.name = s + } else { + l.name = strings.Join([]string{l.name, s}, ".") + } + return l +} + +// WithOptions clones the current Logger, applies the supplied Options, and +// returns the resulting Logger. It's safe to use concurrently. +func (log *Logger) WithOptions(opts ...Option) *Logger { + c := log.clone() + for _, opt := range opts { + opt.apply(c) + } + return c +} + +// With creates a child logger and adds structured context to it. Fields added +// to the child don't affect the parent, and vice versa. Any fields that +// require evaluation (such as Objects) are evaluated upon invocation of With. +func (log *Logger) With(fields ...Field) *Logger { + if len(fields) == 0 { + return log + } + l := log.clone() + l.core = l.core.With(fields) + return l +} + +// WithLazy creates a child logger and adds structured context to it lazily. +// +// The fields are evaluated only if the logger is further chained with [With] +// or is written to with any of the log level methods. +// Until that occurs, the logger may retain references to objects inside the fields, +// and logging will reflect the state of an object at the time of logging, +// not the time of WithLazy(). +// +// WithLazy provides a worthwhile performance optimization for contextual loggers +// when the likelihood of using the child logger is low, +// such as error paths and rarely taken branches. +// +// Similar to [With], fields added to the child don't affect the parent, and vice versa. +func (log *Logger) WithLazy(fields ...Field) *Logger { + if len(fields) == 0 { + return log + } + return log.WithOptions(WrapCore(func(core zapcore.Core) zapcore.Core { + return zapcore.NewLazyWith(core, fields) + })) +} + +// Level reports the minimum enabled level for this logger. +// +// For NopLoggers, this is [zapcore.InvalidLevel]. +func (log *Logger) Level() zapcore.Level { + return zapcore.LevelOf(log.core) +} + +// Check returns a CheckedEntry if logging a message at the specified level +// is enabled. It's a completely optional optimization; in high-performance +// applications, Check can help avoid allocating a slice to hold fields. +func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { + return log.check(lvl, msg) +} + +// Log logs a message at the specified level. The message includes any fields +// passed at the log site, as well as any fields accumulated on the logger. +// Any Fields that require evaluation (such as Objects) are evaluated upon +// invocation of Log. +func (log *Logger) Log(lvl zapcore.Level, msg string, fields ...Field) { + if ce := log.check(lvl, msg); ce != nil { + ce.Write(fields...) + } +} + +// Debug logs a message at DebugLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Debug(msg string, fields ...Field) { + if ce := log.check(DebugLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Info logs a message at InfoLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Info(msg string, fields ...Field) { + if ce := log.check(InfoLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Warn logs a message at WarnLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Warn(msg string, fields ...Field) { + if ce := log.check(WarnLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Error logs a message at ErrorLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Error(msg string, fields ...Field) { + if ce := log.check(ErrorLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// DPanic logs a message at DPanicLevel. The message includes any fields +// passed at the log site, as well as any fields accumulated on the logger. +// +// If the logger is in development mode, it then panics (DPanic means +// "development panic"). This is useful for catching errors that are +// recoverable, but shouldn't ever happen. +func (log *Logger) DPanic(msg string, fields ...Field) { + if ce := log.check(DPanicLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Panic logs a message at PanicLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +// +// The logger then panics, even if logging at PanicLevel is disabled. +func (log *Logger) Panic(msg string, fields ...Field) { + if ce := log.check(PanicLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Fatal logs a message at FatalLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +// +// The logger then calls os.Exit(1), even if logging at FatalLevel is +// disabled. +func (log *Logger) Fatal(msg string, fields ...Field) { + if ce := log.check(FatalLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Sync calls the underlying Core's Sync method, flushing any buffered log +// entries. Applications should take care to call Sync before exiting. +func (log *Logger) Sync() error { + return log.core.Sync() +} + +// Core returns the Logger's underlying zapcore.Core. +func (log *Logger) Core() zapcore.Core { + return log.core +} + +// Name returns the Logger's underlying name, +// or an empty string if the logger is unnamed. +func (log *Logger) Name() string { + return log.name +} + +func (log *Logger) clone() *Logger { + clone := *log + return &clone +} + +func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { + // Logger.check must always be called directly by a method in the + // Logger interface (e.g., Check, Info, Fatal). + // This skips Logger.check and the Info/Fatal/Check/etc. method that + // called it. + const callerSkipOffset = 2 + + // Check the level first to reduce the cost of disabled log calls. + // Since Panic and higher may exit, we skip the optimization for those levels. + if lvl < zapcore.DPanicLevel && !log.core.Enabled(lvl) { + return nil + } + + // Create basic checked entry thru the core; this will be non-nil if the + // log message will actually be written somewhere. + ent := zapcore.Entry{ + LoggerName: log.name, + Time: log.clock.Now(), + Level: lvl, + Message: msg, + } + ce := log.core.Check(ent, nil) + willWrite := ce != nil + + // Set up any required terminal behavior. + switch ent.Level { + case zapcore.PanicLevel: + ce = ce.After(ent, zapcore.WriteThenPanic) + case zapcore.FatalLevel: + onFatal := log.onFatal + // nil or WriteThenNoop will lead to continued execution after + // a Fatal log entry, which is unexpected. For example, + // + // f, err := os.Open(..) + // if err != nil { + // log.Fatal("cannot open", zap.Error(err)) + // } + // fmt.Println(f.Name()) + // + // The f.Name() will panic if we continue execution after the + // log.Fatal. + if onFatal == nil || onFatal == zapcore.WriteThenNoop { + onFatal = zapcore.WriteThenFatal + } + ce = ce.After(ent, onFatal) + case zapcore.DPanicLevel: + if log.development { + ce = ce.After(ent, zapcore.WriteThenPanic) + } + } + + // Only do further annotation if we're going to write this message; checked + // entries that exist only for terminal behavior don't benefit from + // annotation. + if !willWrite { + return ce + } + + // Thread the error output through to the CheckedEntry. + ce.ErrorOutput = log.errorOutput + + addStack := log.addStack.Enabled(ce.Level) + if !log.addCaller && !addStack { + return ce + } + + // Adding the caller or stack trace requires capturing the callers of + // this function. We'll share information between these two. + stackDepth := stacktrace.First + if addStack { + stackDepth = stacktrace.Full + } + stack := stacktrace.Capture(log.callerSkip+callerSkipOffset, stackDepth) + defer stack.Free() + + if stack.Count() == 0 { + if log.addCaller { + fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC()) + _ = log.errorOutput.Sync() + } + return ce + } + + frame, more := stack.Next() + + if log.addCaller { + ce.Caller = zapcore.EntryCaller{ + Defined: frame.PC != 0, + PC: frame.PC, + File: frame.File, + Line: frame.Line, + Function: frame.Function, + } + } + + if addStack { + buffer := bufferpool.Get() + defer buffer.Free() + + stackfmt := stacktrace.NewFormatter(buffer) + + // We've already extracted the first frame, so format that + // separately and defer to stackfmt for the rest. + stackfmt.FormatFrame(frame) + if more { + stackfmt.FormatStack(stack) + } + ce.Stack = buffer.String() + } + + return ce +} diff --git a/vendor/go.uber.org/zap/options.go b/vendor/go.uber.org/zap/options.go new file mode 100644 index 00000000..c4f3bca3 --- /dev/null +++ b/vendor/go.uber.org/zap/options.go @@ -0,0 +1,167 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "fmt" + + "go.uber.org/zap/zapcore" +) + +// An Option configures a Logger. +type Option interface { + apply(*Logger) +} + +// optionFunc wraps a func so it satisfies the Option interface. +type optionFunc func(*Logger) + +func (f optionFunc) apply(log *Logger) { + f(log) +} + +// WrapCore wraps or replaces the Logger's underlying zapcore.Core. +func WrapCore(f func(zapcore.Core) zapcore.Core) Option { + return optionFunc(func(log *Logger) { + log.core = f(log.core) + }) +} + +// Hooks registers functions which will be called each time the Logger writes +// out an Entry. Repeated use of Hooks is additive. +// +// Hooks are useful for simple side effects, like capturing metrics for the +// number of emitted logs. More complex side effects, including anything that +// requires access to the Entry's structured fields, should be implemented as +// a zapcore.Core instead. See zapcore.RegisterHooks for details. +func Hooks(hooks ...func(zapcore.Entry) error) Option { + return optionFunc(func(log *Logger) { + log.core = zapcore.RegisterHooks(log.core, hooks...) + }) +} + +// Fields adds fields to the Logger. +func Fields(fs ...Field) Option { + return optionFunc(func(log *Logger) { + log.core = log.core.With(fs) + }) +} + +// ErrorOutput sets the destination for errors generated by the Logger. Note +// that this option only affects internal errors; for sample code that sends +// error-level logs to a different location from info- and debug-level logs, +// see the package-level AdvancedConfiguration example. +// +// The supplied WriteSyncer must be safe for concurrent use. The Open and +// zapcore.Lock functions are the simplest ways to protect files with a mutex. +func ErrorOutput(w zapcore.WriteSyncer) Option { + return optionFunc(func(log *Logger) { + log.errorOutput = w + }) +} + +// Development puts the logger in development mode, which makes DPanic-level +// logs panic instead of simply logging an error. +func Development() Option { + return optionFunc(func(log *Logger) { + log.development = true + }) +} + +// AddCaller configures the Logger to annotate each message with the filename, +// line number, and function name of zap's caller. See also WithCaller. +func AddCaller() Option { + return WithCaller(true) +} + +// WithCaller configures the Logger to annotate each message with the filename, +// line number, and function name of zap's caller, or not, depending on the +// value of enabled. This is a generalized form of AddCaller. +func WithCaller(enabled bool) Option { + return optionFunc(func(log *Logger) { + log.addCaller = enabled + }) +} + +// AddCallerSkip increases the number of callers skipped by caller annotation +// (as enabled by the AddCaller option). When building wrappers around the +// Logger and SugaredLogger, supplying this Option prevents zap from always +// reporting the wrapper code as the caller. +func AddCallerSkip(skip int) Option { + return optionFunc(func(log *Logger) { + log.callerSkip += skip + }) +} + +// AddStacktrace configures the Logger to record a stack trace for all messages at +// or above a given level. +func AddStacktrace(lvl zapcore.LevelEnabler) Option { + return optionFunc(func(log *Logger) { + log.addStack = lvl + }) +} + +// IncreaseLevel increase the level of the logger. It has no effect if +// the passed in level tries to decrease the level of the logger. +func IncreaseLevel(lvl zapcore.LevelEnabler) Option { + return optionFunc(func(log *Logger) { + core, err := zapcore.NewIncreaseLevelCore(log.core, lvl) + if err != nil { + fmt.Fprintf(log.errorOutput, "failed to IncreaseLevel: %v\n", err) + } else { + log.core = core + } + }) +} + +// OnFatal sets the action to take on fatal logs. +// +// Deprecated: Use [WithFatalHook] instead. +func OnFatal(action zapcore.CheckWriteAction) Option { + return WithFatalHook(action) +} + +// WithFatalHook sets a CheckWriteHook to run on fatal logs. +// Zap will call this hook after writing a log statement with a Fatal level. +// +// For example, the following builds a logger that will exit the current +// goroutine after writing a fatal log message, but it will not exit the +// program. +// +// zap.New(core, zap.WithFatalHook(zapcore.WriteThenGoexit)) +// +// It is important that the provided CheckWriteHook stops the control flow at +// the current statement to meet expectations of callers of the logger. +// We recommend calling os.Exit or runtime.Goexit inside custom hooks at +// minimum. +func WithFatalHook(hook zapcore.CheckWriteHook) Option { + return optionFunc(func(log *Logger) { + log.onFatal = hook + }) +} + +// WithClock specifies the clock used by the logger to determine the current +// time for logged entries. Defaults to the system clock with time.Now. +func WithClock(clock zapcore.Clock) Option { + return optionFunc(func(log *Logger) { + log.clock = clock + }) +} diff --git a/vendor/go.uber.org/zap/sink.go b/vendor/go.uber.org/zap/sink.go new file mode 100644 index 00000000..499772a0 --- /dev/null +++ b/vendor/go.uber.org/zap/sink.go @@ -0,0 +1,180 @@ +// Copyright (c) 2016-2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + + "go.uber.org/zap/zapcore" +) + +const schemeFile = "file" + +var _sinkRegistry = newSinkRegistry() + +// Sink defines the interface to write to and close logger destinations. +type Sink interface { + zapcore.WriteSyncer + io.Closer +} + +type errSinkNotFound struct { + scheme string +} + +func (e *errSinkNotFound) Error() string { + return fmt.Sprintf("no sink found for scheme %q", e.scheme) +} + +type nopCloserSink struct{ zapcore.WriteSyncer } + +func (nopCloserSink) Close() error { return nil } + +type sinkRegistry struct { + mu sync.Mutex + factories map[string]func(*url.URL) (Sink, error) // keyed by scheme + openFile func(string, int, os.FileMode) (*os.File, error) // type matches os.OpenFile +} + +func newSinkRegistry() *sinkRegistry { + sr := &sinkRegistry{ + factories: make(map[string]func(*url.URL) (Sink, error)), + openFile: os.OpenFile, + } + // Infallible operation: the registry is empty, so we can't have a conflict. + _ = sr.RegisterSink(schemeFile, sr.newFileSinkFromURL) + return sr +} + +// RegisterScheme registers the given factory for the specific scheme. +func (sr *sinkRegistry) RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error { + sr.mu.Lock() + defer sr.mu.Unlock() + + if scheme == "" { + return errors.New("can't register a sink factory for empty string") + } + normalized, err := normalizeScheme(scheme) + if err != nil { + return fmt.Errorf("%q is not a valid scheme: %v", scheme, err) + } + if _, ok := sr.factories[normalized]; ok { + return fmt.Errorf("sink factory already registered for scheme %q", normalized) + } + sr.factories[normalized] = factory + return nil +} + +func (sr *sinkRegistry) newSink(rawURL string) (Sink, error) { + // URL parsing doesn't work well for Windows paths such as `c:\log.txt`, as scheme is set to + // the drive, and path is unset unless `c:/log.txt` is used. + // To avoid Windows-specific URL handling, we instead check IsAbs to open as a file. + // filepath.IsAbs is OS-specific, so IsAbs('c:/log.txt') is false outside of Windows. + if filepath.IsAbs(rawURL) { + return sr.newFileSinkFromPath(rawURL) + } + + u, err := url.Parse(rawURL) + if err != nil { + return nil, fmt.Errorf("can't parse %q as a URL: %v", rawURL, err) + } + if u.Scheme == "" { + u.Scheme = schemeFile + } + + sr.mu.Lock() + factory, ok := sr.factories[u.Scheme] + sr.mu.Unlock() + if !ok { + return nil, &errSinkNotFound{u.Scheme} + } + return factory(u) +} + +// RegisterSink registers a user-supplied factory for all sinks with a +// particular scheme. +// +// All schemes must be ASCII, valid under section 0.1 of RFC 3986 +// (https://tools.ietf.org/html/rfc3983#section-3.1), and must not already +// have a factory registered. Zap automatically registers a factory for the +// "file" scheme. +func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error { + return _sinkRegistry.RegisterSink(scheme, factory) +} + +func (sr *sinkRegistry) newFileSinkFromURL(u *url.URL) (Sink, error) { + if u.User != nil { + return nil, fmt.Errorf("user and password not allowed with file URLs: got %v", u) + } + if u.Fragment != "" { + return nil, fmt.Errorf("fragments not allowed with file URLs: got %v", u) + } + if u.RawQuery != "" { + return nil, fmt.Errorf("query parameters not allowed with file URLs: got %v", u) + } + // Error messages are better if we check hostname and port separately. + if u.Port() != "" { + return nil, fmt.Errorf("ports not allowed with file URLs: got %v", u) + } + if hn := u.Hostname(); hn != "" && hn != "localhost" { + return nil, fmt.Errorf("file URLs must leave host empty or use localhost: got %v", u) + } + + return sr.newFileSinkFromPath(u.Path) +} + +func (sr *sinkRegistry) newFileSinkFromPath(path string) (Sink, error) { + switch path { + case "stdout": + return nopCloserSink{os.Stdout}, nil + case "stderr": + return nopCloserSink{os.Stderr}, nil + } + return sr.openFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666) +} + +func normalizeScheme(s string) (string, error) { + // https://tools.ietf.org/html/rfc3986#section-3.1 + s = strings.ToLower(s) + if first := s[0]; 'a' > first || 'z' < first { + return "", errors.New("must start with a letter") + } + for i := 1; i < len(s); i++ { // iterate over bytes, not runes + c := s[i] + switch { + case 'a' <= c && c <= 'z': + continue + case '0' <= c && c <= '9': + continue + case c == '.' || c == '+' || c == '-': + continue + } + return "", fmt.Errorf("may not contain %q", c) + } + return s, nil +} diff --git a/vendor/go.uber.org/zap/sugar.go b/vendor/go.uber.org/zap/sugar.go new file mode 100644 index 00000000..00ac5fe3 --- /dev/null +++ b/vendor/go.uber.org/zap/sugar.go @@ -0,0 +1,437 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "fmt" + + "go.uber.org/zap/zapcore" + + "go.uber.org/multierr" +) + +const ( + _oddNumberErrMsg = "Ignored key without a value." + _nonStringKeyErrMsg = "Ignored key-value pairs with non-string keys." + _multipleErrMsg = "Multiple errors without a key." +) + +// A SugaredLogger wraps the base Logger functionality in a slower, but less +// verbose, API. Any Logger can be converted to a SugaredLogger with its Sugar +// method. +// +// Unlike the Logger, the SugaredLogger doesn't insist on structured logging. +// For each log level, it exposes four methods: +// +// - methods named after the log level for log.Print-style logging +// - methods ending in "w" for loosely-typed structured logging +// - methods ending in "f" for log.Printf-style logging +// - methods ending in "ln" for log.Println-style logging +// +// For example, the methods for InfoLevel are: +// +// Info(...any) Print-style logging +// Infow(...any) Structured logging (read as "info with") +// Infof(string, ...any) Printf-style logging +// Infoln(...any) Println-style logging +type SugaredLogger struct { + base *Logger +} + +// Desugar unwraps a SugaredLogger, exposing the original Logger. Desugaring +// is quite inexpensive, so it's reasonable for a single application to use +// both Loggers and SugaredLoggers, converting between them on the boundaries +// of performance-sensitive code. +func (s *SugaredLogger) Desugar() *Logger { + base := s.base.clone() + base.callerSkip -= 2 + return base +} + +// Named adds a sub-scope to the logger's name. See Logger.Named for details. +func (s *SugaredLogger) Named(name string) *SugaredLogger { + return &SugaredLogger{base: s.base.Named(name)} +} + +// WithOptions clones the current SugaredLogger, applies the supplied Options, +// and returns the result. It's safe to use concurrently. +func (s *SugaredLogger) WithOptions(opts ...Option) *SugaredLogger { + base := s.base.clone() + for _, opt := range opts { + opt.apply(base) + } + return &SugaredLogger{base: base} +} + +// With adds a variadic number of fields to the logging context. It accepts a +// mix of strongly-typed Field objects and loosely-typed key-value pairs. When +// processing pairs, the first element of the pair is used as the field key +// and the second as the field value. +// +// For example, +// +// sugaredLogger.With( +// "hello", "world", +// "failure", errors.New("oh no"), +// Stack(), +// "count", 42, +// "user", User{Name: "alice"}, +// ) +// +// is the equivalent of +// +// unsugared.With( +// String("hello", "world"), +// String("failure", "oh no"), +// Stack(), +// Int("count", 42), +// Object("user", User{Name: "alice"}), +// ) +// +// Note that the keys in key-value pairs should be strings. In development, +// passing a non-string key panics. In production, the logger is more +// forgiving: a separate error is logged, but the key-value pair is skipped +// and execution continues. Passing an orphaned key triggers similar behavior: +// panics in development and errors in production. +func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger { + return &SugaredLogger{base: s.base.With(s.sweetenFields(args)...)} +} + +// Level reports the minimum enabled level for this logger. +// +// For NopLoggers, this is [zapcore.InvalidLevel]. +func (s *SugaredLogger) Level() zapcore.Level { + return zapcore.LevelOf(s.base.core) +} + +// Debug logs the provided arguments at [DebugLevel]. +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) Debug(args ...interface{}) { + s.log(DebugLevel, "", args, nil) +} + +// Info logs the provided arguments at [InfoLevel]. +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) Info(args ...interface{}) { + s.log(InfoLevel, "", args, nil) +} + +// Warn logs the provided arguments at [WarnLevel]. +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) Warn(args ...interface{}) { + s.log(WarnLevel, "", args, nil) +} + +// Error logs the provided arguments at [ErrorLevel]. +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) Error(args ...interface{}) { + s.log(ErrorLevel, "", args, nil) +} + +// DPanic logs the provided arguments at [DPanicLevel]. +// In development, the logger then panics. (See [DPanicLevel] for details.) +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) DPanic(args ...interface{}) { + s.log(DPanicLevel, "", args, nil) +} + +// Panic constructs a message with the provided arguments and panics. +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) Panic(args ...interface{}) { + s.log(PanicLevel, "", args, nil) +} + +// Fatal constructs a message with the provided arguments and calls os.Exit. +// Spaces are added between arguments when neither is a string. +func (s *SugaredLogger) Fatal(args ...interface{}) { + s.log(FatalLevel, "", args, nil) +} + +// Debugf formats the message according to the format specifier +// and logs it at [DebugLevel]. +func (s *SugaredLogger) Debugf(template string, args ...interface{}) { + s.log(DebugLevel, template, args, nil) +} + +// Infof formats the message according to the format specifier +// and logs it at [InfoLevel]. +func (s *SugaredLogger) Infof(template string, args ...interface{}) { + s.log(InfoLevel, template, args, nil) +} + +// Warnf formats the message according to the format specifier +// and logs it at [WarnLevel]. +func (s *SugaredLogger) Warnf(template string, args ...interface{}) { + s.log(WarnLevel, template, args, nil) +} + +// Errorf formats the message according to the format specifier +// and logs it at [ErrorLevel]. +func (s *SugaredLogger) Errorf(template string, args ...interface{}) { + s.log(ErrorLevel, template, args, nil) +} + +// DPanicf formats the message according to the format specifier +// and logs it at [DPanicLevel]. +// In development, the logger then panics. (See [DPanicLevel] for details.) +func (s *SugaredLogger) DPanicf(template string, args ...interface{}) { + s.log(DPanicLevel, template, args, nil) +} + +// Panicf formats the message according to the format specifier +// and panics. +func (s *SugaredLogger) Panicf(template string, args ...interface{}) { + s.log(PanicLevel, template, args, nil) +} + +// Fatalf formats the message according to the format specifier +// and calls os.Exit. +func (s *SugaredLogger) Fatalf(template string, args ...interface{}) { + s.log(FatalLevel, template, args, nil) +} + +// Debugw logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +// +// When debug-level logging is disabled, this is much faster than +// +// s.With(keysAndValues).Debug(msg) +func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{}) { + s.log(DebugLevel, msg, nil, keysAndValues) +} + +// Infow logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{}) { + s.log(InfoLevel, msg, nil, keysAndValues) +} + +// Warnw logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{}) { + s.log(WarnLevel, msg, nil, keysAndValues) +} + +// Errorw logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{}) { + s.log(ErrorLevel, msg, nil, keysAndValues) +} + +// DPanicw logs a message with some additional context. In development, the +// logger then panics. (See DPanicLevel for details.) The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{}) { + s.log(DPanicLevel, msg, nil, keysAndValues) +} + +// Panicw logs a message with some additional context, then panics. The +// variadic key-value pairs are treated as they are in With. +func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{}) { + s.log(PanicLevel, msg, nil, keysAndValues) +} + +// Fatalw logs a message with some additional context, then calls os.Exit. The +// variadic key-value pairs are treated as they are in With. +func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{}) { + s.log(FatalLevel, msg, nil, keysAndValues) +} + +// Debugln logs a message at [DebugLevel]. +// Spaces are always added between arguments. +func (s *SugaredLogger) Debugln(args ...interface{}) { + s.logln(DebugLevel, args, nil) +} + +// Infoln logs a message at [InfoLevel]. +// Spaces are always added between arguments. +func (s *SugaredLogger) Infoln(args ...interface{}) { + s.logln(InfoLevel, args, nil) +} + +// Warnln logs a message at [WarnLevel]. +// Spaces are always added between arguments. +func (s *SugaredLogger) Warnln(args ...interface{}) { + s.logln(WarnLevel, args, nil) +} + +// Errorln logs a message at [ErrorLevel]. +// Spaces are always added between arguments. +func (s *SugaredLogger) Errorln(args ...interface{}) { + s.logln(ErrorLevel, args, nil) +} + +// DPanicln logs a message at [DPanicLevel]. +// In development, the logger then panics. (See [DPanicLevel] for details.) +// Spaces are always added between arguments. +func (s *SugaredLogger) DPanicln(args ...interface{}) { + s.logln(DPanicLevel, args, nil) +} + +// Panicln logs a message at [PanicLevel] and panics. +// Spaces are always added between arguments. +func (s *SugaredLogger) Panicln(args ...interface{}) { + s.logln(PanicLevel, args, nil) +} + +// Fatalln logs a message at [FatalLevel] and calls os.Exit. +// Spaces are always added between arguments. +func (s *SugaredLogger) Fatalln(args ...interface{}) { + s.logln(FatalLevel, args, nil) +} + +// Sync flushes any buffered log entries. +func (s *SugaredLogger) Sync() error { + return s.base.Sync() +} + +// log message with Sprint, Sprintf, or neither. +func (s *SugaredLogger) log(lvl zapcore.Level, template string, fmtArgs []interface{}, context []interface{}) { + // If logging at this level is completely disabled, skip the overhead of + // string formatting. + if lvl < DPanicLevel && !s.base.Core().Enabled(lvl) { + return + } + + msg := getMessage(template, fmtArgs) + if ce := s.base.Check(lvl, msg); ce != nil { + ce.Write(s.sweetenFields(context)...) + } +} + +// logln message with Sprintln +func (s *SugaredLogger) logln(lvl zapcore.Level, fmtArgs []interface{}, context []interface{}) { + if lvl < DPanicLevel && !s.base.Core().Enabled(lvl) { + return + } + + msg := getMessageln(fmtArgs) + if ce := s.base.Check(lvl, msg); ce != nil { + ce.Write(s.sweetenFields(context)...) + } +} + +// getMessage format with Sprint, Sprintf, or neither. +func getMessage(template string, fmtArgs []interface{}) string { + if len(fmtArgs) == 0 { + return template + } + + if template != "" { + return fmt.Sprintf(template, fmtArgs...) + } + + if len(fmtArgs) == 1 { + if str, ok := fmtArgs[0].(string); ok { + return str + } + } + return fmt.Sprint(fmtArgs...) +} + +// getMessageln format with Sprintln. +func getMessageln(fmtArgs []interface{}) string { + msg := fmt.Sprintln(fmtArgs...) + return msg[:len(msg)-1] +} + +func (s *SugaredLogger) sweetenFields(args []interface{}) []Field { + if len(args) == 0 { + return nil + } + + var ( + // Allocate enough space for the worst case; if users pass only structured + // fields, we shouldn't penalize them with extra allocations. + fields = make([]Field, 0, len(args)) + invalid invalidPairs + seenError bool + ) + + for i := 0; i < len(args); { + // This is a strongly-typed field. Consume it and move on. + if f, ok := args[i].(Field); ok { + fields = append(fields, f) + i++ + continue + } + + // If it is an error, consume it and move on. + if err, ok := args[i].(error); ok { + if !seenError { + seenError = true + fields = append(fields, Error(err)) + } else { + s.base.Error(_multipleErrMsg, Error(err)) + } + i++ + continue + } + + // Make sure this element isn't a dangling key. + if i == len(args)-1 { + s.base.Error(_oddNumberErrMsg, Any("ignored", args[i])) + break + } + + // Consume this value and the next, treating them as a key-value pair. If the + // key isn't a string, add this pair to the slice of invalid pairs. + key, val := args[i], args[i+1] + if keyStr, ok := key.(string); !ok { + // Subsequent errors are likely, so allocate once up front. + if cap(invalid) == 0 { + invalid = make(invalidPairs, 0, len(args)/2) + } + invalid = append(invalid, invalidPair{i, key, val}) + } else { + fields = append(fields, Any(keyStr, val)) + } + i += 2 + } + + // If we encountered any invalid key-value pairs, log an error. + if len(invalid) > 0 { + s.base.Error(_nonStringKeyErrMsg, Array("invalid", invalid)) + } + return fields +} + +type invalidPair struct { + position int + key, value interface{} +} + +func (p invalidPair) MarshalLogObject(enc zapcore.ObjectEncoder) error { + enc.AddInt64("position", int64(p.position)) + Any("key", p.key).AddTo(enc) + Any("value", p.value).AddTo(enc) + return nil +} + +type invalidPairs []invalidPair + +func (ps invalidPairs) MarshalLogArray(enc zapcore.ArrayEncoder) error { + var err error + for i := range ps { + err = multierr.Append(err, enc.AppendObject(ps[i])) + } + return err +} diff --git a/vendor/go.uber.org/zap/time.go b/vendor/go.uber.org/zap/time.go new file mode 100644 index 00000000..c5a1f162 --- /dev/null +++ b/vendor/go.uber.org/zap/time.go @@ -0,0 +1,27 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import "time" + +func timeToMillis(t time.Time) int64 { + return t.UnixNano() / int64(time.Millisecond) +} diff --git a/vendor/go.uber.org/zap/writer.go b/vendor/go.uber.org/zap/writer.go new file mode 100644 index 00000000..06768c67 --- /dev/null +++ b/vendor/go.uber.org/zap/writer.go @@ -0,0 +1,98 @@ +// Copyright (c) 2016-2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zap + +import ( + "fmt" + "io" + + "go.uber.org/zap/zapcore" + + "go.uber.org/multierr" +) + +// Open is a high-level wrapper that takes a variadic number of URLs, opens or +// creates each of the specified resources, and combines them into a locked +// WriteSyncer. It also returns any error encountered and a function to close +// any opened files. +// +// Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without a +// scheme and URLs with the "file" scheme. Third-party code may register +// factories for other schemes using RegisterSink. +// +// URLs with the "file" scheme must use absolute paths on the local +// filesystem. No user, password, port, fragments, or query parameters are +// allowed, and the hostname must be empty or "localhost". +// +// Since it's common to write logs to the local filesystem, URLs without a +// scheme (e.g., "/var/log/foo.log") are treated as local file paths. Without +// a scheme, the special paths "stdout" and "stderr" are interpreted as +// os.Stdout and os.Stderr. When specified without a scheme, relative file +// paths also work. +func Open(paths ...string) (zapcore.WriteSyncer, func(), error) { + writers, closeAll, err := open(paths) + if err != nil { + return nil, nil, err + } + + writer := CombineWriteSyncers(writers...) + return writer, closeAll, nil +} + +func open(paths []string) ([]zapcore.WriteSyncer, func(), error) { + writers := make([]zapcore.WriteSyncer, 0, len(paths)) + closers := make([]io.Closer, 0, len(paths)) + closeAll := func() { + for _, c := range closers { + _ = c.Close() + } + } + + var openErr error + for _, path := range paths { + sink, err := _sinkRegistry.newSink(path) + if err != nil { + openErr = multierr.Append(openErr, fmt.Errorf("open sink %q: %w", path, err)) + continue + } + writers = append(writers, sink) + closers = append(closers, sink) + } + if openErr != nil { + closeAll() + return nil, nil, openErr + } + + return writers, closeAll, nil +} + +// CombineWriteSyncers is a utility that combines multiple WriteSyncers into a +// single, locked WriteSyncer. If no inputs are supplied, it returns a no-op +// WriteSyncer. +// +// It's provided purely as a convenience; the result is no different from +// using zapcore.NewMultiWriteSyncer and zapcore.Lock individually. +func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer { + if len(writers) == 0 { + return zapcore.AddSync(io.Discard) + } + return zapcore.Lock(zapcore.NewMultiWriteSyncer(writers...)) +} diff --git a/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go b/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go new file mode 100644 index 00000000..a40e93b3 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go @@ -0,0 +1,219 @@ +// Copyright (c) 2021 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "bufio" + "sync" + "time" + + "go.uber.org/multierr" +) + +const ( + // _defaultBufferSize specifies the default size used by Buffer. + _defaultBufferSize = 256 * 1024 // 256 kB + + // _defaultFlushInterval specifies the default flush interval for + // Buffer. + _defaultFlushInterval = 30 * time.Second +) + +// A BufferedWriteSyncer is a WriteSyncer that buffers writes in-memory before +// flushing them to a wrapped WriteSyncer after reaching some limit, or at some +// fixed interval--whichever comes first. +// +// BufferedWriteSyncer is safe for concurrent use. You don't need to use +// zapcore.Lock for WriteSyncers with BufferedWriteSyncer. +// +// To set up a BufferedWriteSyncer, construct a WriteSyncer for your log +// destination (*os.File is a valid WriteSyncer), wrap it with +// BufferedWriteSyncer, and defer a Stop() call for when you no longer need the +// object. +// +// func main() { +// ws := ... // your log destination +// bws := &zapcore.BufferedWriteSyncer{WS: ws} +// defer bws.Stop() +// +// // ... +// core := zapcore.NewCore(enc, bws, lvl) +// logger := zap.New(core) +// +// // ... +// } +// +// By default, a BufferedWriteSyncer will buffer up to 256 kilobytes of logs, +// waiting at most 30 seconds between flushes. +// You can customize these parameters by setting the Size or FlushInterval +// fields. +// For example, the following buffers up to 512 kB of logs before flushing them +// to Stderr, with a maximum of one minute between each flush. +// +// ws := &BufferedWriteSyncer{ +// WS: os.Stderr, +// Size: 512 * 1024, // 512 kB +// FlushInterval: time.Minute, +// } +// defer ws.Stop() +type BufferedWriteSyncer struct { + // WS is the WriteSyncer around which BufferedWriteSyncer will buffer + // writes. + // + // This field is required. + WS WriteSyncer + + // Size specifies the maximum amount of data the writer will buffered + // before flushing. + // + // Defaults to 256 kB if unspecified. + Size int + + // FlushInterval specifies how often the writer should flush data if + // there have been no writes. + // + // Defaults to 30 seconds if unspecified. + FlushInterval time.Duration + + // Clock, if specified, provides control of the source of time for the + // writer. + // + // Defaults to the system clock. + Clock Clock + + // unexported fields for state + mu sync.Mutex + initialized bool // whether initialize() has run + stopped bool // whether Stop() has run + writer *bufio.Writer + ticker *time.Ticker + stop chan struct{} // closed when flushLoop should stop + done chan struct{} // closed when flushLoop has stopped +} + +func (s *BufferedWriteSyncer) initialize() { + size := s.Size + if size == 0 { + size = _defaultBufferSize + } + + flushInterval := s.FlushInterval + if flushInterval == 0 { + flushInterval = _defaultFlushInterval + } + + if s.Clock == nil { + s.Clock = DefaultClock + } + + s.ticker = s.Clock.NewTicker(flushInterval) + s.writer = bufio.NewWriterSize(s.WS, size) + s.stop = make(chan struct{}) + s.done = make(chan struct{}) + s.initialized = true + go s.flushLoop() +} + +// Write writes log data into buffer syncer directly, multiple Write calls will be batched, +// and log data will be flushed to disk when the buffer is full or periodically. +func (s *BufferedWriteSyncer) Write(bs []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if !s.initialized { + s.initialize() + } + + // To avoid partial writes from being flushed, we manually flush the existing buffer if: + // * The current write doesn't fit into the buffer fully, and + // * The buffer is not empty (since bufio will not split large writes when the buffer is empty) + if len(bs) > s.writer.Available() && s.writer.Buffered() > 0 { + if err := s.writer.Flush(); err != nil { + return 0, err + } + } + + return s.writer.Write(bs) +} + +// Sync flushes buffered log data into disk directly. +func (s *BufferedWriteSyncer) Sync() error { + s.mu.Lock() + defer s.mu.Unlock() + + var err error + if s.initialized { + err = s.writer.Flush() + } + + return multierr.Append(err, s.WS.Sync()) +} + +// flushLoop flushes the buffer at the configured interval until Stop is +// called. +func (s *BufferedWriteSyncer) flushLoop() { + defer close(s.done) + + for { + select { + case <-s.ticker.C: + // we just simply ignore error here + // because the underlying bufio writer stores any errors + // and we return any error from Sync() as part of the close + _ = s.Sync() + case <-s.stop: + return + } + } +} + +// Stop closes the buffer, cleans up background goroutines, and flushes +// remaining unwritten data. +func (s *BufferedWriteSyncer) Stop() (err error) { + var stopped bool + + // Critical section. + func() { + s.mu.Lock() + defer s.mu.Unlock() + + if !s.initialized { + return + } + + stopped = s.stopped + if stopped { + return + } + s.stopped = true + + s.ticker.Stop() + close(s.stop) // tell flushLoop to stop + <-s.done // and wait until it has + }() + + // Don't call Sync on consecutive Stops. + if !stopped { + err = s.Sync() + } + + return err +} diff --git a/vendor/go.uber.org/zap/zapcore/clock.go b/vendor/go.uber.org/zap/zapcore/clock.go new file mode 100644 index 00000000..422fd82a --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/clock.go @@ -0,0 +1,48 @@ +// Copyright (c) 2021 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "time" + +// DefaultClock is the default clock used by Zap in operations that require +// time. This clock uses the system clock for all operations. +var DefaultClock = systemClock{} + +// Clock is a source of time for logged entries. +type Clock interface { + // Now returns the current local time. + Now() time.Time + + // NewTicker returns *time.Ticker that holds a channel + // that delivers "ticks" of a clock. + NewTicker(time.Duration) *time.Ticker +} + +// systemClock implements default Clock that uses system time. +type systemClock struct{} + +func (systemClock) Now() time.Time { + return time.Now() +} + +func (systemClock) NewTicker(duration time.Duration) *time.Ticker { + return time.NewTicker(duration) +} diff --git a/vendor/go.uber.org/zap/zapcore/console_encoder.go b/vendor/go.uber.org/zap/zapcore/console_encoder.go new file mode 100644 index 00000000..8ca0bfaf --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/console_encoder.go @@ -0,0 +1,157 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "fmt" + + "go.uber.org/zap/buffer" + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/internal/pool" +) + +var _sliceEncoderPool = pool.New(func() *sliceArrayEncoder { + return &sliceArrayEncoder{ + elems: make([]interface{}, 0, 2), + } +}) + +func getSliceEncoder() *sliceArrayEncoder { + return _sliceEncoderPool.Get() +} + +func putSliceEncoder(e *sliceArrayEncoder) { + e.elems = e.elems[:0] + _sliceEncoderPool.Put(e) +} + +type consoleEncoder struct { + *jsonEncoder +} + +// NewConsoleEncoder creates an encoder whose output is designed for human - +// rather than machine - consumption. It serializes the core log entry data +// (message, level, timestamp, etc.) in a plain-text format and leaves the +// structured context as JSON. +// +// Note that although the console encoder doesn't use the keys specified in the +// encoder configuration, it will omit any element whose key is set to the empty +// string. +func NewConsoleEncoder(cfg EncoderConfig) Encoder { + if cfg.ConsoleSeparator == "" { + // Use a default delimiter of '\t' for backwards compatibility + cfg.ConsoleSeparator = "\t" + } + return consoleEncoder{newJSONEncoder(cfg, true)} +} + +func (c consoleEncoder) Clone() Encoder { + return consoleEncoder{c.jsonEncoder.Clone().(*jsonEncoder)} +} + +func (c consoleEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { + line := bufferpool.Get() + + // We don't want the entry's metadata to be quoted and escaped (if it's + // encoded as strings), which means that we can't use the JSON encoder. The + // simplest option is to use the memory encoder and fmt.Fprint. + // + // If this ever becomes a performance bottleneck, we can implement + // ArrayEncoder for our plain-text format. + arr := getSliceEncoder() + if c.TimeKey != "" && c.EncodeTime != nil { + c.EncodeTime(ent.Time, arr) + } + if c.LevelKey != "" && c.EncodeLevel != nil { + c.EncodeLevel(ent.Level, arr) + } + if ent.LoggerName != "" && c.NameKey != "" { + nameEncoder := c.EncodeName + + if nameEncoder == nil { + // Fall back to FullNameEncoder for backward compatibility. + nameEncoder = FullNameEncoder + } + + nameEncoder(ent.LoggerName, arr) + } + if ent.Caller.Defined { + if c.CallerKey != "" && c.EncodeCaller != nil { + c.EncodeCaller(ent.Caller, arr) + } + if c.FunctionKey != "" { + arr.AppendString(ent.Caller.Function) + } + } + for i := range arr.elems { + if i > 0 { + line.AppendString(c.ConsoleSeparator) + } + fmt.Fprint(line, arr.elems[i]) + } + putSliceEncoder(arr) + + // Add the message itself. + if c.MessageKey != "" { + c.addSeparatorIfNecessary(line) + line.AppendString(ent.Message) + } + + // Add any structured context. + c.writeContext(line, fields) + + // If there's no stacktrace key, honor that; this allows users to force + // single-line output. + if ent.Stack != "" && c.StacktraceKey != "" { + line.AppendByte('\n') + line.AppendString(ent.Stack) + } + + line.AppendString(c.LineEnding) + return line, nil +} + +func (c consoleEncoder) writeContext(line *buffer.Buffer, extra []Field) { + context := c.jsonEncoder.Clone().(*jsonEncoder) + defer func() { + // putJSONEncoder assumes the buffer is still used, but we write out the buffer so + // we can free it. + context.buf.Free() + putJSONEncoder(context) + }() + + addFields(context, extra) + context.closeOpenNamespaces() + if context.buf.Len() == 0 { + return + } + + c.addSeparatorIfNecessary(line) + line.AppendByte('{') + line.Write(context.buf.Bytes()) + line.AppendByte('}') +} + +func (c consoleEncoder) addSeparatorIfNecessary(line *buffer.Buffer) { + if line.Len() > 0 { + line.AppendString(c.ConsoleSeparator) + } +} diff --git a/vendor/go.uber.org/zap/zapcore/core.go b/vendor/go.uber.org/zap/zapcore/core.go new file mode 100644 index 00000000..776e93f6 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/core.go @@ -0,0 +1,122 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +// Core is a minimal, fast logger interface. It's designed for library authors +// to wrap in a more user-friendly API. +type Core interface { + LevelEnabler + + // With adds structured context to the Core. + With([]Field) Core + // Check determines whether the supplied Entry should be logged (using the + // embedded LevelEnabler and possibly some extra logic). If the entry + // should be logged, the Core adds itself to the CheckedEntry and returns + // the result. + // + // Callers must use Check before calling Write. + Check(Entry, *CheckedEntry) *CheckedEntry + // Write serializes the Entry and any Fields supplied at the log site and + // writes them to their destination. + // + // If called, Write should always log the Entry and Fields; it should not + // replicate the logic of Check. + Write(Entry, []Field) error + // Sync flushes buffered logs (if any). + Sync() error +} + +type nopCore struct{} + +// NewNopCore returns a no-op Core. +func NewNopCore() Core { return nopCore{} } +func (nopCore) Enabled(Level) bool { return false } +func (n nopCore) With([]Field) Core { return n } +func (nopCore) Check(_ Entry, ce *CheckedEntry) *CheckedEntry { return ce } +func (nopCore) Write(Entry, []Field) error { return nil } +func (nopCore) Sync() error { return nil } + +// NewCore creates a Core that writes logs to a WriteSyncer. +func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core { + return &ioCore{ + LevelEnabler: enab, + enc: enc, + out: ws, + } +} + +type ioCore struct { + LevelEnabler + enc Encoder + out WriteSyncer +} + +var ( + _ Core = (*ioCore)(nil) + _ leveledEnabler = (*ioCore)(nil) +) + +func (c *ioCore) Level() Level { + return LevelOf(c.LevelEnabler) +} + +func (c *ioCore) With(fields []Field) Core { + clone := c.clone() + addFields(clone.enc, fields) + return clone +} + +func (c *ioCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + if c.Enabled(ent.Level) { + return ce.AddCore(ent, c) + } + return ce +} + +func (c *ioCore) Write(ent Entry, fields []Field) error { + buf, err := c.enc.EncodeEntry(ent, fields) + if err != nil { + return err + } + _, err = c.out.Write(buf.Bytes()) + buf.Free() + if err != nil { + return err + } + if ent.Level > ErrorLevel { + // Since we may be crashing the program, sync the output. + // Ignore Sync errors, pending a clean solution to issue #370. + _ = c.Sync() + } + return nil +} + +func (c *ioCore) Sync() error { + return c.out.Sync() +} + +func (c *ioCore) clone() *ioCore { + return &ioCore{ + LevelEnabler: c.LevelEnabler, + enc: c.enc.Clone(), + out: c.out, + } +} diff --git a/vendor/go.uber.org/zap/zapcore/doc.go b/vendor/go.uber.org/zap/zapcore/doc.go new file mode 100644 index 00000000..31000e91 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/doc.go @@ -0,0 +1,24 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Package zapcore defines and implements the low-level interfaces upon which +// zap is built. By providing alternate implementations of these interfaces, +// external packages can extend zap's capabilities. +package zapcore // import "go.uber.org/zap/zapcore" diff --git a/vendor/go.uber.org/zap/zapcore/encoder.go b/vendor/go.uber.org/zap/zapcore/encoder.go new file mode 100644 index 00000000..5769ff3e --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/encoder.go @@ -0,0 +1,451 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "encoding/json" + "io" + "time" + + "go.uber.org/zap/buffer" +) + +// DefaultLineEnding defines the default line ending when writing logs. +// Alternate line endings specified in EncoderConfig can override this +// behavior. +const DefaultLineEnding = "\n" + +// OmitKey defines the key to use when callers want to remove a key from log output. +const OmitKey = "" + +// A LevelEncoder serializes a Level to a primitive type. +type LevelEncoder func(Level, PrimitiveArrayEncoder) + +// LowercaseLevelEncoder serializes a Level to a lowercase string. For example, +// InfoLevel is serialized to "info". +func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + enc.AppendString(l.String()) +} + +// LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring. +// For example, InfoLevel is serialized to "info" and colored blue. +func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + s, ok := _levelToLowercaseColorString[l] + if !ok { + s = _unknownLevelColor.Add(l.String()) + } + enc.AppendString(s) +} + +// CapitalLevelEncoder serializes a Level to an all-caps string. For example, +// InfoLevel is serialized to "INFO". +func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + enc.AppendString(l.CapitalString()) +} + +// CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color. +// For example, InfoLevel is serialized to "INFO" and colored blue. +func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + s, ok := _levelToCapitalColorString[l] + if !ok { + s = _unknownLevelColor.Add(l.CapitalString()) + } + enc.AppendString(s) +} + +// UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled to +// CapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder, +// "colored" is unmarshaled to LowercaseColorLevelEncoder, and anything else +// is unmarshaled to LowercaseLevelEncoder. +func (e *LevelEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "capital": + *e = CapitalLevelEncoder + case "capitalColor": + *e = CapitalColorLevelEncoder + case "color": + *e = LowercaseColorLevelEncoder + default: + *e = LowercaseLevelEncoder + } + return nil +} + +// A TimeEncoder serializes a time.Time to a primitive type. +type TimeEncoder func(time.Time, PrimitiveArrayEncoder) + +// EpochTimeEncoder serializes a time.Time to a floating-point number of seconds +// since the Unix epoch. +func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + nanos := t.UnixNano() + sec := float64(nanos) / float64(time.Second) + enc.AppendFloat64(sec) +} + +// EpochMillisTimeEncoder serializes a time.Time to a floating-point number of +// milliseconds since the Unix epoch. +func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + nanos := t.UnixNano() + millis := float64(nanos) / float64(time.Millisecond) + enc.AppendFloat64(millis) +} + +// EpochNanosTimeEncoder serializes a time.Time to an integer number of +// nanoseconds since the Unix epoch. +func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + enc.AppendInt64(t.UnixNano()) +} + +func encodeTimeLayout(t time.Time, layout string, enc PrimitiveArrayEncoder) { + type appendTimeEncoder interface { + AppendTimeLayout(time.Time, string) + } + + if enc, ok := enc.(appendTimeEncoder); ok { + enc.AppendTimeLayout(t, layout) + return + } + + enc.AppendString(t.Format(layout)) +} + +// ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted string +// with millisecond precision. +// +// If enc supports AppendTimeLayout(t time.Time,layout string), it's used +// instead of appending a pre-formatted string value. +func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, "2006-01-02T15:04:05.000Z0700", enc) +} + +// RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string. +// +// If enc supports AppendTimeLayout(t time.Time,layout string), it's used +// instead of appending a pre-formatted string value. +func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, time.RFC3339, enc) +} + +// RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted string +// with nanosecond precision. +// +// If enc supports AppendTimeLayout(t time.Time,layout string), it's used +// instead of appending a pre-formatted string value. +func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, time.RFC3339Nano, enc) +} + +// TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using +// given layout. +func TimeEncoderOfLayout(layout string) TimeEncoder { + return func(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, layout, enc) + } +} + +// UnmarshalText unmarshals text to a TimeEncoder. +// "rfc3339nano" and "RFC3339Nano" are unmarshaled to RFC3339NanoTimeEncoder. +// "rfc3339" and "RFC3339" are unmarshaled to RFC3339TimeEncoder. +// "iso8601" and "ISO8601" are unmarshaled to ISO8601TimeEncoder. +// "millis" is unmarshaled to EpochMillisTimeEncoder. +// "nanos" is unmarshaled to EpochNanosEncoder. +// Anything else is unmarshaled to EpochTimeEncoder. +func (e *TimeEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "rfc3339nano", "RFC3339Nano": + *e = RFC3339NanoTimeEncoder + case "rfc3339", "RFC3339": + *e = RFC3339TimeEncoder + case "iso8601", "ISO8601": + *e = ISO8601TimeEncoder + case "millis": + *e = EpochMillisTimeEncoder + case "nanos": + *e = EpochNanosTimeEncoder + default: + *e = EpochTimeEncoder + } + return nil +} + +// UnmarshalYAML unmarshals YAML to a TimeEncoder. +// If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout. +// +// timeEncoder: +// layout: 06/01/02 03:04pm +// +// If value is string, it uses UnmarshalText. +// +// timeEncoder: iso8601 +func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error { + var o struct { + Layout string `json:"layout" yaml:"layout"` + } + if err := unmarshal(&o); err == nil { + *e = TimeEncoderOfLayout(o.Layout) + return nil + } + + var s string + if err := unmarshal(&s); err != nil { + return err + } + return e.UnmarshalText([]byte(s)) +} + +// UnmarshalJSON unmarshals JSON to a TimeEncoder as same way UnmarshalYAML does. +func (e *TimeEncoder) UnmarshalJSON(data []byte) error { + return e.UnmarshalYAML(func(v interface{}) error { + return json.Unmarshal(data, v) + }) +} + +// A DurationEncoder serializes a time.Duration to a primitive type. +type DurationEncoder func(time.Duration, PrimitiveArrayEncoder) + +// SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed. +func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendFloat64(float64(d) / float64(time.Second)) +} + +// NanosDurationEncoder serializes a time.Duration to an integer number of +// nanoseconds elapsed. +func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendInt64(int64(d)) +} + +// MillisDurationEncoder serializes a time.Duration to an integer number of +// milliseconds elapsed. +func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendInt64(d.Nanoseconds() / 1e6) +} + +// StringDurationEncoder serializes a time.Duration using its built-in String +// method. +func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendString(d.String()) +} + +// UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled +// to StringDurationEncoder, and anything else is unmarshaled to +// NanosDurationEncoder. +func (e *DurationEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "string": + *e = StringDurationEncoder + case "nanos": + *e = NanosDurationEncoder + case "ms": + *e = MillisDurationEncoder + default: + *e = SecondsDurationEncoder + } + return nil +} + +// A CallerEncoder serializes an EntryCaller to a primitive type. +type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder) + +// FullCallerEncoder serializes a caller in /full/path/to/package/file:line +// format. +func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { + // TODO: consider using a byte-oriented API to save an allocation. + enc.AppendString(caller.String()) +} + +// ShortCallerEncoder serializes a caller in package/file:line format, trimming +// all but the final directory from the full path. +func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { + // TODO: consider using a byte-oriented API to save an allocation. + enc.AppendString(caller.TrimmedPath()) +} + +// UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled to +// FullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder. +func (e *CallerEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "full": + *e = FullCallerEncoder + default: + *e = ShortCallerEncoder + } + return nil +} + +// A NameEncoder serializes a period-separated logger name to a primitive +// type. +type NameEncoder func(string, PrimitiveArrayEncoder) + +// FullNameEncoder serializes the logger name as-is. +func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder) { + enc.AppendString(loggerName) +} + +// UnmarshalText unmarshals text to a NameEncoder. Currently, everything is +// unmarshaled to FullNameEncoder. +func (e *NameEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "full": + *e = FullNameEncoder + default: + *e = FullNameEncoder + } + return nil +} + +// An EncoderConfig allows users to configure the concrete encoders supplied by +// zapcore. +type EncoderConfig struct { + // Set the keys used for each log entry. If any key is empty, that portion + // of the entry is omitted. + MessageKey string `json:"messageKey" yaml:"messageKey"` + LevelKey string `json:"levelKey" yaml:"levelKey"` + TimeKey string `json:"timeKey" yaml:"timeKey"` + NameKey string `json:"nameKey" yaml:"nameKey"` + CallerKey string `json:"callerKey" yaml:"callerKey"` + FunctionKey string `json:"functionKey" yaml:"functionKey"` + StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"` + SkipLineEnding bool `json:"skipLineEnding" yaml:"skipLineEnding"` + LineEnding string `json:"lineEnding" yaml:"lineEnding"` + // Configure the primitive representations of common complex types. For + // example, some users may want all time.Times serialized as floating-point + // seconds since epoch, while others may prefer ISO8601 strings. + EncodeLevel LevelEncoder `json:"levelEncoder" yaml:"levelEncoder"` + EncodeTime TimeEncoder `json:"timeEncoder" yaml:"timeEncoder"` + EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"` + EncodeCaller CallerEncoder `json:"callerEncoder" yaml:"callerEncoder"` + // Unlike the other primitive type encoders, EncodeName is optional. The + // zero value falls back to FullNameEncoder. + EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"` + // Configure the encoder for interface{} type objects. + // If not provided, objects are encoded using json.Encoder + NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"` + // Configures the field separator used by the console encoder. Defaults + // to tab. + ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"` +} + +// ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding a +// map- or struct-like object to the logging context. Like maps, ObjectEncoders +// aren't safe for concurrent use (though typical use shouldn't require locks). +type ObjectEncoder interface { + // Logging-specific marshalers. + AddArray(key string, marshaler ArrayMarshaler) error + AddObject(key string, marshaler ObjectMarshaler) error + + // Built-in types. + AddBinary(key string, value []byte) // for arbitrary bytes + AddByteString(key string, value []byte) // for UTF-8 encoded bytes + AddBool(key string, value bool) + AddComplex128(key string, value complex128) + AddComplex64(key string, value complex64) + AddDuration(key string, value time.Duration) + AddFloat64(key string, value float64) + AddFloat32(key string, value float32) + AddInt(key string, value int) + AddInt64(key string, value int64) + AddInt32(key string, value int32) + AddInt16(key string, value int16) + AddInt8(key string, value int8) + AddString(key, value string) + AddTime(key string, value time.Time) + AddUint(key string, value uint) + AddUint64(key string, value uint64) + AddUint32(key string, value uint32) + AddUint16(key string, value uint16) + AddUint8(key string, value uint8) + AddUintptr(key string, value uintptr) + + // AddReflected uses reflection to serialize arbitrary objects, so it can be + // slow and allocation-heavy. + AddReflected(key string, value interface{}) error + // OpenNamespace opens an isolated namespace where all subsequent fields will + // be added. Applications can use namespaces to prevent key collisions when + // injecting loggers into sub-components or third-party libraries. + OpenNamespace(key string) +} + +// ArrayEncoder is a strongly-typed, encoding-agnostic interface for adding +// array-like objects to the logging context. Of note, it supports mixed-type +// arrays even though they aren't typical in Go. Like slices, ArrayEncoders +// aren't safe for concurrent use (though typical use shouldn't require locks). +type ArrayEncoder interface { + // Built-in types. + PrimitiveArrayEncoder + + // Time-related types. + AppendDuration(time.Duration) + AppendTime(time.Time) + + // Logging-specific marshalers. + AppendArray(ArrayMarshaler) error + AppendObject(ObjectMarshaler) error + + // AppendReflected uses reflection to serialize arbitrary objects, so it's + // slow and allocation-heavy. + AppendReflected(value interface{}) error +} + +// PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals +// only in Go's built-in types. It's included only so that Duration- and +// TimeEncoders cannot trigger infinite recursion. +type PrimitiveArrayEncoder interface { + // Built-in types. + AppendBool(bool) + AppendByteString([]byte) // for UTF-8 encoded bytes + AppendComplex128(complex128) + AppendComplex64(complex64) + AppendFloat64(float64) + AppendFloat32(float32) + AppendInt(int) + AppendInt64(int64) + AppendInt32(int32) + AppendInt16(int16) + AppendInt8(int8) + AppendString(string) + AppendUint(uint) + AppendUint64(uint64) + AppendUint32(uint32) + AppendUint16(uint16) + AppendUint8(uint8) + AppendUintptr(uintptr) +} + +// Encoder is a format-agnostic interface for all log entry marshalers. Since +// log encoders don't need to support the same wide range of use cases as +// general-purpose marshalers, it's possible to make them faster and +// lower-allocation. +// +// Implementations of the ObjectEncoder interface's methods can, of course, +// freely modify the receiver. However, the Clone and EncodeEntry methods will +// be called concurrently and shouldn't modify the receiver. +type Encoder interface { + ObjectEncoder + + // Clone copies the encoder, ensuring that adding fields to the copy doesn't + // affect the original. + Clone() Encoder + + // EncodeEntry encodes an entry and fields, along with any accumulated + // context, into a byte buffer and returns it. Any fields that are empty, + // including fields on the `Entry` type, should be omitted. + EncodeEntry(Entry, []Field) (*buffer.Buffer, error) +} diff --git a/vendor/go.uber.org/zap/zapcore/entry.go b/vendor/go.uber.org/zap/zapcore/entry.go new file mode 100644 index 00000000..459a5d7c --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/entry.go @@ -0,0 +1,298 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "fmt" + "runtime" + "strings" + "time" + + "go.uber.org/multierr" + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/internal/exit" + "go.uber.org/zap/internal/pool" +) + +var _cePool = pool.New(func() *CheckedEntry { + // Pre-allocate some space for cores. + return &CheckedEntry{ + cores: make([]Core, 4), + } +}) + +func getCheckedEntry() *CheckedEntry { + ce := _cePool.Get() + ce.reset() + return ce +} + +func putCheckedEntry(ce *CheckedEntry) { + if ce == nil { + return + } + _cePool.Put(ce) +} + +// NewEntryCaller makes an EntryCaller from the return signature of +// runtime.Caller. +func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller { + if !ok { + return EntryCaller{} + } + return EntryCaller{ + PC: pc, + File: file, + Line: line, + Defined: true, + } +} + +// EntryCaller represents the caller of a logging function. +type EntryCaller struct { + Defined bool + PC uintptr + File string + Line int + Function string +} + +// String returns the full path and line number of the caller. +func (ec EntryCaller) String() string { + return ec.FullPath() +} + +// FullPath returns a /full/path/to/package/file:line description of the +// caller. +func (ec EntryCaller) FullPath() string { + if !ec.Defined { + return "undefined" + } + buf := bufferpool.Get() + buf.AppendString(ec.File) + buf.AppendByte(':') + buf.AppendInt(int64(ec.Line)) + caller := buf.String() + buf.Free() + return caller +} + +// TrimmedPath returns a package/file:line description of the caller, +// preserving only the leaf directory name and file name. +func (ec EntryCaller) TrimmedPath() string { + if !ec.Defined { + return "undefined" + } + // nb. To make sure we trim the path correctly on Windows too, we + // counter-intuitively need to use '/' and *not* os.PathSeparator here, + // because the path given originates from Go stdlib, specifically + // runtime.Caller() which (as of Mar/17) returns forward slashes even on + // Windows. + // + // See https://github.com/golang/go/issues/3335 + // and https://github.com/golang/go/issues/18151 + // + // for discussion on the issue on Go side. + // + // Find the last separator. + // + idx := strings.LastIndexByte(ec.File, '/') + if idx == -1 { + return ec.FullPath() + } + // Find the penultimate separator. + idx = strings.LastIndexByte(ec.File[:idx], '/') + if idx == -1 { + return ec.FullPath() + } + buf := bufferpool.Get() + // Keep everything after the penultimate separator. + buf.AppendString(ec.File[idx+1:]) + buf.AppendByte(':') + buf.AppendInt(int64(ec.Line)) + caller := buf.String() + buf.Free() + return caller +} + +// An Entry represents a complete log message. The entry's structured context +// is already serialized, but the log level, time, message, and call site +// information are available for inspection and modification. Any fields left +// empty will be omitted when encoding. +// +// Entries are pooled, so any functions that accept them MUST be careful not to +// retain references to them. +type Entry struct { + Level Level + Time time.Time + LoggerName string + Message string + Caller EntryCaller + Stack string +} + +// CheckWriteHook is a custom action that may be executed after an entry is +// written. +// +// Register one on a CheckedEntry with the After method. +// +// if ce := logger.Check(...); ce != nil { +// ce = ce.After(hook) +// ce.Write(...) +// } +// +// You can configure the hook for Fatal log statements at the logger level with +// the zap.WithFatalHook option. +type CheckWriteHook interface { + // OnWrite is invoked with the CheckedEntry that was written and a list + // of fields added with that entry. + // + // The list of fields DOES NOT include fields that were already added + // to the logger with the With method. + OnWrite(*CheckedEntry, []Field) +} + +// CheckWriteAction indicates what action to take after a log entry is +// processed. Actions are ordered in increasing severity. +type CheckWriteAction uint8 + +const ( + // WriteThenNoop indicates that nothing special needs to be done. It's the + // default behavior. + WriteThenNoop CheckWriteAction = iota + // WriteThenGoexit runs runtime.Goexit after Write. + WriteThenGoexit + // WriteThenPanic causes a panic after Write. + WriteThenPanic + // WriteThenFatal causes an os.Exit(1) after Write. + WriteThenFatal +) + +// OnWrite implements the OnWrite method to keep CheckWriteAction compatible +// with the new CheckWriteHook interface which deprecates CheckWriteAction. +func (a CheckWriteAction) OnWrite(ce *CheckedEntry, _ []Field) { + switch a { + case WriteThenGoexit: + runtime.Goexit() + case WriteThenPanic: + panic(ce.Message) + case WriteThenFatal: + exit.With(1) + } +} + +var _ CheckWriteHook = CheckWriteAction(0) + +// CheckedEntry is an Entry together with a collection of Cores that have +// already agreed to log it. +// +// CheckedEntry references should be created by calling AddCore or After on a +// nil *CheckedEntry. References are returned to a pool after Write, and MUST +// NOT be retained after calling their Write method. +type CheckedEntry struct { + Entry + ErrorOutput WriteSyncer + dirty bool // best-effort detection of pool misuse + after CheckWriteHook + cores []Core +} + +func (ce *CheckedEntry) reset() { + ce.Entry = Entry{} + ce.ErrorOutput = nil + ce.dirty = false + ce.after = nil + for i := range ce.cores { + // don't keep references to cores + ce.cores[i] = nil + } + ce.cores = ce.cores[:0] +} + +// Write writes the entry to the stored Cores, returns any errors, and returns +// the CheckedEntry reference to a pool for immediate re-use. Finally, it +// executes any required CheckWriteAction. +func (ce *CheckedEntry) Write(fields ...Field) { + if ce == nil { + return + } + + if ce.dirty { + if ce.ErrorOutput != nil { + // Make a best effort to detect unsafe re-use of this CheckedEntry. + // If the entry is dirty, log an internal error; because the + // CheckedEntry is being used after it was returned to the pool, + // the message may be an amalgamation from multiple call sites. + fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", ce.Time, ce.Entry) + _ = ce.ErrorOutput.Sync() // ignore error + } + return + } + ce.dirty = true + + var err error + for i := range ce.cores { + err = multierr.Append(err, ce.cores[i].Write(ce.Entry, fields)) + } + if err != nil && ce.ErrorOutput != nil { + fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", ce.Time, err) + _ = ce.ErrorOutput.Sync() // ignore error + } + + hook := ce.after + if hook != nil { + hook.OnWrite(ce, fields) + } + putCheckedEntry(ce) +} + +// AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be +// used by Core.Check implementations, and is safe to call on nil CheckedEntry +// references. +func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry { + if ce == nil { + ce = getCheckedEntry() + ce.Entry = ent + } + ce.cores = append(ce.cores, core) + return ce +} + +// Should sets this CheckedEntry's CheckWriteAction, which controls whether a +// Core will panic or fatal after writing this log entry. Like AddCore, it's +// safe to call on nil CheckedEntry references. +// +// Deprecated: Use [CheckedEntry.After] instead. +func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry { + return ce.After(ent, should) +} + +// After sets this CheckEntry's CheckWriteHook, which will be called after this +// log entry has been written. It's safe to call this on nil CheckedEntry +// references. +func (ce *CheckedEntry) After(ent Entry, hook CheckWriteHook) *CheckedEntry { + if ce == nil { + ce = getCheckedEntry() + ce.Entry = ent + } + ce.after = hook + return ce +} diff --git a/vendor/go.uber.org/zap/zapcore/error.go b/vendor/go.uber.org/zap/zapcore/error.go new file mode 100644 index 00000000..c40df132 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/error.go @@ -0,0 +1,136 @@ +// Copyright (c) 2017 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "fmt" + "reflect" + + "go.uber.org/zap/internal/pool" +) + +// Encodes the given error into fields of an object. A field with the given +// name is added for the error message. +// +// If the error implements fmt.Formatter, a field with the name ${key}Verbose +// is also added with the full verbose error message. +// +// Finally, if the error implements errorGroup (from go.uber.org/multierr) or +// causer (from github.com/pkg/errors), a ${key}Causes field is added with an +// array of objects containing the errors this error was comprised of. +// +// { +// "error": err.Error(), +// "errorVerbose": fmt.Sprintf("%+v", err), +// "errorCauses": [ +// ... +// ], +// } +func encodeError(key string, err error, enc ObjectEncoder) (retErr error) { + // Try to capture panics (from nil references or otherwise) when calling + // the Error() method + defer func() { + if rerr := recover(); rerr != nil { + // If it's a nil pointer, just say "". The likeliest causes are a + // error that fails to guard against nil or a nil pointer for a + // value receiver, and in either case, "" is a nice result. + if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { + enc.AddString(key, "") + return + } + + retErr = fmt.Errorf("PANIC=%v", rerr) + } + }() + + basic := err.Error() + enc.AddString(key, basic) + + switch e := err.(type) { + case errorGroup: + return enc.AddArray(key+"Causes", errArray(e.Errors())) + case fmt.Formatter: + verbose := fmt.Sprintf("%+v", e) + if verbose != basic { + // This is a rich error type, like those produced by + // github.com/pkg/errors. + enc.AddString(key+"Verbose", verbose) + } + } + return nil +} + +type errorGroup interface { + // Provides read-only access to the underlying list of errors, preferably + // without causing any allocs. + Errors() []error +} + +// Note that errArray and errArrayElem are very similar to the version +// implemented in the top-level error.go file. We can't re-use this because +// that would require exporting errArray as part of the zapcore API. + +// Encodes a list of errors using the standard error encoding logic. +type errArray []error + +func (errs errArray) MarshalLogArray(arr ArrayEncoder) error { + for i := range errs { + if errs[i] == nil { + continue + } + + el := newErrArrayElem(errs[i]) + err := arr.AppendObject(el) + el.Free() + if err != nil { + return err + } + } + return nil +} + +var _errArrayElemPool = pool.New(func() *errArrayElem { + return &errArrayElem{} +}) + +// Encodes any error into a {"error": ...} re-using the same errors logic. +// +// May be passed in place of an array to build a single-element array. +type errArrayElem struct{ err error } + +func newErrArrayElem(err error) *errArrayElem { + e := _errArrayElemPool.Get() + e.err = err + return e +} + +func (e *errArrayElem) MarshalLogArray(arr ArrayEncoder) error { + return arr.AppendObject(e) +} + +func (e *errArrayElem) MarshalLogObject(enc ObjectEncoder) error { + return encodeError("error", e.err, enc) +} + +func (e *errArrayElem) Free() { + e.err = nil + _errArrayElemPool.Put(e) +} diff --git a/vendor/go.uber.org/zap/zapcore/field.go b/vendor/go.uber.org/zap/zapcore/field.go new file mode 100644 index 00000000..95bdb0a1 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/field.go @@ -0,0 +1,233 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "bytes" + "fmt" + "math" + "reflect" + "time" +) + +// A FieldType indicates which member of the Field union struct should be used +// and how it should be serialized. +type FieldType uint8 + +const ( + // UnknownType is the default field type. Attempting to add it to an encoder will panic. + UnknownType FieldType = iota + // ArrayMarshalerType indicates that the field carries an ArrayMarshaler. + ArrayMarshalerType + // ObjectMarshalerType indicates that the field carries an ObjectMarshaler. + ObjectMarshalerType + // BinaryType indicates that the field carries an opaque binary blob. + BinaryType + // BoolType indicates that the field carries a bool. + BoolType + // ByteStringType indicates that the field carries UTF-8 encoded bytes. + ByteStringType + // Complex128Type indicates that the field carries a complex128. + Complex128Type + // Complex64Type indicates that the field carries a complex128. + Complex64Type + // DurationType indicates that the field carries a time.Duration. + DurationType + // Float64Type indicates that the field carries a float64. + Float64Type + // Float32Type indicates that the field carries a float32. + Float32Type + // Int64Type indicates that the field carries an int64. + Int64Type + // Int32Type indicates that the field carries an int32. + Int32Type + // Int16Type indicates that the field carries an int16. + Int16Type + // Int8Type indicates that the field carries an int8. + Int8Type + // StringType indicates that the field carries a string. + StringType + // TimeType indicates that the field carries a time.Time that is + // representable by a UnixNano() stored as an int64. + TimeType + // TimeFullType indicates that the field carries a time.Time stored as-is. + TimeFullType + // Uint64Type indicates that the field carries a uint64. + Uint64Type + // Uint32Type indicates that the field carries a uint32. + Uint32Type + // Uint16Type indicates that the field carries a uint16. + Uint16Type + // Uint8Type indicates that the field carries a uint8. + Uint8Type + // UintptrType indicates that the field carries a uintptr. + UintptrType + // ReflectType indicates that the field carries an interface{}, which should + // be serialized using reflection. + ReflectType + // NamespaceType signals the beginning of an isolated namespace. All + // subsequent fields should be added to the new namespace. + NamespaceType + // StringerType indicates that the field carries a fmt.Stringer. + StringerType + // ErrorType indicates that the field carries an error. + ErrorType + // SkipType indicates that the field is a no-op. + SkipType + + // InlineMarshalerType indicates that the field carries an ObjectMarshaler + // that should be inlined. + InlineMarshalerType +) + +// A Field is a marshaling operation used to add a key-value pair to a logger's +// context. Most fields are lazily marshaled, so it's inexpensive to add fields +// to disabled debug-level log statements. +type Field struct { + Key string + Type FieldType + Integer int64 + String string + Interface interface{} +} + +// AddTo exports a field through the ObjectEncoder interface. It's primarily +// useful to library authors, and shouldn't be necessary in most applications. +func (f Field) AddTo(enc ObjectEncoder) { + var err error + + switch f.Type { + case ArrayMarshalerType: + err = enc.AddArray(f.Key, f.Interface.(ArrayMarshaler)) + case ObjectMarshalerType: + err = enc.AddObject(f.Key, f.Interface.(ObjectMarshaler)) + case InlineMarshalerType: + err = f.Interface.(ObjectMarshaler).MarshalLogObject(enc) + case BinaryType: + enc.AddBinary(f.Key, f.Interface.([]byte)) + case BoolType: + enc.AddBool(f.Key, f.Integer == 1) + case ByteStringType: + enc.AddByteString(f.Key, f.Interface.([]byte)) + case Complex128Type: + enc.AddComplex128(f.Key, f.Interface.(complex128)) + case Complex64Type: + enc.AddComplex64(f.Key, f.Interface.(complex64)) + case DurationType: + enc.AddDuration(f.Key, time.Duration(f.Integer)) + case Float64Type: + enc.AddFloat64(f.Key, math.Float64frombits(uint64(f.Integer))) + case Float32Type: + enc.AddFloat32(f.Key, math.Float32frombits(uint32(f.Integer))) + case Int64Type: + enc.AddInt64(f.Key, f.Integer) + case Int32Type: + enc.AddInt32(f.Key, int32(f.Integer)) + case Int16Type: + enc.AddInt16(f.Key, int16(f.Integer)) + case Int8Type: + enc.AddInt8(f.Key, int8(f.Integer)) + case StringType: + enc.AddString(f.Key, f.String) + case TimeType: + if f.Interface != nil { + enc.AddTime(f.Key, time.Unix(0, f.Integer).In(f.Interface.(*time.Location))) + } else { + // Fall back to UTC if location is nil. + enc.AddTime(f.Key, time.Unix(0, f.Integer)) + } + case TimeFullType: + enc.AddTime(f.Key, f.Interface.(time.Time)) + case Uint64Type: + enc.AddUint64(f.Key, uint64(f.Integer)) + case Uint32Type: + enc.AddUint32(f.Key, uint32(f.Integer)) + case Uint16Type: + enc.AddUint16(f.Key, uint16(f.Integer)) + case Uint8Type: + enc.AddUint8(f.Key, uint8(f.Integer)) + case UintptrType: + enc.AddUintptr(f.Key, uintptr(f.Integer)) + case ReflectType: + err = enc.AddReflected(f.Key, f.Interface) + case NamespaceType: + enc.OpenNamespace(f.Key) + case StringerType: + err = encodeStringer(f.Key, f.Interface, enc) + case ErrorType: + err = encodeError(f.Key, f.Interface.(error), enc) + case SkipType: + break + default: + panic(fmt.Sprintf("unknown field type: %v", f)) + } + + if err != nil { + enc.AddString(fmt.Sprintf("%sError", f.Key), err.Error()) + } +} + +// Equals returns whether two fields are equal. For non-primitive types such as +// errors, marshalers, or reflect types, it uses reflect.DeepEqual. +func (f Field) Equals(other Field) bool { + if f.Type != other.Type { + return false + } + if f.Key != other.Key { + return false + } + + switch f.Type { + case BinaryType, ByteStringType: + return bytes.Equal(f.Interface.([]byte), other.Interface.([]byte)) + case ArrayMarshalerType, ObjectMarshalerType, ErrorType, ReflectType: + return reflect.DeepEqual(f.Interface, other.Interface) + default: + return f == other + } +} + +func addFields(enc ObjectEncoder, fields []Field) { + for i := range fields { + fields[i].AddTo(enc) + } +} + +func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (retErr error) { + // Try to capture panics (from nil references or otherwise) when calling + // the String() method, similar to https://golang.org/src/fmt/print.go#L540 + defer func() { + if err := recover(); err != nil { + // If it's a nil pointer, just say "". The likeliest causes are a + // Stringer that fails to guard against nil or a nil pointer for a + // value receiver, and in either case, "" is a nice result. + if v := reflect.ValueOf(stringer); v.Kind() == reflect.Ptr && v.IsNil() { + enc.AddString(key, "") + return + } + + retErr = fmt.Errorf("PANIC=%v", err) + } + }() + + enc.AddString(key, stringer.(fmt.Stringer).String()) + return nil +} diff --git a/vendor/go.uber.org/zap/zapcore/hook.go b/vendor/go.uber.org/zap/zapcore/hook.go new file mode 100644 index 00000000..198def99 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/hook.go @@ -0,0 +1,77 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "go.uber.org/multierr" + +type hooked struct { + Core + funcs []func(Entry) error +} + +var ( + _ Core = (*hooked)(nil) + _ leveledEnabler = (*hooked)(nil) +) + +// RegisterHooks wraps a Core and runs a collection of user-defined callback +// hooks each time a message is logged. Execution of the callbacks is blocking. +// +// This offers users an easy way to register simple callbacks (e.g., metrics +// collection) without implementing the full Core interface. +func RegisterHooks(core Core, hooks ...func(Entry) error) Core { + funcs := append([]func(Entry) error{}, hooks...) + return &hooked{ + Core: core, + funcs: funcs, + } +} + +func (h *hooked) Level() Level { + return LevelOf(h.Core) +} + +func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + // Let the wrapped Core decide whether to log this message or not. This + // also gives the downstream a chance to register itself directly with the + // CheckedEntry. + if downstream := h.Core.Check(ent, ce); downstream != nil { + return downstream.AddCore(ent, h) + } + return ce +} + +func (h *hooked) With(fields []Field) Core { + return &hooked{ + Core: h.Core.With(fields), + funcs: h.funcs, + } +} + +func (h *hooked) Write(ent Entry, _ []Field) error { + // Since our downstream had a chance to register itself directly with the + // CheckedMessage, we don't need to call it here. + var err error + for i := range h.funcs { + err = multierr.Append(err, h.funcs[i](ent)) + } + return err +} diff --git a/vendor/go.uber.org/zap/zapcore/increase_level.go b/vendor/go.uber.org/zap/zapcore/increase_level.go new file mode 100644 index 00000000..7a11237a --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/increase_level.go @@ -0,0 +1,75 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "fmt" + +type levelFilterCore struct { + core Core + level LevelEnabler +} + +var ( + _ Core = (*levelFilterCore)(nil) + _ leveledEnabler = (*levelFilterCore)(nil) +) + +// NewIncreaseLevelCore creates a core that can be used to increase the level of +// an existing Core. It cannot be used to decrease the logging level, as it acts +// as a filter before calling the underlying core. If level decreases the log level, +// an error is returned. +func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error) { + for l := _maxLevel; l >= _minLevel; l-- { + if !core.Enabled(l) && level.Enabled(l) { + return nil, fmt.Errorf("invalid increase level, as level %q is allowed by increased level, but not by existing core", l) + } + } + + return &levelFilterCore{core, level}, nil +} + +func (c *levelFilterCore) Enabled(lvl Level) bool { + return c.level.Enabled(lvl) +} + +func (c *levelFilterCore) Level() Level { + return LevelOf(c.level) +} + +func (c *levelFilterCore) With(fields []Field) Core { + return &levelFilterCore{c.core.With(fields), c.level} +} + +func (c *levelFilterCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + if !c.Enabled(ent.Level) { + return ce + } + + return c.core.Check(ent, ce) +} + +func (c *levelFilterCore) Write(ent Entry, fields []Field) error { + return c.core.Write(ent, fields) +} + +func (c *levelFilterCore) Sync() error { + return c.core.Sync() +} diff --git a/vendor/go.uber.org/zap/zapcore/json_encoder.go b/vendor/go.uber.org/zap/zapcore/json_encoder.go new file mode 100644 index 00000000..c8ab8697 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/json_encoder.go @@ -0,0 +1,583 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "encoding/base64" + "math" + "time" + "unicode/utf8" + + "go.uber.org/zap/buffer" + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/internal/pool" +) + +// For JSON-escaping; see jsonEncoder.safeAddString below. +const _hex = "0123456789abcdef" + +var _jsonPool = pool.New(func() *jsonEncoder { + return &jsonEncoder{} +}) + +func putJSONEncoder(enc *jsonEncoder) { + if enc.reflectBuf != nil { + enc.reflectBuf.Free() + } + enc.EncoderConfig = nil + enc.buf = nil + enc.spaced = false + enc.openNamespaces = 0 + enc.reflectBuf = nil + enc.reflectEnc = nil + _jsonPool.Put(enc) +} + +type jsonEncoder struct { + *EncoderConfig + buf *buffer.Buffer + spaced bool // include spaces after colons and commas + openNamespaces int + + // for encoding generic values by reflection + reflectBuf *buffer.Buffer + reflectEnc ReflectedEncoder +} + +// NewJSONEncoder creates a fast, low-allocation JSON encoder. The encoder +// appropriately escapes all field keys and values. +// +// Note that the encoder doesn't deduplicate keys, so it's possible to produce +// a message like +// +// {"foo":"bar","foo":"baz"} +// +// This is permitted by the JSON specification, but not encouraged. Many +// libraries will ignore duplicate key-value pairs (typically keeping the last +// pair) when unmarshaling, but users should attempt to avoid adding duplicate +// keys. +func NewJSONEncoder(cfg EncoderConfig) Encoder { + return newJSONEncoder(cfg, false) +} + +func newJSONEncoder(cfg EncoderConfig, spaced bool) *jsonEncoder { + if cfg.SkipLineEnding { + cfg.LineEnding = "" + } else if cfg.LineEnding == "" { + cfg.LineEnding = DefaultLineEnding + } + + // If no EncoderConfig.NewReflectedEncoder is provided by the user, then use default + if cfg.NewReflectedEncoder == nil { + cfg.NewReflectedEncoder = defaultReflectedEncoder + } + + return &jsonEncoder{ + EncoderConfig: &cfg, + buf: bufferpool.Get(), + spaced: spaced, + } +} + +func (enc *jsonEncoder) AddArray(key string, arr ArrayMarshaler) error { + enc.addKey(key) + return enc.AppendArray(arr) +} + +func (enc *jsonEncoder) AddObject(key string, obj ObjectMarshaler) error { + enc.addKey(key) + return enc.AppendObject(obj) +} + +func (enc *jsonEncoder) AddBinary(key string, val []byte) { + enc.AddString(key, base64.StdEncoding.EncodeToString(val)) +} + +func (enc *jsonEncoder) AddByteString(key string, val []byte) { + enc.addKey(key) + enc.AppendByteString(val) +} + +func (enc *jsonEncoder) AddBool(key string, val bool) { + enc.addKey(key) + enc.AppendBool(val) +} + +func (enc *jsonEncoder) AddComplex128(key string, val complex128) { + enc.addKey(key) + enc.AppendComplex128(val) +} + +func (enc *jsonEncoder) AddComplex64(key string, val complex64) { + enc.addKey(key) + enc.AppendComplex64(val) +} + +func (enc *jsonEncoder) AddDuration(key string, val time.Duration) { + enc.addKey(key) + enc.AppendDuration(val) +} + +func (enc *jsonEncoder) AddFloat64(key string, val float64) { + enc.addKey(key) + enc.AppendFloat64(val) +} + +func (enc *jsonEncoder) AddFloat32(key string, val float32) { + enc.addKey(key) + enc.AppendFloat32(val) +} + +func (enc *jsonEncoder) AddInt64(key string, val int64) { + enc.addKey(key) + enc.AppendInt64(val) +} + +func (enc *jsonEncoder) resetReflectBuf() { + if enc.reflectBuf == nil { + enc.reflectBuf = bufferpool.Get() + enc.reflectEnc = enc.NewReflectedEncoder(enc.reflectBuf) + } else { + enc.reflectBuf.Reset() + } +} + +var nullLiteralBytes = []byte("null") + +// Only invoke the standard JSON encoder if there is actually something to +// encode; otherwise write JSON null literal directly. +func (enc *jsonEncoder) encodeReflected(obj interface{}) ([]byte, error) { + if obj == nil { + return nullLiteralBytes, nil + } + enc.resetReflectBuf() + if err := enc.reflectEnc.Encode(obj); err != nil { + return nil, err + } + enc.reflectBuf.TrimNewline() + return enc.reflectBuf.Bytes(), nil +} + +func (enc *jsonEncoder) AddReflected(key string, obj interface{}) error { + valueBytes, err := enc.encodeReflected(obj) + if err != nil { + return err + } + enc.addKey(key) + _, err = enc.buf.Write(valueBytes) + return err +} + +func (enc *jsonEncoder) OpenNamespace(key string) { + enc.addKey(key) + enc.buf.AppendByte('{') + enc.openNamespaces++ +} + +func (enc *jsonEncoder) AddString(key, val string) { + enc.addKey(key) + enc.AppendString(val) +} + +func (enc *jsonEncoder) AddTime(key string, val time.Time) { + enc.addKey(key) + enc.AppendTime(val) +} + +func (enc *jsonEncoder) AddUint64(key string, val uint64) { + enc.addKey(key) + enc.AppendUint64(val) +} + +func (enc *jsonEncoder) AppendArray(arr ArrayMarshaler) error { + enc.addElementSeparator() + enc.buf.AppendByte('[') + err := arr.MarshalLogArray(enc) + enc.buf.AppendByte(']') + return err +} + +func (enc *jsonEncoder) AppendObject(obj ObjectMarshaler) error { + // Close ONLY new openNamespaces that are created during + // AppendObject(). + old := enc.openNamespaces + enc.openNamespaces = 0 + enc.addElementSeparator() + enc.buf.AppendByte('{') + err := obj.MarshalLogObject(enc) + enc.buf.AppendByte('}') + enc.closeOpenNamespaces() + enc.openNamespaces = old + return err +} + +func (enc *jsonEncoder) AppendBool(val bool) { + enc.addElementSeparator() + enc.buf.AppendBool(val) +} + +func (enc *jsonEncoder) AppendByteString(val []byte) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.safeAddByteString(val) + enc.buf.AppendByte('"') +} + +// appendComplex appends the encoded form of the provided complex128 value. +// precision specifies the encoding precision for the real and imaginary +// components of the complex number. +func (enc *jsonEncoder) appendComplex(val complex128, precision int) { + enc.addElementSeparator() + // Cast to a platform-independent, fixed-size type. + r, i := float64(real(val)), float64(imag(val)) + enc.buf.AppendByte('"') + // Because we're always in a quoted string, we can use strconv without + // special-casing NaN and +/-Inf. + enc.buf.AppendFloat(r, precision) + // If imaginary part is less than 0, minus (-) sign is added by default + // by AppendFloat. + if i >= 0 { + enc.buf.AppendByte('+') + } + enc.buf.AppendFloat(i, precision) + enc.buf.AppendByte('i') + enc.buf.AppendByte('"') +} + +func (enc *jsonEncoder) AppendDuration(val time.Duration) { + cur := enc.buf.Len() + if e := enc.EncodeDuration; e != nil { + e(val, enc) + } + if cur == enc.buf.Len() { + // User-supplied EncodeDuration is a no-op. Fall back to nanoseconds to keep + // JSON valid. + enc.AppendInt64(int64(val)) + } +} + +func (enc *jsonEncoder) AppendInt64(val int64) { + enc.addElementSeparator() + enc.buf.AppendInt(val) +} + +func (enc *jsonEncoder) AppendReflected(val interface{}) error { + valueBytes, err := enc.encodeReflected(val) + if err != nil { + return err + } + enc.addElementSeparator() + _, err = enc.buf.Write(valueBytes) + return err +} + +func (enc *jsonEncoder) AppendString(val string) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.safeAddString(val) + enc.buf.AppendByte('"') +} + +func (enc *jsonEncoder) AppendTimeLayout(time time.Time, layout string) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.buf.AppendTime(time, layout) + enc.buf.AppendByte('"') +} + +func (enc *jsonEncoder) AppendTime(val time.Time) { + cur := enc.buf.Len() + if e := enc.EncodeTime; e != nil { + e(val, enc) + } + if cur == enc.buf.Len() { + // User-supplied EncodeTime is a no-op. Fall back to nanos since epoch to keep + // output JSON valid. + enc.AppendInt64(val.UnixNano()) + } +} + +func (enc *jsonEncoder) AppendUint64(val uint64) { + enc.addElementSeparator() + enc.buf.AppendUint(val) +} + +func (enc *jsonEncoder) AddInt(k string, v int) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddInt32(k string, v int32) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddInt16(k string, v int16) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddInt8(k string, v int8) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddUint(k string, v uint) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUint32(k string, v uint32) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUint16(k string, v uint16) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUint8(k string, v uint8) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUintptr(k string, v uintptr) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AppendComplex64(v complex64) { enc.appendComplex(complex128(v), 32) } +func (enc *jsonEncoder) AppendComplex128(v complex128) { enc.appendComplex(complex128(v), 64) } +func (enc *jsonEncoder) AppendFloat64(v float64) { enc.appendFloat(v, 64) } +func (enc *jsonEncoder) AppendFloat32(v float32) { enc.appendFloat(float64(v), 32) } +func (enc *jsonEncoder) AppendInt(v int) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendInt32(v int32) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendInt16(v int16) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendInt8(v int8) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendUint(v uint) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUint32(v uint32) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUint16(v uint16) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUint8(v uint8) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUintptr(v uintptr) { enc.AppendUint64(uint64(v)) } + +func (enc *jsonEncoder) Clone() Encoder { + clone := enc.clone() + clone.buf.Write(enc.buf.Bytes()) + return clone +} + +func (enc *jsonEncoder) clone() *jsonEncoder { + clone := _jsonPool.Get() + clone.EncoderConfig = enc.EncoderConfig + clone.spaced = enc.spaced + clone.openNamespaces = enc.openNamespaces + clone.buf = bufferpool.Get() + return clone +} + +func (enc *jsonEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { + final := enc.clone() + final.buf.AppendByte('{') + + if final.LevelKey != "" && final.EncodeLevel != nil { + final.addKey(final.LevelKey) + cur := final.buf.Len() + final.EncodeLevel(ent.Level, final) + if cur == final.buf.Len() { + // User-supplied EncodeLevel was a no-op. Fall back to strings to keep + // output JSON valid. + final.AppendString(ent.Level.String()) + } + } + if final.TimeKey != "" { + final.AddTime(final.TimeKey, ent.Time) + } + if ent.LoggerName != "" && final.NameKey != "" { + final.addKey(final.NameKey) + cur := final.buf.Len() + nameEncoder := final.EncodeName + + // if no name encoder provided, fall back to FullNameEncoder for backwards + // compatibility + if nameEncoder == nil { + nameEncoder = FullNameEncoder + } + + nameEncoder(ent.LoggerName, final) + if cur == final.buf.Len() { + // User-supplied EncodeName was a no-op. Fall back to strings to + // keep output JSON valid. + final.AppendString(ent.LoggerName) + } + } + if ent.Caller.Defined { + if final.CallerKey != "" { + final.addKey(final.CallerKey) + cur := final.buf.Len() + final.EncodeCaller(ent.Caller, final) + if cur == final.buf.Len() { + // User-supplied EncodeCaller was a no-op. Fall back to strings to + // keep output JSON valid. + final.AppendString(ent.Caller.String()) + } + } + if final.FunctionKey != "" { + final.addKey(final.FunctionKey) + final.AppendString(ent.Caller.Function) + } + } + if final.MessageKey != "" { + final.addKey(enc.MessageKey) + final.AppendString(ent.Message) + } + if enc.buf.Len() > 0 { + final.addElementSeparator() + final.buf.Write(enc.buf.Bytes()) + } + addFields(final, fields) + final.closeOpenNamespaces() + if ent.Stack != "" && final.StacktraceKey != "" { + final.AddString(final.StacktraceKey, ent.Stack) + } + final.buf.AppendByte('}') + final.buf.AppendString(final.LineEnding) + + ret := final.buf + putJSONEncoder(final) + return ret, nil +} + +func (enc *jsonEncoder) truncate() { + enc.buf.Reset() +} + +func (enc *jsonEncoder) closeOpenNamespaces() { + for i := 0; i < enc.openNamespaces; i++ { + enc.buf.AppendByte('}') + } + enc.openNamespaces = 0 +} + +func (enc *jsonEncoder) addKey(key string) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.safeAddString(key) + enc.buf.AppendByte('"') + enc.buf.AppendByte(':') + if enc.spaced { + enc.buf.AppendByte(' ') + } +} + +func (enc *jsonEncoder) addElementSeparator() { + last := enc.buf.Len() - 1 + if last < 0 { + return + } + switch enc.buf.Bytes()[last] { + case '{', '[', ':', ',', ' ': + return + default: + enc.buf.AppendByte(',') + if enc.spaced { + enc.buf.AppendByte(' ') + } + } +} + +func (enc *jsonEncoder) appendFloat(val float64, bitSize int) { + enc.addElementSeparator() + switch { + case math.IsNaN(val): + enc.buf.AppendString(`"NaN"`) + case math.IsInf(val, 1): + enc.buf.AppendString(`"+Inf"`) + case math.IsInf(val, -1): + enc.buf.AppendString(`"-Inf"`) + default: + enc.buf.AppendFloat(val, bitSize) + } +} + +// safeAddString JSON-escapes a string and appends it to the internal buffer. +// Unlike the standard library's encoder, it doesn't attempt to protect the +// user from browser vulnerabilities or JSONP-related problems. +func (enc *jsonEncoder) safeAddString(s string) { + safeAppendStringLike( + (*buffer.Buffer).AppendString, + utf8.DecodeRuneInString, + enc.buf, + s, + ) +} + +// safeAddByteString is no-alloc equivalent of safeAddString(string(s)) for s []byte. +func (enc *jsonEncoder) safeAddByteString(s []byte) { + safeAppendStringLike( + (*buffer.Buffer).AppendBytes, + utf8.DecodeRune, + enc.buf, + s, + ) +} + +// safeAppendStringLike is a generic implementation of safeAddString and safeAddByteString. +// It appends a string or byte slice to the buffer, escaping all special characters. +func safeAppendStringLike[S []byte | string]( + // appendTo appends this string-like object to the buffer. + appendTo func(*buffer.Buffer, S), + // decodeRune decodes the next rune from the string-like object + // and returns its value and width in bytes. + decodeRune func(S) (rune, int), + buf *buffer.Buffer, + s S, +) { + // The encoding logic below works by skipping over characters + // that can be safely copied as-is, + // until a character is found that needs special handling. + // At that point, we copy everything we've seen so far, + // and then handle that special character. + // + // last is the index of the last byte that was copied to the buffer. + last := 0 + for i := 0; i < len(s); { + if s[i] >= utf8.RuneSelf { + // Character >= RuneSelf may be part of a multi-byte rune. + // They need to be decoded before we can decide how to handle them. + r, size := decodeRune(s[i:]) + if r != utf8.RuneError || size != 1 { + // No special handling required. + // Skip over this rune and continue. + i += size + continue + } + + // Invalid UTF-8 sequence. + // Replace it with the Unicode replacement character. + appendTo(buf, s[last:i]) + buf.AppendString(`\ufffd`) + + i++ + last = i + } else { + // Character < RuneSelf is a single-byte UTF-8 rune. + if s[i] >= 0x20 && s[i] != '\\' && s[i] != '"' { + // No escaping necessary. + // Skip over this character and continue. + i++ + continue + } + + // This character needs to be escaped. + appendTo(buf, s[last:i]) + switch s[i] { + case '\\', '"': + buf.AppendByte('\\') + buf.AppendByte(s[i]) + case '\n': + buf.AppendByte('\\') + buf.AppendByte('n') + case '\r': + buf.AppendByte('\\') + buf.AppendByte('r') + case '\t': + buf.AppendByte('\\') + buf.AppendByte('t') + default: + // Encode bytes < 0x20, except for the escape sequences above. + buf.AppendString(`\u00`) + buf.AppendByte(_hex[s[i]>>4]) + buf.AppendByte(_hex[s[i]&0xF]) + } + + i++ + last = i + } + } + + // add remaining + appendTo(buf, s[last:]) +} diff --git a/vendor/go.uber.org/zap/zapcore/lazy_with.go b/vendor/go.uber.org/zap/zapcore/lazy_with.go new file mode 100644 index 00000000..05288d6a --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/lazy_with.go @@ -0,0 +1,54 @@ +// Copyright (c) 2023 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "sync" + +type lazyWithCore struct { + Core + sync.Once + fields []Field +} + +// NewLazyWith wraps a Core with a "lazy" Core that will only encode fields if +// the logger is written to (or is further chained in a lon-lazy manner). +func NewLazyWith(core Core, fields []Field) Core { + return &lazyWithCore{ + Core: core, + fields: fields, + } +} + +func (d *lazyWithCore) initOnce() { + d.Once.Do(func() { + d.Core = d.Core.With(d.fields) + }) +} + +func (d *lazyWithCore) With(fields []Field) Core { + d.initOnce() + return d.Core.With(fields) +} + +func (d *lazyWithCore) Check(e Entry, ce *CheckedEntry) *CheckedEntry { + d.initOnce() + return d.Core.Check(e, ce) +} diff --git a/vendor/go.uber.org/zap/zapcore/level.go b/vendor/go.uber.org/zap/zapcore/level.go new file mode 100644 index 00000000..e01a2413 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/level.go @@ -0,0 +1,229 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "bytes" + "errors" + "fmt" +) + +var errUnmarshalNilLevel = errors.New("can't unmarshal a nil *Level") + +// A Level is a logging priority. Higher levels are more important. +type Level int8 + +const ( + // DebugLevel logs are typically voluminous, and are usually disabled in + // production. + DebugLevel Level = iota - 1 + // InfoLevel is the default logging priority. + InfoLevel + // WarnLevel logs are more important than Info, but don't need individual + // human review. + WarnLevel + // ErrorLevel logs are high-priority. If an application is running smoothly, + // it shouldn't generate any error-level logs. + ErrorLevel + // DPanicLevel logs are particularly important errors. In development the + // logger panics after writing the message. + DPanicLevel + // PanicLevel logs a message, then panics. + PanicLevel + // FatalLevel logs a message, then calls os.Exit(1). + FatalLevel + + _minLevel = DebugLevel + _maxLevel = FatalLevel + + // InvalidLevel is an invalid value for Level. + // + // Core implementations may panic if they see messages of this level. + InvalidLevel = _maxLevel + 1 +) + +// ParseLevel parses a level based on the lower-case or all-caps ASCII +// representation of the log level. If the provided ASCII representation is +// invalid an error is returned. +// +// This is particularly useful when dealing with text input to configure log +// levels. +func ParseLevel(text string) (Level, error) { + var level Level + err := level.UnmarshalText([]byte(text)) + return level, err +} + +type leveledEnabler interface { + LevelEnabler + + Level() Level +} + +// LevelOf reports the minimum enabled log level for the given LevelEnabler +// from Zap's supported log levels, or [InvalidLevel] if none of them are +// enabled. +// +// A LevelEnabler may implement a 'Level() Level' method to override the +// behavior of this function. +// +// func (c *core) Level() Level { +// return c.currentLevel +// } +// +// It is recommended that [Core] implementations that wrap other cores use +// LevelOf to retrieve the level of the wrapped core. For example, +// +// func (c *coreWrapper) Level() Level { +// return zapcore.LevelOf(c.wrappedCore) +// } +func LevelOf(enab LevelEnabler) Level { + if lvler, ok := enab.(leveledEnabler); ok { + return lvler.Level() + } + + for lvl := _minLevel; lvl <= _maxLevel; lvl++ { + if enab.Enabled(lvl) { + return lvl + } + } + + return InvalidLevel +} + +// String returns a lower-case ASCII representation of the log level. +func (l Level) String() string { + switch l { + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warn" + case ErrorLevel: + return "error" + case DPanicLevel: + return "dpanic" + case PanicLevel: + return "panic" + case FatalLevel: + return "fatal" + default: + return fmt.Sprintf("Level(%d)", l) + } +} + +// CapitalString returns an all-caps ASCII representation of the log level. +func (l Level) CapitalString() string { + // Printing levels in all-caps is common enough that we should export this + // functionality. + switch l { + case DebugLevel: + return "DEBUG" + case InfoLevel: + return "INFO" + case WarnLevel: + return "WARN" + case ErrorLevel: + return "ERROR" + case DPanicLevel: + return "DPANIC" + case PanicLevel: + return "PANIC" + case FatalLevel: + return "FATAL" + default: + return fmt.Sprintf("LEVEL(%d)", l) + } +} + +// MarshalText marshals the Level to text. Note that the text representation +// drops the -Level suffix (see example). +func (l Level) MarshalText() ([]byte, error) { + return []byte(l.String()), nil +} + +// UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalText +// expects the text representation of a Level to drop the -Level suffix (see +// example). +// +// In particular, this makes it easy to configure logging levels using YAML, +// TOML, or JSON files. +func (l *Level) UnmarshalText(text []byte) error { + if l == nil { + return errUnmarshalNilLevel + } + if !l.unmarshalText(text) && !l.unmarshalText(bytes.ToLower(text)) { + return fmt.Errorf("unrecognized level: %q", text) + } + return nil +} + +func (l *Level) unmarshalText(text []byte) bool { + switch string(text) { + case "debug", "DEBUG": + *l = DebugLevel + case "info", "INFO", "": // make the zero value useful + *l = InfoLevel + case "warn", "WARN": + *l = WarnLevel + case "error", "ERROR": + *l = ErrorLevel + case "dpanic", "DPANIC": + *l = DPanicLevel + case "panic", "PANIC": + *l = PanicLevel + case "fatal", "FATAL": + *l = FatalLevel + default: + return false + } + return true +} + +// Set sets the level for the flag.Value interface. +func (l *Level) Set(s string) error { + return l.UnmarshalText([]byte(s)) +} + +// Get gets the level for the flag.Getter interface. +func (l *Level) Get() interface{} { + return *l +} + +// Enabled returns true if the given level is at or above this level. +func (l Level) Enabled(lvl Level) bool { + return lvl >= l +} + +// LevelEnabler decides whether a given logging level is enabled when logging a +// message. +// +// Enablers are intended to be used to implement deterministic filters; +// concerns like sampling are better implemented as a Core. +// +// Each concrete Level value implements a static LevelEnabler which returns +// true for itself and all higher logging levels. For example WarnLevel.Enabled() +// will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and +// FatalLevel, but return false for InfoLevel and DebugLevel. +type LevelEnabler interface { + Enabled(Level) bool +} diff --git a/vendor/go.uber.org/zap/zapcore/level_strings.go b/vendor/go.uber.org/zap/zapcore/level_strings.go new file mode 100644 index 00000000..7af8dadc --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/level_strings.go @@ -0,0 +1,46 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "go.uber.org/zap/internal/color" + +var ( + _levelToColor = map[Level]color.Color{ + DebugLevel: color.Magenta, + InfoLevel: color.Blue, + WarnLevel: color.Yellow, + ErrorLevel: color.Red, + DPanicLevel: color.Red, + PanicLevel: color.Red, + FatalLevel: color.Red, + } + _unknownLevelColor = color.Red + + _levelToLowercaseColorString = make(map[Level]string, len(_levelToColor)) + _levelToCapitalColorString = make(map[Level]string, len(_levelToColor)) +) + +func init() { + for level, color := range _levelToColor { + _levelToLowercaseColorString[level] = color.Add(level.String()) + _levelToCapitalColorString[level] = color.Add(level.CapitalString()) + } +} diff --git a/vendor/go.uber.org/zap/zapcore/marshaler.go b/vendor/go.uber.org/zap/zapcore/marshaler.go new file mode 100644 index 00000000..c3c55ba0 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/marshaler.go @@ -0,0 +1,61 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +// ObjectMarshaler allows user-defined types to efficiently add themselves to the +// logging context, and to selectively omit information which shouldn't be +// included in logs (e.g., passwords). +// +// Note: ObjectMarshaler is only used when zap.Object is used or when +// passed directly to zap.Any. It is not used when reflection-based +// encoding is used. +type ObjectMarshaler interface { + MarshalLogObject(ObjectEncoder) error +} + +// ObjectMarshalerFunc is a type adapter that turns a function into an +// ObjectMarshaler. +type ObjectMarshalerFunc func(ObjectEncoder) error + +// MarshalLogObject calls the underlying function. +func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error { + return f(enc) +} + +// ArrayMarshaler allows user-defined types to efficiently add themselves to the +// logging context, and to selectively omit information which shouldn't be +// included in logs (e.g., passwords). +// +// Note: ArrayMarshaler is only used when zap.Array is used or when +// passed directly to zap.Any. It is not used when reflection-based +// encoding is used. +type ArrayMarshaler interface { + MarshalLogArray(ArrayEncoder) error +} + +// ArrayMarshalerFunc is a type adapter that turns a function into an +// ArrayMarshaler. +type ArrayMarshalerFunc func(ArrayEncoder) error + +// MarshalLogArray calls the underlying function. +func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error { + return f(enc) +} diff --git a/vendor/go.uber.org/zap/zapcore/memory_encoder.go b/vendor/go.uber.org/zap/zapcore/memory_encoder.go new file mode 100644 index 00000000..dfead082 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/memory_encoder.go @@ -0,0 +1,179 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "time" + +// MapObjectEncoder is an ObjectEncoder backed by a simple +// map[string]interface{}. It's not fast enough for production use, but it's +// helpful in tests. +type MapObjectEncoder struct { + // Fields contains the entire encoded log context. + Fields map[string]interface{} + // cur is a pointer to the namespace we're currently writing to. + cur map[string]interface{} +} + +// NewMapObjectEncoder creates a new map-backed ObjectEncoder. +func NewMapObjectEncoder() *MapObjectEncoder { + m := make(map[string]interface{}) + return &MapObjectEncoder{ + Fields: m, + cur: m, + } +} + +// AddArray implements ObjectEncoder. +func (m *MapObjectEncoder) AddArray(key string, v ArrayMarshaler) error { + arr := &sliceArrayEncoder{elems: make([]interface{}, 0)} + err := v.MarshalLogArray(arr) + m.cur[key] = arr.elems + return err +} + +// AddObject implements ObjectEncoder. +func (m *MapObjectEncoder) AddObject(k string, v ObjectMarshaler) error { + newMap := NewMapObjectEncoder() + m.cur[k] = newMap.Fields + return v.MarshalLogObject(newMap) +} + +// AddBinary implements ObjectEncoder. +func (m *MapObjectEncoder) AddBinary(k string, v []byte) { m.cur[k] = v } + +// AddByteString implements ObjectEncoder. +func (m *MapObjectEncoder) AddByteString(k string, v []byte) { m.cur[k] = string(v) } + +// AddBool implements ObjectEncoder. +func (m *MapObjectEncoder) AddBool(k string, v bool) { m.cur[k] = v } + +// AddDuration implements ObjectEncoder. +func (m MapObjectEncoder) AddDuration(k string, v time.Duration) { m.cur[k] = v } + +// AddComplex128 implements ObjectEncoder. +func (m *MapObjectEncoder) AddComplex128(k string, v complex128) { m.cur[k] = v } + +// AddComplex64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddComplex64(k string, v complex64) { m.cur[k] = v } + +// AddFloat64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddFloat64(k string, v float64) { m.cur[k] = v } + +// AddFloat32 implements ObjectEncoder. +func (m *MapObjectEncoder) AddFloat32(k string, v float32) { m.cur[k] = v } + +// AddInt implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt(k string, v int) { m.cur[k] = v } + +// AddInt64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt64(k string, v int64) { m.cur[k] = v } + +// AddInt32 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt32(k string, v int32) { m.cur[k] = v } + +// AddInt16 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt16(k string, v int16) { m.cur[k] = v } + +// AddInt8 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt8(k string, v int8) { m.cur[k] = v } + +// AddString implements ObjectEncoder. +func (m *MapObjectEncoder) AddString(k string, v string) { m.cur[k] = v } + +// AddTime implements ObjectEncoder. +func (m MapObjectEncoder) AddTime(k string, v time.Time) { m.cur[k] = v } + +// AddUint implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint(k string, v uint) { m.cur[k] = v } + +// AddUint64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint64(k string, v uint64) { m.cur[k] = v } + +// AddUint32 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint32(k string, v uint32) { m.cur[k] = v } + +// AddUint16 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint16(k string, v uint16) { m.cur[k] = v } + +// AddUint8 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint8(k string, v uint8) { m.cur[k] = v } + +// AddUintptr implements ObjectEncoder. +func (m *MapObjectEncoder) AddUintptr(k string, v uintptr) { m.cur[k] = v } + +// AddReflected implements ObjectEncoder. +func (m *MapObjectEncoder) AddReflected(k string, v interface{}) error { + m.cur[k] = v + return nil +} + +// OpenNamespace implements ObjectEncoder. +func (m *MapObjectEncoder) OpenNamespace(k string) { + ns := make(map[string]interface{}) + m.cur[k] = ns + m.cur = ns +} + +// sliceArrayEncoder is an ArrayEncoder backed by a simple []interface{}. Like +// the MapObjectEncoder, it's not designed for production use. +type sliceArrayEncoder struct { + elems []interface{} +} + +func (s *sliceArrayEncoder) AppendArray(v ArrayMarshaler) error { + enc := &sliceArrayEncoder{} + err := v.MarshalLogArray(enc) + s.elems = append(s.elems, enc.elems) + return err +} + +func (s *sliceArrayEncoder) AppendObject(v ObjectMarshaler) error { + m := NewMapObjectEncoder() + err := v.MarshalLogObject(m) + s.elems = append(s.elems, m.Fields) + return err +} + +func (s *sliceArrayEncoder) AppendReflected(v interface{}) error { + s.elems = append(s.elems, v) + return nil +} + +func (s *sliceArrayEncoder) AppendBool(v bool) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendByteString(v []byte) { s.elems = append(s.elems, string(v)) } +func (s *sliceArrayEncoder) AppendComplex128(v complex128) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendComplex64(v complex64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendDuration(v time.Duration) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendFloat64(v float64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendFloat32(v float32) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt(v int) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt64(v int64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt32(v int32) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt16(v int16) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt8(v int8) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendString(v string) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendTime(v time.Time) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint(v uint) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint64(v uint64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint32(v uint32) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint16(v uint16) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint8(v uint8) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUintptr(v uintptr) { s.elems = append(s.elems, v) } diff --git a/vendor/go.uber.org/zap/zapcore/reflected_encoder.go b/vendor/go.uber.org/zap/zapcore/reflected_encoder.go new file mode 100644 index 00000000..8746360e --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/reflected_encoder.go @@ -0,0 +1,41 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "encoding/json" + "io" +) + +// ReflectedEncoder serializes log fields that can't be serialized with Zap's +// JSON encoder. These have the ReflectType field type. +// Use EncoderConfig.NewReflectedEncoder to set this. +type ReflectedEncoder interface { + // Encode encodes and writes to the underlying data stream. + Encode(interface{}) error +} + +func defaultReflectedEncoder(w io.Writer) ReflectedEncoder { + enc := json.NewEncoder(w) + // For consistency with our custom JSON encoder. + enc.SetEscapeHTML(false) + return enc +} diff --git a/vendor/go.uber.org/zap/zapcore/sampler.go b/vendor/go.uber.org/zap/zapcore/sampler.go new file mode 100644 index 00000000..b7c093a4 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/sampler.go @@ -0,0 +1,229 @@ +// Copyright (c) 2016-2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "sync/atomic" + "time" +) + +const ( + _numLevels = _maxLevel - _minLevel + 1 + _countersPerLevel = 4096 +) + +type counter struct { + resetAt atomic.Int64 + counter atomic.Uint64 +} + +type counters [_numLevels][_countersPerLevel]counter + +func newCounters() *counters { + return &counters{} +} + +func (cs *counters) get(lvl Level, key string) *counter { + i := lvl - _minLevel + j := fnv32a(key) % _countersPerLevel + return &cs[i][j] +} + +// fnv32a, adapted from "hash/fnv", but without a []byte(string) alloc +func fnv32a(s string) uint32 { + const ( + offset32 = 2166136261 + prime32 = 16777619 + ) + hash := uint32(offset32) + for i := 0; i < len(s); i++ { + hash ^= uint32(s[i]) + hash *= prime32 + } + return hash +} + +func (c *counter) IncCheckReset(t time.Time, tick time.Duration) uint64 { + tn := t.UnixNano() + resetAfter := c.resetAt.Load() + if resetAfter > tn { + return c.counter.Add(1) + } + + c.counter.Store(1) + + newResetAfter := tn + tick.Nanoseconds() + if !c.resetAt.CompareAndSwap(resetAfter, newResetAfter) { + // We raced with another goroutine trying to reset, and it also reset + // the counter to 1, so we need to reincrement the counter. + return c.counter.Add(1) + } + + return 1 +} + +// SamplingDecision is a decision represented as a bit field made by sampler. +// More decisions may be added in the future. +type SamplingDecision uint32 + +const ( + // LogDropped indicates that the Sampler dropped a log entry. + LogDropped SamplingDecision = 1 << iota + // LogSampled indicates that the Sampler sampled a log entry. + LogSampled +) + +// optionFunc wraps a func so it satisfies the SamplerOption interface. +type optionFunc func(*sampler) + +func (f optionFunc) apply(s *sampler) { + f(s) +} + +// SamplerOption configures a Sampler. +type SamplerOption interface { + apply(*sampler) +} + +// nopSamplingHook is the default hook used by sampler. +func nopSamplingHook(Entry, SamplingDecision) {} + +// SamplerHook registers a function which will be called when Sampler makes a +// decision. +// +// This hook may be used to get visibility into the performance of the sampler. +// For example, use it to track metrics of dropped versus sampled logs. +// +// var dropped atomic.Int64 +// zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) { +// if dec&zapcore.LogDropped > 0 { +// dropped.Inc() +// } +// }) +func SamplerHook(hook func(entry Entry, dec SamplingDecision)) SamplerOption { + return optionFunc(func(s *sampler) { + s.hook = hook + }) +} + +// NewSamplerWithOptions creates a Core that samples incoming entries, which +// caps the CPU and I/O load of logging while attempting to preserve a +// representative subset of your logs. +// +// Zap samples by logging the first N entries with a given level and message +// each tick. If more Entries with the same level and message are seen during +// the same interval, every Mth message is logged and the rest are dropped. +// +// For example, +// +// core = NewSamplerWithOptions(core, time.Second, 10, 5) +// +// This will log the first 10 log entries with the same level and message +// in a one second interval as-is. Following that, it will allow through +// every 5th log entry with the same level and message in that interval. +// +// If thereafter is zero, the Core will drop all log entries after the first N +// in that interval. +// +// Sampler can be configured to report sampling decisions with the SamplerHook +// option. +// +// Keep in mind that Zap's sampling implementation is optimized for speed over +// absolute precision; under load, each tick may be slightly over- or +// under-sampled. +func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core { + s := &sampler{ + Core: core, + tick: tick, + counts: newCounters(), + first: uint64(first), + thereafter: uint64(thereafter), + hook: nopSamplingHook, + } + for _, opt := range opts { + opt.apply(s) + } + + return s +} + +type sampler struct { + Core + + counts *counters + tick time.Duration + first, thereafter uint64 + hook func(Entry, SamplingDecision) +} + +var ( + _ Core = (*sampler)(nil) + _ leveledEnabler = (*sampler)(nil) +) + +// NewSampler creates a Core that samples incoming entries, which +// caps the CPU and I/O load of logging while attempting to preserve a +// representative subset of your logs. +// +// Zap samples by logging the first N entries with a given level and message +// each tick. If more Entries with the same level and message are seen during +// the same interval, every Mth message is logged and the rest are dropped. +// +// Keep in mind that zap's sampling implementation is optimized for speed over +// absolute precision; under load, each tick may be slightly over- or +// under-sampled. +// +// Deprecated: use NewSamplerWithOptions. +func NewSampler(core Core, tick time.Duration, first, thereafter int) Core { + return NewSamplerWithOptions(core, tick, first, thereafter) +} + +func (s *sampler) Level() Level { + return LevelOf(s.Core) +} + +func (s *sampler) With(fields []Field) Core { + return &sampler{ + Core: s.Core.With(fields), + tick: s.tick, + counts: s.counts, + first: s.first, + thereafter: s.thereafter, + hook: s.hook, + } +} + +func (s *sampler) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + if !s.Enabled(ent.Level) { + return ce + } + + if ent.Level >= _minLevel && ent.Level <= _maxLevel { + counter := s.counts.get(ent.Level, ent.Message) + n := counter.IncCheckReset(ent.Time, s.tick) + if n > s.first && (s.thereafter == 0 || (n-s.first)%s.thereafter != 0) { + s.hook(ent, LogDropped) + return ce + } + s.hook(ent, LogSampled) + } + return s.Core.Check(ent, ce) +} diff --git a/vendor/go.uber.org/zap/zapcore/tee.go b/vendor/go.uber.org/zap/zapcore/tee.go new file mode 100644 index 00000000..9bb32f05 --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/tee.go @@ -0,0 +1,96 @@ +// Copyright (c) 2016-2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import "go.uber.org/multierr" + +type multiCore []Core + +var ( + _ leveledEnabler = multiCore(nil) + _ Core = multiCore(nil) +) + +// NewTee creates a Core that duplicates log entries into two or more +// underlying Cores. +// +// Calling it with a single Core returns the input unchanged, and calling +// it with no input returns a no-op Core. +func NewTee(cores ...Core) Core { + switch len(cores) { + case 0: + return NewNopCore() + case 1: + return cores[0] + default: + return multiCore(cores) + } +} + +func (mc multiCore) With(fields []Field) Core { + clone := make(multiCore, len(mc)) + for i := range mc { + clone[i] = mc[i].With(fields) + } + return clone +} + +func (mc multiCore) Level() Level { + minLvl := _maxLevel // mc is never empty + for i := range mc { + if lvl := LevelOf(mc[i]); lvl < minLvl { + minLvl = lvl + } + } + return minLvl +} + +func (mc multiCore) Enabled(lvl Level) bool { + for i := range mc { + if mc[i].Enabled(lvl) { + return true + } + } + return false +} + +func (mc multiCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + for i := range mc { + ce = mc[i].Check(ent, ce) + } + return ce +} + +func (mc multiCore) Write(ent Entry, fields []Field) error { + var err error + for i := range mc { + err = multierr.Append(err, mc[i].Write(ent, fields)) + } + return err +} + +func (mc multiCore) Sync() error { + var err error + for i := range mc { + err = multierr.Append(err, mc[i].Sync()) + } + return err +} diff --git a/vendor/go.uber.org/zap/zapcore/write_syncer.go b/vendor/go.uber.org/zap/zapcore/write_syncer.go new file mode 100644 index 00000000..d4a1af3d --- /dev/null +++ b/vendor/go.uber.org/zap/zapcore/write_syncer.go @@ -0,0 +1,122 @@ +// Copyright (c) 2016 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package zapcore + +import ( + "io" + "sync" + + "go.uber.org/multierr" +) + +// A WriteSyncer is an io.Writer that can also flush any buffered data. Note +// that *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer. +type WriteSyncer interface { + io.Writer + Sync() error +} + +// AddSync converts an io.Writer to a WriteSyncer. It attempts to be +// intelligent: if the concrete type of the io.Writer implements WriteSyncer, +// we'll use the existing Sync method. If it doesn't, we'll add a no-op Sync. +func AddSync(w io.Writer) WriteSyncer { + switch w := w.(type) { + case WriteSyncer: + return w + default: + return writerWrapper{w} + } +} + +type lockedWriteSyncer struct { + sync.Mutex + ws WriteSyncer +} + +// Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In +// particular, *os.Files must be locked before use. +func Lock(ws WriteSyncer) WriteSyncer { + if _, ok := ws.(*lockedWriteSyncer); ok { + // no need to layer on another lock + return ws + } + return &lockedWriteSyncer{ws: ws} +} + +func (s *lockedWriteSyncer) Write(bs []byte) (int, error) { + s.Lock() + n, err := s.ws.Write(bs) + s.Unlock() + return n, err +} + +func (s *lockedWriteSyncer) Sync() error { + s.Lock() + err := s.ws.Sync() + s.Unlock() + return err +} + +type writerWrapper struct { + io.Writer +} + +func (w writerWrapper) Sync() error { + return nil +} + +type multiWriteSyncer []WriteSyncer + +// NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes +// and sync calls, much like io.MultiWriter. +func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer { + if len(ws) == 1 { + return ws[0] + } + return multiWriteSyncer(ws) +} + +// See https://golang.org/src/io/multi.go +// When not all underlying syncers write the same number of bytes, +// the smallest number is returned even though Write() is called on +// all of them. +func (ws multiWriteSyncer) Write(p []byte) (int, error) { + var writeErr error + nWritten := 0 + for _, w := range ws { + n, err := w.Write(p) + writeErr = multierr.Append(writeErr, err) + if nWritten == 0 && n != 0 { + nWritten = n + } else if n < nWritten { + nWritten = n + } + } + return nWritten, writeErr +} + +func (ws multiWriteSyncer) Sync() error { + var err error + for _, w := range ws { + err = multierr.Append(err, w.Sync()) + } + return err +} diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go new file mode 100644 index 00000000..db1c95fa --- /dev/null +++ b/vendor/golang.org/x/net/context/context.go @@ -0,0 +1,144 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package context defines the Context type, which carries deadlines, +// cancellation signals, and other request-scoped values across API boundaries +// and between processes. +// As of Go 1.7 this package is available in the standard library under the +// name [context], and migrating to it can be done automatically with [go fix]. +// +// Incoming requests to a server should create a [Context], and outgoing +// calls to servers should accept a Context. The chain of function +// calls between them must propagate the Context, optionally replacing +// it with a derived Context created using [WithCancel], [WithDeadline], +// [WithTimeout], or [WithValue]. +// +// Programs that use Contexts should follow these rules to keep interfaces +// consistent across packages and enable static analysis tools to check context +// propagation: +// +// Do not store Contexts inside a struct type; instead, pass a Context +// explicitly to each function that needs it. This is discussed further in +// https://go.dev/blog/context-and-structs. The Context should be the first +// parameter, typically named ctx: +// +// func DoSomething(ctx context.Context, arg Arg) error { +// // ... use ctx ... +// } +// +// Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] +// if you are unsure about which Context to use. +// +// Use context Values only for request-scoped data that transits processes and +// APIs, not for passing optional parameters to functions. +// +// The same Context may be passed to functions running in different goroutines; +// Contexts are safe for simultaneous use by multiple goroutines. +// +// See https://go.dev/blog/context for example code for a server that uses +// Contexts. +// +// [go fix]: https://go.dev/cmd/go#hdr-Update_packages_to_use_new_APIs +package context + +import ( + "context" // standard library's context, as of Go 1.7 + "time" +) + +// A Context carries a deadline, a cancellation signal, and other values across +// API boundaries. +// +// Context's methods may be called by multiple goroutines simultaneously. +type Context = context.Context + +// Canceled is the error returned by [Context.Err] when the context is canceled +// for some reason other than its deadline passing. +var Canceled = context.Canceled + +// DeadlineExceeded is the error returned by [Context.Err] when the context is canceled +// due to its deadline passing. +var DeadlineExceeded = context.DeadlineExceeded + +// Background returns a non-nil, empty Context. It is never canceled, has no +// values, and has no deadline. It is typically used by the main function, +// initialization, and tests, and as the top-level Context for incoming +// requests. +func Background() Context { + return background +} + +// TODO returns a non-nil, empty Context. Code should use context.TODO when +// it's unclear which Context to use or it is not yet available (because the +// surrounding function has not yet been extended to accept a Context +// parameter). +func TODO() Context { + return todo +} + +var ( + background = context.Background() + todo = context.TODO() +) + +// A CancelFunc tells an operation to abandon its work. +// A CancelFunc does not wait for the work to stop. +// A CancelFunc may be called by multiple goroutines simultaneously. +// After the first call, subsequent calls to a CancelFunc do nothing. +type CancelFunc = context.CancelFunc + +// WithCancel returns a derived context that points to the parent context +// but has a new Done channel. The returned context's Done channel is closed +// when the returned cancel function is called or when the parent context's +// Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this [Context] complete. +func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { + return context.WithCancel(parent) +} + +// WithDeadline returns a derived context that points to the parent context +// but has the deadline adjusted to be no later than d. If the parent's +// deadline is already earlier than d, WithDeadline(parent, d) is semantically +// equivalent to parent. The returned [Context.Done] channel is closed when +// the deadline expires, when the returned cancel function is called, +// or when the parent context's Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this [Context] complete. +func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { + return context.WithDeadline(parent, d) +} + +// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this [Context] complete: +// +// func slowOperationWithTimeout(ctx context.Context) (Result, error) { +// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) +// defer cancel() // releases resources if slowOperation completes before timeout elapses +// return slowOperation(ctx) +// } +func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { + return context.WithTimeout(parent, timeout) +} + +// WithValue returns a derived context that points to the parent Context. +// In the derived context, the value associated with key is val. +// +// Use context Values only for request-scoped data that transits processes and +// APIs, not for passing optional parameters to functions. +// +// The provided key must be comparable and should not be of type +// string or any other built-in type to avoid collisions between +// packages using context. Users of WithValue should define their own +// types for keys. To avoid allocating when assigning to an +// interface{}, context keys often have concrete type +// struct{}. Alternatively, exported context key variables' static +// type should be a pointer or interface. +func WithValue(parent Context, key, val interface{}) Context { + return context.WithValue(parent, key, val) +} diff --git a/vendor/golang.org/x/oauth2/.travis.yml b/vendor/golang.org/x/oauth2/.travis.yml new file mode 100644 index 00000000..fa139db2 --- /dev/null +++ b/vendor/golang.org/x/oauth2/.travis.yml @@ -0,0 +1,13 @@ +language: go + +go: + - tip + +install: + - export GOPATH="$HOME/gopath" + - mkdir -p "$GOPATH/src/golang.org/x" + - mv "$TRAVIS_BUILD_DIR" "$GOPATH/src/golang.org/x/oauth2" + - go get -v -t -d golang.org/x/oauth2/... + +script: + - go test -v golang.org/x/oauth2/... diff --git a/vendor/golang.org/x/oauth2/CONTRIBUTING.md b/vendor/golang.org/x/oauth2/CONTRIBUTING.md new file mode 100644 index 00000000..dfbed62c --- /dev/null +++ b/vendor/golang.org/x/oauth2/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing to Go + +Go is an open source project. + +It is the work of hundreds of contributors. We appreciate your help! + +## Filing issues + +When [filing an issue](https://github.com/golang/oauth2/issues), make sure to answer these five questions: + +1. What version of Go are you using (`go version`)? +2. What operating system and processor architecture are you using? +3. What did you do? +4. What did you expect to see? +5. What did you see instead? + +General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. +The gophers there will answer or ask you to file an issue if you've tripped over a bug. + +## Contributing code + +Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) +before sending patches. + +Unless otherwise noted, the Go source files are distributed under +the BSD-style license found in the LICENSE file. diff --git a/vendor/golang.org/x/oauth2/LICENSE b/vendor/golang.org/x/oauth2/LICENSE new file mode 100644 index 00000000..2a7cf70d --- /dev/null +++ b/vendor/golang.org/x/oauth2/LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/oauth2/README.md b/vendor/golang.org/x/oauth2/README.md new file mode 100644 index 00000000..48dbb9d8 --- /dev/null +++ b/vendor/golang.org/x/oauth2/README.md @@ -0,0 +1,35 @@ +# OAuth2 for Go + +[![Go Reference](https://pkg.go.dev/badge/golang.org/x/oauth2.svg)](https://pkg.go.dev/golang.org/x/oauth2) +[![Build Status](https://travis-ci.org/golang/oauth2.svg?branch=master)](https://travis-ci.org/golang/oauth2) + +oauth2 package contains a client implementation for OAuth 2.0 spec. + +See pkg.go.dev for further documentation and examples. + +* [pkg.go.dev/golang.org/x/oauth2](https://pkg.go.dev/golang.org/x/oauth2) +* [pkg.go.dev/golang.org/x/oauth2/google](https://pkg.go.dev/golang.org/x/oauth2/google) + +## Policy for new endpoints + +We no longer accept new provider-specific packages in this repo if all +they do is add a single endpoint variable. If you just want to add a +single endpoint, add it to the +[pkg.go.dev/golang.org/x/oauth2/endpoints](https://pkg.go.dev/golang.org/x/oauth2/endpoints) +package. + +## Report Issues / Send Patches + +The main issue tracker for the oauth2 repository is located at +https://github.com/golang/oauth2/issues. + +This repository uses Gerrit for code changes. To learn how to submit changes to +this repository, see https://go.dev/doc/contribute. + +The git repository is https://go.googlesource.com/oauth2. + +Note: + +* Excluding trivial changes, all contributions should be connected to an existing issue. +* API changes must go through the [change proposal process](https://go.dev/s/proposal-process) before they can be accepted. +* The code owners are listed at [dev.golang.org/owners](https://dev.golang.org/owners#:~:text=x/oauth2). diff --git a/vendor/golang.org/x/oauth2/deviceauth.go b/vendor/golang.org/x/oauth2/deviceauth.go new file mode 100644 index 00000000..e99c92f3 --- /dev/null +++ b/vendor/golang.org/x/oauth2/deviceauth.go @@ -0,0 +1,198 @@ +package oauth2 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "golang.org/x/oauth2/internal" +) + +// https://datatracker.ietf.org/doc/html/rfc8628#section-3.5 +const ( + errAuthorizationPending = "authorization_pending" + errSlowDown = "slow_down" + errAccessDenied = "access_denied" + errExpiredToken = "expired_token" +) + +// DeviceAuthResponse describes a successful RFC 8628 Device Authorization Response +// https://datatracker.ietf.org/doc/html/rfc8628#section-3.2 +type DeviceAuthResponse struct { + // DeviceCode + DeviceCode string `json:"device_code"` + // UserCode is the code the user should enter at the verification uri + UserCode string `json:"user_code"` + // VerificationURI is where user should enter the user code + VerificationURI string `json:"verification_uri"` + // VerificationURIComplete (if populated) includes the user code in the verification URI. This is typically shown to the user in non-textual form, such as a QR code. + VerificationURIComplete string `json:"verification_uri_complete,omitempty"` + // Expiry is when the device code and user code expire + Expiry time.Time `json:"expires_in,omitempty"` + // Interval is the duration in seconds that Poll should wait between requests + Interval int64 `json:"interval,omitempty"` +} + +func (d DeviceAuthResponse) MarshalJSON() ([]byte, error) { + type Alias DeviceAuthResponse + var expiresIn int64 + if !d.Expiry.IsZero() { + expiresIn = int64(time.Until(d.Expiry).Seconds()) + } + return json.Marshal(&struct { + ExpiresIn int64 `json:"expires_in,omitempty"` + *Alias + }{ + ExpiresIn: expiresIn, + Alias: (*Alias)(&d), + }) + +} + +func (c *DeviceAuthResponse) UnmarshalJSON(data []byte) error { + type Alias DeviceAuthResponse + aux := &struct { + ExpiresIn int64 `json:"expires_in"` + // workaround misspelling of verification_uri + VerificationURL string `json:"verification_url"` + *Alias + }{ + Alias: (*Alias)(c), + } + if err := json.Unmarshal(data, &aux); err != nil { + return err + } + if aux.ExpiresIn != 0 { + c.Expiry = time.Now().UTC().Add(time.Second * time.Duration(aux.ExpiresIn)) + } + if c.VerificationURI == "" { + c.VerificationURI = aux.VerificationURL + } + return nil +} + +// DeviceAuth returns a device auth struct which contains a device code +// and authorization information provided for users to enter on another device. +func (c *Config) DeviceAuth(ctx context.Context, opts ...AuthCodeOption) (*DeviceAuthResponse, error) { + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.1 + v := url.Values{ + "client_id": {c.ClientID}, + } + if len(c.Scopes) > 0 { + v.Set("scope", strings.Join(c.Scopes, " ")) + } + for _, opt := range opts { + opt.setValue(v) + } + return retrieveDeviceAuth(ctx, c, v) +} + +func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAuthResponse, error) { + if c.Endpoint.DeviceAuthURL == "" { + return nil, errors.New("endpoint missing DeviceAuthURL") + } + + req, err := http.NewRequest("POST", c.Endpoint.DeviceAuthURL, strings.NewReader(v.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + t := time.Now() + r, err := internal.ContextClient(ctx).Do(req) + if err != nil { + return nil, err + } + + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + return nil, fmt.Errorf("oauth2: cannot auth device: %v", err) + } + if code := r.StatusCode; code < 200 || code > 299 { + return nil, &RetrieveError{ + Response: r, + Body: body, + } + } + + da := &DeviceAuthResponse{} + err = json.Unmarshal(body, &da) + if err != nil { + return nil, fmt.Errorf("unmarshal %s", err) + } + + if !da.Expiry.IsZero() { + // Make a small adjustment to account for time taken by the request + da.Expiry = da.Expiry.Add(-time.Since(t)) + } + + return da, nil +} + +// DeviceAccessToken polls the server to exchange a device code for a token. +func (c *Config) DeviceAccessToken(ctx context.Context, da *DeviceAuthResponse, opts ...AuthCodeOption) (*Token, error) { + if !da.Expiry.IsZero() { + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, da.Expiry) + defer cancel() + } + + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.4 + v := url.Values{ + "client_id": {c.ClientID}, + "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, + "device_code": {da.DeviceCode}, + } + if len(c.Scopes) > 0 { + v.Set("scope", strings.Join(c.Scopes, " ")) + } + for _, opt := range opts { + opt.setValue(v) + } + + // "If no value is provided, clients MUST use 5 as the default." + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.2 + interval := da.Interval + if interval == 0 { + interval = 5 + } + + ticker := time.NewTicker(time.Duration(interval) * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-ticker.C: + tok, err := retrieveToken(ctx, c, v) + if err == nil { + return tok, nil + } + + e, ok := err.(*RetrieveError) + if !ok { + return nil, err + } + switch e.ErrorCode { + case errSlowDown: + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.5 + // "the interval MUST be increased by 5 seconds for this and all subsequent requests" + interval += 5 + ticker.Reset(time.Duration(interval) * time.Second) + case errAuthorizationPending: + // Do nothing. + case errAccessDenied, errExpiredToken: + fallthrough + default: + return tok, err + } + } + } +} diff --git a/vendor/golang.org/x/oauth2/internal/doc.go b/vendor/golang.org/x/oauth2/internal/doc.go new file mode 100644 index 00000000..03265e88 --- /dev/null +++ b/vendor/golang.org/x/oauth2/internal/doc.go @@ -0,0 +1,6 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package internal contains support packages for oauth2 package. +package internal diff --git a/vendor/golang.org/x/oauth2/internal/oauth2.go b/vendor/golang.org/x/oauth2/internal/oauth2.go new file mode 100644 index 00000000..14989bea --- /dev/null +++ b/vendor/golang.org/x/oauth2/internal/oauth2.go @@ -0,0 +1,37 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" +) + +// ParseKey converts the binary contents of a private key file +// to an *rsa.PrivateKey. It detects whether the private key is in a +// PEM container or not. If so, it extracts the private key +// from PEM container before conversion. It only supports PEM +// containers with no passphrase. +func ParseKey(key []byte) (*rsa.PrivateKey, error) { + block, _ := pem.Decode(key) + if block != nil { + key = block.Bytes + } + parsedKey, err := x509.ParsePKCS8PrivateKey(key) + if err != nil { + parsedKey, err = x509.ParsePKCS1PrivateKey(key) + if err != nil { + return nil, fmt.Errorf("private key should be a PEM or plain PKCS1 or PKCS8; parse error: %v", err) + } + } + parsed, ok := parsedKey.(*rsa.PrivateKey) + if !ok { + return nil, errors.New("private key is invalid") + } + return parsed, nil +} diff --git a/vendor/golang.org/x/oauth2/internal/token.go b/vendor/golang.org/x/oauth2/internal/token.go new file mode 100644 index 00000000..e83ddeef --- /dev/null +++ b/vendor/golang.org/x/oauth2/internal/token.go @@ -0,0 +1,352 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "math" + "mime" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// Token represents the credentials used to authorize +// the requests to access protected resources on the OAuth 2.0 +// provider's backend. +// +// This type is a mirror of oauth2.Token and exists to break +// an otherwise-circular dependency. Other internal packages +// should convert this Token into an oauth2.Token before use. +type Token struct { + // AccessToken is the token that authorizes and authenticates + // the requests. + AccessToken string + + // TokenType is the type of token. + // The Type method returns either this or "Bearer", the default. + TokenType string + + // RefreshToken is a token that's used by the application + // (as opposed to the user) to refresh the access token + // if it expires. + RefreshToken string + + // Expiry is the optional expiration time of the access token. + // + // If zero, TokenSource implementations will reuse the same + // token forever and RefreshToken or equivalent + // mechanisms for that TokenSource will not be used. + Expiry time.Time + + // Raw optionally contains extra metadata from the server + // when updating a token. + Raw interface{} +} + +// tokenJSON is the struct representing the HTTP response from OAuth2 +// providers returning a token or error in JSON form. +// https://datatracker.ietf.org/doc/html/rfc6749#section-5.1 +type tokenJSON struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + RefreshToken string `json:"refresh_token"` + ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number + // error fields + // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 + ErrorCode string `json:"error"` + ErrorDescription string `json:"error_description"` + ErrorURI string `json:"error_uri"` +} + +func (e *tokenJSON) expiry() (t time.Time) { + if v := e.ExpiresIn; v != 0 { + return time.Now().Add(time.Duration(v) * time.Second) + } + return +} + +type expirationTime int32 + +func (e *expirationTime) UnmarshalJSON(b []byte) error { + if len(b) == 0 || string(b) == "null" { + return nil + } + var n json.Number + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + i, err := n.Int64() + if err != nil { + return err + } + if i > math.MaxInt32 { + i = math.MaxInt32 + } + *e = expirationTime(i) + return nil +} + +// RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op. +// +// Deprecated: this function no longer does anything. Caller code that +// wants to avoid potential extra HTTP requests made during +// auto-probing of the provider's auth style should set +// Endpoint.AuthStyle. +func RegisterBrokenAuthHeaderProvider(tokenURL string) {} + +// AuthStyle is a copy of the golang.org/x/oauth2 package's AuthStyle type. +type AuthStyle int + +const ( + AuthStyleUnknown AuthStyle = 0 + AuthStyleInParams AuthStyle = 1 + AuthStyleInHeader AuthStyle = 2 +) + +// LazyAuthStyleCache is a backwards compatibility compromise to let Configs +// have a lazily-initialized AuthStyleCache. +// +// The two users of this, oauth2.Config and oauth2/clientcredentials.Config, +// both would ideally just embed an unexported AuthStyleCache but because both +// were historically allowed to be copied by value we can't retroactively add an +// uncopyable Mutex to them. +// +// We could use an atomic.Pointer, but that was added recently enough (in Go +// 1.18) that we'd break Go 1.17 users where the tests as of 2023-08-03 +// still pass. By using an atomic.Value, it supports both Go 1.17 and +// copying by value, even if that's not ideal. +type LazyAuthStyleCache struct { + v atomic.Value // of *AuthStyleCache +} + +func (lc *LazyAuthStyleCache) Get() *AuthStyleCache { + if c, ok := lc.v.Load().(*AuthStyleCache); ok { + return c + } + c := new(AuthStyleCache) + if !lc.v.CompareAndSwap(nil, c) { + c = lc.v.Load().(*AuthStyleCache) + } + return c +} + +// AuthStyleCache is the set of tokenURLs we've successfully used via +// RetrieveToken and which style auth we ended up using. +// It's called a cache, but it doesn't (yet?) shrink. It's expected that +// the set of OAuth2 servers a program contacts over time is fixed and +// small. +type AuthStyleCache struct { + mu sync.Mutex + m map[string]AuthStyle // keyed by tokenURL +} + +// lookupAuthStyle reports which auth style we last used with tokenURL +// when calling RetrieveToken and whether we have ever done so. +func (c *AuthStyleCache) lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) { + c.mu.Lock() + defer c.mu.Unlock() + style, ok = c.m[tokenURL] + return +} + +// setAuthStyle adds an entry to authStyleCache, documented above. +func (c *AuthStyleCache) setAuthStyle(tokenURL string, v AuthStyle) { + c.mu.Lock() + defer c.mu.Unlock() + if c.m == nil { + c.m = make(map[string]AuthStyle) + } + c.m[tokenURL] = v +} + +// newTokenRequest returns a new *http.Request to retrieve a new token +// from tokenURL using the provided clientID, clientSecret, and POST +// body parameters. +// +// inParams is whether the clientID & clientSecret should be encoded +// as the POST body. An 'inParams' value of true means to send it in +// the POST body (along with any values in v); false means to send it +// in the Authorization header. +func newTokenRequest(tokenURL, clientID, clientSecret string, v url.Values, authStyle AuthStyle) (*http.Request, error) { + if authStyle == AuthStyleInParams { + v = cloneURLValues(v) + if clientID != "" { + v.Set("client_id", clientID) + } + if clientSecret != "" { + v.Set("client_secret", clientSecret) + } + } + req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if authStyle == AuthStyleInHeader { + req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret)) + } + return req, nil +} + +func cloneURLValues(v url.Values) url.Values { + v2 := make(url.Values, len(v)) + for k, vv := range v { + v2[k] = append([]string(nil), vv...) + } + return v2 +} + +func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values, authStyle AuthStyle, styleCache *AuthStyleCache) (*Token, error) { + needsAuthStyleProbe := authStyle == 0 + if needsAuthStyleProbe { + if style, ok := styleCache.lookupAuthStyle(tokenURL); ok { + authStyle = style + needsAuthStyleProbe = false + } else { + authStyle = AuthStyleInHeader // the first way we'll try + } + } + req, err := newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle) + if err != nil { + return nil, err + } + token, err := doTokenRoundTrip(ctx, req) + if err != nil && needsAuthStyleProbe { + // If we get an error, assume the server wants the + // clientID & clientSecret in a different form. + // See https://code.google.com/p/goauth2/issues/detail?id=31 for background. + // In summary: + // - Reddit only accepts client secret in the Authorization header + // - Dropbox accepts either it in URL param or Auth header, but not both. + // - Google only accepts URL param (not spec compliant?), not Auth header + // - Stripe only accepts client secret in Auth header with Bearer method, not Basic + // + // We used to maintain a big table in this code of all the sites and which way + // they went, but maintaining it didn't scale & got annoying. + // So just try both ways. + authStyle = AuthStyleInParams // the second way we'll try + req, _ = newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle) + token, err = doTokenRoundTrip(ctx, req) + } + if needsAuthStyleProbe && err == nil { + styleCache.setAuthStyle(tokenURL, authStyle) + } + // Don't overwrite `RefreshToken` with an empty value + // if this was a token refreshing request. + if token != nil && token.RefreshToken == "" { + token.RefreshToken = v.Get("refresh_token") + } + return token, err +} + +func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { + r, err := ContextClient(ctx).Do(req.WithContext(ctx)) + if err != nil { + return nil, err + } + body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) + r.Body.Close() + if err != nil { + return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) + } + + failureStatus := r.StatusCode < 200 || r.StatusCode > 299 + retrieveError := &RetrieveError{ + Response: r, + Body: body, + // attempt to populate error detail below + } + + var token *Token + content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) + switch content { + case "application/x-www-form-urlencoded", "text/plain": + // some endpoints return a query string + vals, err := url.ParseQuery(string(body)) + if err != nil { + if failureStatus { + return nil, retrieveError + } + return nil, fmt.Errorf("oauth2: cannot parse response: %v", err) + } + retrieveError.ErrorCode = vals.Get("error") + retrieveError.ErrorDescription = vals.Get("error_description") + retrieveError.ErrorURI = vals.Get("error_uri") + token = &Token{ + AccessToken: vals.Get("access_token"), + TokenType: vals.Get("token_type"), + RefreshToken: vals.Get("refresh_token"), + Raw: vals, + } + e := vals.Get("expires_in") + expires, _ := strconv.Atoi(e) + if expires != 0 { + token.Expiry = time.Now().Add(time.Duration(expires) * time.Second) + } + default: + var tj tokenJSON + if err = json.Unmarshal(body, &tj); err != nil { + if failureStatus { + return nil, retrieveError + } + return nil, fmt.Errorf("oauth2: cannot parse json: %v", err) + } + retrieveError.ErrorCode = tj.ErrorCode + retrieveError.ErrorDescription = tj.ErrorDescription + retrieveError.ErrorURI = tj.ErrorURI + token = &Token{ + AccessToken: tj.AccessToken, + TokenType: tj.TokenType, + RefreshToken: tj.RefreshToken, + Expiry: tj.expiry(), + Raw: make(map[string]interface{}), + } + json.Unmarshal(body, &token.Raw) // no error checks for optional fields + } + // according to spec, servers should respond status 400 in error case + // https://www.rfc-editor.org/rfc/rfc6749#section-5.2 + // but some unorthodox servers respond 200 in error case + if failureStatus || retrieveError.ErrorCode != "" { + return nil, retrieveError + } + if token.AccessToken == "" { + return nil, errors.New("oauth2: server response missing access_token") + } + return token, nil +} + +// mirrors oauth2.RetrieveError +type RetrieveError struct { + Response *http.Response + Body []byte + ErrorCode string + ErrorDescription string + ErrorURI string +} + +func (r *RetrieveError) Error() string { + if r.ErrorCode != "" { + s := fmt.Sprintf("oauth2: %q", r.ErrorCode) + if r.ErrorDescription != "" { + s += fmt.Sprintf(" %q", r.ErrorDescription) + } + if r.ErrorURI != "" { + s += fmt.Sprintf(" %q", r.ErrorURI) + } + return s + } + return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) +} diff --git a/vendor/golang.org/x/oauth2/internal/transport.go b/vendor/golang.org/x/oauth2/internal/transport.go new file mode 100644 index 00000000..b9db01dd --- /dev/null +++ b/vendor/golang.org/x/oauth2/internal/transport.go @@ -0,0 +1,28 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +import ( + "context" + "net/http" +) + +// HTTPClient is the context key to use with golang.org/x/net/context's +// WithValue function to associate an *http.Client value with a context. +var HTTPClient ContextKey + +// ContextKey is just an empty struct. It exists so HTTPClient can be +// an immutable public variable with a unique type. It's immutable +// because nobody else can create a ContextKey, being unexported. +type ContextKey struct{} + +func ContextClient(ctx context.Context) *http.Client { + if ctx != nil { + if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok { + return hc + } + } + return http.DefaultClient +} diff --git a/vendor/golang.org/x/oauth2/oauth2.go b/vendor/golang.org/x/oauth2/oauth2.go new file mode 100644 index 00000000..74f052aa --- /dev/null +++ b/vendor/golang.org/x/oauth2/oauth2.go @@ -0,0 +1,421 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package oauth2 provides support for making +// OAuth2 authorized and authenticated HTTP requests, +// as specified in RFC 6749. +// It can additionally grant authorization with Bearer JWT. +package oauth2 // import "golang.org/x/oauth2" + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "golang.org/x/oauth2/internal" +) + +// NoContext is the default context you should supply if not using +// your own context.Context (see https://golang.org/x/net/context). +// +// Deprecated: Use context.Background() or context.TODO() instead. +var NoContext = context.TODO() + +// RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op. +// +// Deprecated: this function no longer does anything. Caller code that +// wants to avoid potential extra HTTP requests made during +// auto-probing of the provider's auth style should set +// Endpoint.AuthStyle. +func RegisterBrokenAuthHeaderProvider(tokenURL string) {} + +// Config describes a typical 3-legged OAuth2 flow, with both the +// client application information and the server's endpoint URLs. +// For the client credentials 2-legged OAuth2 flow, see the clientcredentials +// package (https://golang.org/x/oauth2/clientcredentials). +type Config struct { + // ClientID is the application's ID. + ClientID string + + // ClientSecret is the application's secret. + ClientSecret string + + // Endpoint contains the resource server's token endpoint + // URLs. These are constants specific to each server and are + // often available via site-specific packages, such as + // google.Endpoint or github.Endpoint. + Endpoint Endpoint + + // RedirectURL is the URL to redirect users going through + // the OAuth flow, after the resource owner's URLs. + RedirectURL string + + // Scopes specifies optional requested permissions. + Scopes []string + + // authStyleCache caches which auth style to use when Endpoint.AuthStyle is + // the zero value (AuthStyleAutoDetect). + authStyleCache internal.LazyAuthStyleCache +} + +// A TokenSource is anything that can return a token. +type TokenSource interface { + // Token returns a token or an error. + // Token must be safe for concurrent use by multiple goroutines. + // The returned Token must not be modified. + Token() (*Token, error) +} + +// Endpoint represents an OAuth 2.0 provider's authorization and token +// endpoint URLs. +type Endpoint struct { + AuthURL string + DeviceAuthURL string + TokenURL string + + // AuthStyle optionally specifies how the endpoint wants the + // client ID & client secret sent. The zero value means to + // auto-detect. + AuthStyle AuthStyle +} + +// AuthStyle represents how requests for tokens are authenticated +// to the server. +type AuthStyle int + +const ( + // AuthStyleAutoDetect means to auto-detect which authentication + // style the provider wants by trying both ways and caching + // the successful way for the future. + AuthStyleAutoDetect AuthStyle = 0 + + // AuthStyleInParams sends the "client_id" and "client_secret" + // in the POST body as application/x-www-form-urlencoded parameters. + AuthStyleInParams AuthStyle = 1 + + // AuthStyleInHeader sends the client_id and client_password + // using HTTP Basic Authorization. This is an optional style + // described in the OAuth2 RFC 6749 section 2.3.1. + AuthStyleInHeader AuthStyle = 2 +) + +var ( + // AccessTypeOnline and AccessTypeOffline are options passed + // to the Options.AuthCodeURL method. They modify the + // "access_type" field that gets sent in the URL returned by + // AuthCodeURL. + // + // Online is the default if neither is specified. If your + // application needs to refresh access tokens when the user + // is not present at the browser, then use offline. This will + // result in your application obtaining a refresh token the + // first time your application exchanges an authorization + // code for a user. + AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online") + AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline") + + // ApprovalForce forces the users to view the consent dialog + // and confirm the permissions request at the URL returned + // from AuthCodeURL, even if they've already done so. + ApprovalForce AuthCodeOption = SetAuthURLParam("prompt", "consent") +) + +// An AuthCodeOption is passed to Config.AuthCodeURL. +type AuthCodeOption interface { + setValue(url.Values) +} + +type setParam struct{ k, v string } + +func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) } + +// SetAuthURLParam builds an AuthCodeOption which passes key/value parameters +// to a provider's authorization endpoint. +func SetAuthURLParam(key, value string) AuthCodeOption { + return setParam{key, value} +} + +// AuthCodeURL returns a URL to OAuth 2.0 provider's consent page +// that asks for permissions for the required scopes explicitly. +// +// State is an opaque value used by the client to maintain state between the +// request and callback. The authorization server includes this value when +// redirecting the user agent back to the client. +// +// Opts may include AccessTypeOnline or AccessTypeOffline, as well +// as ApprovalForce. +// +// To protect against CSRF attacks, opts should include a PKCE challenge +// (S256ChallengeOption). Not all servers support PKCE. An alternative is to +// generate a random state parameter and verify it after exchange. +// See https://datatracker.ietf.org/doc/html/rfc6749#section-10.12 (predating +// PKCE), https://www.oauth.com/oauth2-servers/pkce/ and +// https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-09.html#name-cross-site-request-forgery (describing both approaches) +func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string { + var buf bytes.Buffer + buf.WriteString(c.Endpoint.AuthURL) + v := url.Values{ + "response_type": {"code"}, + "client_id": {c.ClientID}, + } + if c.RedirectURL != "" { + v.Set("redirect_uri", c.RedirectURL) + } + if len(c.Scopes) > 0 { + v.Set("scope", strings.Join(c.Scopes, " ")) + } + if state != "" { + v.Set("state", state) + } + for _, opt := range opts { + opt.setValue(v) + } + if strings.Contains(c.Endpoint.AuthURL, "?") { + buf.WriteByte('&') + } else { + buf.WriteByte('?') + } + buf.WriteString(v.Encode()) + return buf.String() +} + +// PasswordCredentialsToken converts a resource owner username and password +// pair into a token. +// +// Per the RFC, this grant type should only be used "when there is a high +// degree of trust between the resource owner and the client (e.g., the client +// is part of the device operating system or a highly privileged application), +// and when other authorization grant types are not available." +// See https://tools.ietf.org/html/rfc6749#section-4.3 for more info. +// +// The provided context optionally controls which HTTP client is used. See the HTTPClient variable. +func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) { + v := url.Values{ + "grant_type": {"password"}, + "username": {username}, + "password": {password}, + } + if len(c.Scopes) > 0 { + v.Set("scope", strings.Join(c.Scopes, " ")) + } + return retrieveToken(ctx, c, v) +} + +// Exchange converts an authorization code into a token. +// +// It is used after a resource provider redirects the user back +// to the Redirect URI (the URL obtained from AuthCodeURL). +// +// The provided context optionally controls which HTTP client is used. See the HTTPClient variable. +// +// The code will be in the *http.Request.FormValue("code"). Before +// calling Exchange, be sure to validate FormValue("state") if you are +// using it to protect against CSRF attacks. +// +// If using PKCE to protect against CSRF attacks, opts should include a +// VerifierOption. +func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error) { + v := url.Values{ + "grant_type": {"authorization_code"}, + "code": {code}, + } + if c.RedirectURL != "" { + v.Set("redirect_uri", c.RedirectURL) + } + for _, opt := range opts { + opt.setValue(v) + } + return retrieveToken(ctx, c, v) +} + +// Client returns an HTTP client using the provided token. +// The token will auto-refresh as necessary. The underlying +// HTTP transport will be obtained using the provided context. +// The returned client and its Transport should not be modified. +func (c *Config) Client(ctx context.Context, t *Token) *http.Client { + return NewClient(ctx, c.TokenSource(ctx, t)) +} + +// TokenSource returns a TokenSource that returns t until t expires, +// automatically refreshing it as necessary using the provided context. +// +// Most users will use Config.Client instead. +func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource { + tkr := &tokenRefresher{ + ctx: ctx, + conf: c, + } + if t != nil { + tkr.refreshToken = t.RefreshToken + } + return &reuseTokenSource{ + t: t, + new: tkr, + } +} + +// tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token" +// HTTP requests to renew a token using a RefreshToken. +type tokenRefresher struct { + ctx context.Context // used to get HTTP requests + conf *Config + refreshToken string +} + +// WARNING: Token is not safe for concurrent access, as it +// updates the tokenRefresher's refreshToken field. +// Within this package, it is used by reuseTokenSource which +// synchronizes calls to this method with its own mutex. +func (tf *tokenRefresher) Token() (*Token, error) { + if tf.refreshToken == "" { + return nil, errors.New("oauth2: token expired and refresh token is not set") + } + + tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{ + "grant_type": {"refresh_token"}, + "refresh_token": {tf.refreshToken}, + }) + + if err != nil { + return nil, err + } + if tf.refreshToken != tk.RefreshToken { + tf.refreshToken = tk.RefreshToken + } + return tk, err +} + +// reuseTokenSource is a TokenSource that holds a single token in memory +// and validates its expiry before each call to retrieve it with +// Token. If it's expired, it will be auto-refreshed using the +// new TokenSource. +type reuseTokenSource struct { + new TokenSource // called when t is expired. + + mu sync.Mutex // guards t + t *Token + + expiryDelta time.Duration +} + +// Token returns the current token if it's still valid, else will +// refresh the current token (using r.Context for HTTP client +// information) and return the new one. +func (s *reuseTokenSource) Token() (*Token, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.t.Valid() { + return s.t, nil + } + t, err := s.new.Token() + if err != nil { + return nil, err + } + t.expiryDelta = s.expiryDelta + s.t = t + return t, nil +} + +// StaticTokenSource returns a TokenSource that always returns the same token. +// Because the provided token t is never refreshed, StaticTokenSource is only +// useful for tokens that never expire. +func StaticTokenSource(t *Token) TokenSource { + return staticTokenSource{t} +} + +// staticTokenSource is a TokenSource that always returns the same Token. +type staticTokenSource struct { + t *Token +} + +func (s staticTokenSource) Token() (*Token, error) { + return s.t, nil +} + +// HTTPClient is the context key to use with golang.org/x/net/context's +// WithValue function to associate an *http.Client value with a context. +var HTTPClient internal.ContextKey + +// NewClient creates an *http.Client from a Context and TokenSource. +// The returned client is not valid beyond the lifetime of the context. +// +// Note that if a custom *http.Client is provided via the Context it +// is used only for token acquisition and is not used to configure the +// *http.Client returned from NewClient. +// +// As a special case, if src is nil, a non-OAuth2 client is returned +// using the provided context. This exists to support related OAuth2 +// packages. +func NewClient(ctx context.Context, src TokenSource) *http.Client { + if src == nil { + return internal.ContextClient(ctx) + } + return &http.Client{ + Transport: &Transport{ + Base: internal.ContextClient(ctx).Transport, + Source: ReuseTokenSource(nil, src), + }, + } +} + +// ReuseTokenSource returns a TokenSource which repeatedly returns the +// same token as long as it's valid, starting with t. +// When its cached token is invalid, a new token is obtained from src. +// +// ReuseTokenSource is typically used to reuse tokens from a cache +// (such as a file on disk) between runs of a program, rather than +// obtaining new tokens unnecessarily. +// +// The initial token t may be nil, in which case the TokenSource is +// wrapped in a caching version if it isn't one already. This also +// means it's always safe to wrap ReuseTokenSource around any other +// TokenSource without adverse effects. +func ReuseTokenSource(t *Token, src TokenSource) TokenSource { + // Don't wrap a reuseTokenSource in itself. That would work, + // but cause an unnecessary number of mutex operations. + // Just build the equivalent one. + if rt, ok := src.(*reuseTokenSource); ok { + if t == nil { + // Just use it directly. + return rt + } + src = rt.new + } + return &reuseTokenSource{ + t: t, + new: src, + } +} + +// ReuseTokenSourceWithExpiry returns a TokenSource that acts in the same manner as the +// TokenSource returned by ReuseTokenSource, except the expiry buffer is +// configurable. The expiration time of a token is calculated as +// t.Expiry.Add(-earlyExpiry). +func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSource { + // Don't wrap a reuseTokenSource in itself. That would work, + // but cause an unnecessary number of mutex operations. + // Just build the equivalent one. + if rt, ok := src.(*reuseTokenSource); ok { + if t == nil { + // Just use it directly, but set the expiryDelta to earlyExpiry, + // so the behavior matches what the user expects. + rt.expiryDelta = earlyExpiry + return rt + } + src = rt.new + } + if t != nil { + t.expiryDelta = earlyExpiry + } + return &reuseTokenSource{ + t: t, + new: src, + expiryDelta: earlyExpiry, + } +} diff --git a/vendor/golang.org/x/oauth2/pkce.go b/vendor/golang.org/x/oauth2/pkce.go new file mode 100644 index 00000000..6a95da97 --- /dev/null +++ b/vendor/golang.org/x/oauth2/pkce.go @@ -0,0 +1,68 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package oauth2 + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "net/url" +) + +const ( + codeChallengeKey = "code_challenge" + codeChallengeMethodKey = "code_challenge_method" + codeVerifierKey = "code_verifier" +) + +// GenerateVerifier generates a PKCE code verifier with 32 octets of randomness. +// This follows recommendations in RFC 7636. +// +// A fresh verifier should be generated for each authorization. +// S256ChallengeOption(verifier) should then be passed to Config.AuthCodeURL +// (or Config.DeviceAuth) and VerifierOption(verifier) to Config.Exchange +// (or Config.DeviceAccessToken). +func GenerateVerifier() string { + // "RECOMMENDED that the output of a suitable random number generator be + // used to create a 32-octet sequence. The octet sequence is then + // base64url-encoded to produce a 43-octet URL-safe string to use as the + // code verifier." + // https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 + data := make([]byte, 32) + if _, err := rand.Read(data); err != nil { + panic(err) + } + return base64.RawURLEncoding.EncodeToString(data) +} + +// VerifierOption returns a PKCE code verifier AuthCodeOption. It should be +// passed to Config.Exchange or Config.DeviceAccessToken only. +func VerifierOption(verifier string) AuthCodeOption { + return setParam{k: codeVerifierKey, v: verifier} +} + +// S256ChallengeFromVerifier returns a PKCE code challenge derived from verifier with method S256. +// +// Prefer to use S256ChallengeOption where possible. +func S256ChallengeFromVerifier(verifier string) string { + sha := sha256.Sum256([]byte(verifier)) + return base64.RawURLEncoding.EncodeToString(sha[:]) +} + +// S256ChallengeOption derives a PKCE code challenge derived from verifier with +// method S256. It should be passed to Config.AuthCodeURL or Config.DeviceAuth +// only. +func S256ChallengeOption(verifier string) AuthCodeOption { + return challengeOption{ + challenge_method: "S256", + challenge: S256ChallengeFromVerifier(verifier), + } +} + +type challengeOption struct{ challenge_method, challenge string } + +func (p challengeOption) setValue(m url.Values) { + m.Set(codeChallengeMethodKey, p.challenge_method) + m.Set(codeChallengeKey, p.challenge) +} diff --git a/vendor/golang.org/x/oauth2/token.go b/vendor/golang.org/x/oauth2/token.go new file mode 100644 index 00000000..109997d7 --- /dev/null +++ b/vendor/golang.org/x/oauth2/token.go @@ -0,0 +1,212 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package oauth2 + +import ( + "context" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "golang.org/x/oauth2/internal" +) + +// defaultExpiryDelta determines how earlier a token should be considered +// expired than its actual expiration time. It is used to avoid late +// expirations due to client-server time mismatches. +const defaultExpiryDelta = 10 * time.Second + +// Token represents the credentials used to authorize +// the requests to access protected resources on the OAuth 2.0 +// provider's backend. +// +// Most users of this package should not access fields of Token +// directly. They're exported mostly for use by related packages +// implementing derivative OAuth2 flows. +type Token struct { + // AccessToken is the token that authorizes and authenticates + // the requests. + AccessToken string `json:"access_token"` + + // TokenType is the type of token. + // The Type method returns either this or "Bearer", the default. + TokenType string `json:"token_type,omitempty"` + + // RefreshToken is a token that's used by the application + // (as opposed to the user) to refresh the access token + // if it expires. + RefreshToken string `json:"refresh_token,omitempty"` + + // Expiry is the optional expiration time of the access token. + // + // If zero, TokenSource implementations will reuse the same + // token forever and RefreshToken or equivalent + // mechanisms for that TokenSource will not be used. + Expiry time.Time `json:"expiry,omitempty"` + + // ExpiresIn is the OAuth2 wire format "expires_in" field, + // which specifies how many seconds later the token expires, + // relative to an unknown time base approximately around "now". + // It is the application's responsibility to populate + // `Expiry` from `ExpiresIn` when required. + ExpiresIn int64 `json:"expires_in,omitempty"` + + // raw optionally contains extra metadata from the server + // when updating a token. + raw interface{} + + // expiryDelta is used to calculate when a token is considered + // expired, by subtracting from Expiry. If zero, defaultExpiryDelta + // is used. + expiryDelta time.Duration +} + +// Type returns t.TokenType if non-empty, else "Bearer". +func (t *Token) Type() string { + if strings.EqualFold(t.TokenType, "bearer") { + return "Bearer" + } + if strings.EqualFold(t.TokenType, "mac") { + return "MAC" + } + if strings.EqualFold(t.TokenType, "basic") { + return "Basic" + } + if t.TokenType != "" { + return t.TokenType + } + return "Bearer" +} + +// SetAuthHeader sets the Authorization header to r using the access +// token in t. +// +// This method is unnecessary when using Transport or an HTTP Client +// returned by this package. +func (t *Token) SetAuthHeader(r *http.Request) { + r.Header.Set("Authorization", t.Type()+" "+t.AccessToken) +} + +// WithExtra returns a new Token that's a clone of t, but using the +// provided raw extra map. This is only intended for use by packages +// implementing derivative OAuth2 flows. +func (t *Token) WithExtra(extra interface{}) *Token { + t2 := new(Token) + *t2 = *t + t2.raw = extra + return t2 +} + +// Extra returns an extra field. +// Extra fields are key-value pairs returned by the server as a +// part of the token retrieval response. +func (t *Token) Extra(key string) interface{} { + if raw, ok := t.raw.(map[string]interface{}); ok { + return raw[key] + } + + vals, ok := t.raw.(url.Values) + if !ok { + return nil + } + + v := vals.Get(key) + switch s := strings.TrimSpace(v); strings.Count(s, ".") { + case 0: // Contains no "."; try to parse as int + if i, err := strconv.ParseInt(s, 10, 64); err == nil { + return i + } + case 1: // Contains a single "."; try to parse as float + if f, err := strconv.ParseFloat(s, 64); err == nil { + return f + } + } + + return v +} + +// timeNow is time.Now but pulled out as a variable for tests. +var timeNow = time.Now + +// expired reports whether the token is expired. +// t must be non-nil. +func (t *Token) expired() bool { + if t.Expiry.IsZero() { + return false + } + + expiryDelta := defaultExpiryDelta + if t.expiryDelta != 0 { + expiryDelta = t.expiryDelta + } + return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow()) +} + +// Valid reports whether t is non-nil, has an AccessToken, and is not expired. +func (t *Token) Valid() bool { + return t != nil && t.AccessToken != "" && !t.expired() +} + +// tokenFromInternal maps an *internal.Token struct into +// a *Token struct. +func tokenFromInternal(t *internal.Token) *Token { + if t == nil { + return nil + } + return &Token{ + AccessToken: t.AccessToken, + TokenType: t.TokenType, + RefreshToken: t.RefreshToken, + Expiry: t.Expiry, + raw: t.Raw, + } +} + +// retrieveToken takes a *Config and uses that to retrieve an *internal.Token. +// This token is then mapped from *internal.Token into an *oauth2.Token which is returned along +// with an error.. +func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) { + tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v, internal.AuthStyle(c.Endpoint.AuthStyle), c.authStyleCache.Get()) + if err != nil { + if rErr, ok := err.(*internal.RetrieveError); ok { + return nil, (*RetrieveError)(rErr) + } + return nil, err + } + return tokenFromInternal(tk), nil +} + +// RetrieveError is the error returned when the token endpoint returns a +// non-2XX HTTP status code or populates RFC 6749's 'error' parameter. +// https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 +type RetrieveError struct { + Response *http.Response + // Body is the body that was consumed by reading Response.Body. + // It may be truncated. + Body []byte + // ErrorCode is RFC 6749's 'error' parameter. + ErrorCode string + // ErrorDescription is RFC 6749's 'error_description' parameter. + ErrorDescription string + // ErrorURI is RFC 6749's 'error_uri' parameter. + ErrorURI string +} + +func (r *RetrieveError) Error() string { + if r.ErrorCode != "" { + s := fmt.Sprintf("oauth2: %q", r.ErrorCode) + if r.ErrorDescription != "" { + s += fmt.Sprintf(" %q", r.ErrorDescription) + } + if r.ErrorURI != "" { + s += fmt.Sprintf(" %q", r.ErrorURI) + } + return s + } + return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) +} diff --git a/vendor/golang.org/x/oauth2/transport.go b/vendor/golang.org/x/oauth2/transport.go new file mode 100644 index 00000000..90657915 --- /dev/null +++ b/vendor/golang.org/x/oauth2/transport.go @@ -0,0 +1,89 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package oauth2 + +import ( + "errors" + "log" + "net/http" + "sync" +) + +// Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, +// wrapping a base RoundTripper and adding an Authorization header +// with a token from the supplied Sources. +// +// Transport is a low-level mechanism. Most code will use the +// higher-level Config.Client method instead. +type Transport struct { + // Source supplies the token to add to outgoing requests' + // Authorization headers. + Source TokenSource + + // Base is the base RoundTripper used to make HTTP requests. + // If nil, http.DefaultTransport is used. + Base http.RoundTripper +} + +// RoundTrip authorizes and authenticates the request with an +// access token from Transport's Source. +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + reqBodyClosed := false + if req.Body != nil { + defer func() { + if !reqBodyClosed { + req.Body.Close() + } + }() + } + + if t.Source == nil { + return nil, errors.New("oauth2: Transport's Source is nil") + } + token, err := t.Source.Token() + if err != nil { + return nil, err + } + + req2 := cloneRequest(req) // per RoundTripper contract + token.SetAuthHeader(req2) + + // req.Body is assumed to be closed by the base RoundTripper. + reqBodyClosed = true + return t.base().RoundTrip(req2) +} + +var cancelOnce sync.Once + +// CancelRequest does nothing. It used to be a legacy cancellation mechanism +// but now only it only logs on first use to warn that it's deprecated. +// +// Deprecated: use contexts for cancellation instead. +func (t *Transport) CancelRequest(req *http.Request) { + cancelOnce.Do(func() { + log.Printf("deprecated: golang.org/x/oauth2: Transport.CancelRequest no longer does anything; use contexts") + }) +} + +func (t *Transport) base() http.RoundTripper { + if t.Base != nil { + return t.Base + } + return http.DefaultTransport +} + +// cloneRequest returns a clone of the provided *http.Request. +// The clone is a shallow copy of the struct and its Header map. +func cloneRequest(r *http.Request) *http.Request { + // shallow copy of the struct + r2 := new(http.Request) + *r2 = *r + // deep copy of the Header + r2.Header = make(http.Header, len(r.Header)) + for k, s := range r.Header { + r2.Header[k] = append([]string(nil), s...) + } + return r2 +} diff --git a/vendor/modules.txt b/vendor/modules.txt index c6fa4d15..1d01732d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -86,6 +86,13 @@ github.com/aws/aws-sdk-go-v2/internal/ini github.com/aws/aws-sdk-go-v2/internal/v4a github.com/aws/aws-sdk-go-v2/internal/v4a/internal/crypto github.com/aws/aws-sdk-go-v2/internal/v4a/internal/v4 +# github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.53.0 +## explicit; go 1.22 +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/document +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/document +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/internal/endpoints +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types # github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 ## explicit; go 1.22 github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding @@ -141,6 +148,8 @@ github.com/aws/smithy-go/container/private/cache github.com/aws/smithy-go/container/private/cache/lru github.com/aws/smithy-go/context github.com/aws/smithy-go/document +github.com/aws/smithy-go/document/internal/serde +github.com/aws/smithy-go/document/json github.com/aws/smithy-go/encoding github.com/aws/smithy-go/encoding/httpbinding github.com/aws/smithy-go/encoding/json @@ -591,6 +600,15 @@ github.com/pelletier/go-toml/v2/unstable # github.com/perimeterx/marshmallow v1.1.5 ## explicit; go 1.17 github.com/perimeterx/marshmallow +# github.com/permitio/permit-golang v1.2.5 +## explicit; go 1.19 +github.com/permitio/permit-golang/pkg/api +github.com/permitio/permit-golang/pkg/config +github.com/permitio/permit-golang/pkg/enforcement +github.com/permitio/permit-golang/pkg/errors +github.com/permitio/permit-golang/pkg/models +github.com/permitio/permit-golang/pkg/openapi +github.com/permitio/permit-golang/pkg/permit # github.com/pkg/errors v0.9.1 ## explicit github.com/pkg/errors @@ -817,6 +835,17 @@ go.uber.org/atomic # go.uber.org/multierr v1.11.0 ## explicit; go 1.19 go.uber.org/multierr +# go.uber.org/zap v1.26.0 +## explicit; go 1.19 +go.uber.org/zap +go.uber.org/zap/buffer +go.uber.org/zap/internal +go.uber.org/zap/internal/bufferpool +go.uber.org/zap/internal/color +go.uber.org/zap/internal/exit +go.uber.org/zap/internal/pool +go.uber.org/zap/internal/stacktrace +go.uber.org/zap/zapcore # golang.org/x/crypto v0.36.0 ## explicit; go 1.23.0 golang.org/x/crypto/acme @@ -853,6 +882,7 @@ golang.org/x/mod/module golang.org/x/mod/semver # golang.org/x/net v0.36.0 ## explicit; go 1.23.0 +golang.org/x/net/context golang.org/x/net/html golang.org/x/net/html/atom golang.org/x/net/http/httpguts @@ -863,6 +893,10 @@ golang.org/x/net/idna golang.org/x/net/internal/httpcommon golang.org/x/net/internal/timeseries golang.org/x/net/trace +# golang.org/x/oauth2 v0.27.0 +## explicit; go 1.23.0 +golang.org/x/oauth2 +golang.org/x/oauth2/internal # golang.org/x/sync v0.12.0 ## explicit; go 1.23.0 golang.org/x/sync/errgroup