Skip to content

Commit b9e4bb1

Browse files
fix(bigquery): Update samples and tests related to Table or View
1 parent 12bc84b commit b9e4bb1

File tree

6 files changed

+395
-476
lines changed

6 files changed

+395
-476
lines changed

bigquery/cloud-client/grantAccessToTableOrView.js

Lines changed: 52 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
'use strict';
16-
1715
const {BigQuery} = require('@google-cloud/bigquery');
1816

1917
/**
@@ -26,56 +24,70 @@ const {BigQuery} = require('@google-cloud/bigquery');
2624
* @param {string} role - Role to assign to the member
2725
* @returns {Promise<object[]>} The updated policy bindings
2826
*/
29-
async function grantAccessToTableOrView({
27+
async function grantAccessToTableOrView(
3028
projectId,
3129
datasetId,
3230
resourceName,
3331
principalId,
34-
role,
35-
}) {
32+
role
33+
) {
3634
// [START bigquery_grant_access_to_table_or_view]
37-
// Uncomment and update these variables:
38-
// const projectId = 'my_project_id';
39-
// const datasetId = 'my_dataset';
40-
// const resourceName = 'my_table';
41-
// const principalId = 'user:[email protected]';
42-
// const role = 'roles/bigquery.dataViewer';
43-
44-
// Create a BigQuery client
45-
const bigquery = new BigQuery();
46-
47-
// Get the dataset and table references
48-
const dataset = bigquery.dataset(datasetId);
49-
const table = dataset.table(resourceName);
35+
// TODO(developer): Update and un-comment below lines
36+
37+
// Google Cloud Platform project.
38+
// projectId = "my_project_id"
39+
40+
// Dataset where the table or view is.
41+
// datasetId = "my_dataset"
42+
43+
// Table or view name to get the access policy.
44+
// resourceName = "my_table"
5045

51-
try {
52-
// Get the IAM access policy for the table or view
53-
const [policy] = await table.iam.getPolicy();
46+
// The principal requesting access to the table or view.
47+
// Find more details about principal identifiers here:
48+
// https://cloud.google.com/iam/docs/principal-identifiers
49+
// principalId = "user:[email protected]"
5450

55-
// Create a new binding for the principal and role
56-
const binding = {
57-
role: role,
58-
members: [principalId],
59-
};
51+
// Role to assign to the member.
52+
// role = "roles/bigquery.dataViewer"
6053

61-
// Add the new binding to the policy
62-
policy.bindings.push(binding);
54+
// Instantiate a client.
55+
const client = new BigQuery();
6356

64-
// Set the updated IAM access policy
65-
const [updatedPolicy] = await table.iam.setPolicy(policy);
57+
// Get the table reference.
58+
const dataset = client.dataset(datasetId);
59+
const table = dataset.table(resourceName);
6660

67-
console.log(
68-
`Role '${role}' granted for principal '${principalId}' on resource '${projectId}.${datasetId}.${resourceName}'.`
69-
);
61+
// Get the IAM access policy for the table or view.
62+
const [policy] = await table.getIamPolicy();
7063

71-
return updatedPolicy.bindings;
72-
} catch (error) {
73-
console.error('Error granting access:', error);
74-
throw error;
64+
// Initialize bindings if they do not exist
65+
if (!policy.bindings) {
66+
policy.bindings = [];
7567
}
68+
69+
// To grant access to a table or view.
70+
// add bindings to the Table or View policy.
71+
//
72+
// Find more details about Policy and Binding objects here:
73+
// https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Policy
74+
// https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Binding
75+
const binding = {
76+
role: role,
77+
members: [principalId],
78+
};
79+
policy.bindings.push(binding);
80+
81+
// Set the IAM access policy with updated bindings
82+
const [updatedPolicy] = await table.setIamPolicy(policy);
83+
84+
// Show a success message.
85+
console.log(
86+
`Role '${role}' granted for principal '${principalId}' on resource '${datasetId}.${resourceName}'.`
87+
);
7688
// [END bigquery_grant_access_to_table_or_view]
89+
90+
return updatedPolicy.bindings;
7791
}
7892

79-
module.exports = {
80-
grantAccessToTableOrView,
81-
};
93+
module.exports = {grantAccessToTableOrView};

bigquery/cloud-client/revokeTableOrViewAccess.js

Lines changed: 87 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -12,94 +12,106 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
const {BigQuery} = require('@google-cloud/bigquery');
16-
17-
// [START bigquery_revoke_access_to_table_or_view]
1815
/**
1916
* Revokes access to a BigQuery table or view
20-
* @param {Object} params - The parameters object
21-
* @param {string} params.projectId - The ID of the Google Cloud project
22-
* @param {string} params.datasetId - The ID of the dataset containing the table/view
23-
* @param {string} params.resourceId - The ID of the table or view
24-
* @param {string} [params.memberToRevoke] - Optional. Specific member to revoke access from (e.g., 'group:[email protected]')
25-
* @param {string} [params.roleToRevoke='roles/bigquery.dataViewer'] - Optional. Specific role to revoke
26-
* @returns {Promise<void>}
17+
* @param {string} projectId - The ID of the Google Cloud project
18+
* @param {string} datasetId - The ID of the dataset containing the table/view
19+
* @param {string} resourceName - The ID of the table or view
20+
* @param {string} [roleToRemove=null] - Optional. Specific role to revoke
21+
* @param {string} [principalToRemove=null] - Optional. Specific principal to revoke access from
22+
* @returns {Promise<Object>} The updated IAM policy
2723
*/
28-
async function revokeTableOrViewAccess({
24+
async function revokeAccessToTableOrView(
2925
projectId,
3026
datasetId,
31-
resourceId,
32-
memberToRevoke,
33-
roleToRevoke = 'roles/bigquery.dataViewer',
34-
}) {
35-
// Validate required parameters
36-
if (!projectId || !datasetId || !resourceId) {
37-
throw new Error(
38-
'projectId, datasetId and resourceID are required parameters'
39-
);
27+
resourceName,
28+
roleToRemove = null,
29+
principalToRemove = null
30+
) {
31+
// [START bigquery_revoke_access_to_table_or_view]
32+
// Imports the Google Cloud client library
33+
const {BigQuery} = require('@google-cloud/bigquery');
34+
35+
// TODO (developer): Update and un-comment below lines
36+
// Google Cloud Platform project.
37+
// projectId = "my_project_id"
38+
39+
// Dataset where the table or view is.
40+
// datasetId = "my_dataset"
41+
42+
// Table or view name to get the access policy.
43+
// resourceName = "my_table"
44+
45+
// (Optional) Role to remove from the table or view.
46+
// roleToRemove = "roles/bigquery.dataViewer"
47+
48+
// (Optional) Principal to remove from the table or view.
49+
// principalToRemove = "user:[email protected]"
50+
51+
// Find more information about roles and principals (refered as members) here:
52+
// https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Binding
53+
54+
// Instantiate a client.
55+
const client = new BigQuery();
56+
57+
// Get the table reference.
58+
const dataset = client.dataset(datasetId);
59+
const table = dataset.table(resourceName);
60+
61+
// Get the IAM access policy for the table or view.
62+
const [policy] = await table.getIamPolicy();
63+
64+
// Initialize bindings of they do not exist
65+
if (!policy.bindings) {
66+
policy.bindings = [];
4067
}
41-
try {
42-
// Create BigQuery client
43-
const bigquery = new BigQuery({
44-
projectId: projectId,
45-
});
46-
47-
// Get reference to the table or view
48-
const dataset = bigquery.dataset(datasetId);
49-
const table = dataset.table(resourceId);
50-
51-
// Get current IAM policy
52-
const [policy] = await table.iam.getPolicy();
53-
console.log(
54-
'Current IAM Policy:',
55-
JSON.stringify(policy.bindings, null, 2)
56-
);
5768

58-
// Filter bindings based on parameters
59-
let newBindings = policy.bindings;
60-
61-
if (memberToRevoke && roleToRevoke) {
62-
// Remove specific member from specific role
63-
newBindings = policy.bindings
64-
.map(binding => ({
65-
...binding,
66-
members:
67-
binding.role === roleToRevoke
68-
? binding.members.filter(member => member !== memberToRevoke)
69-
: binding.members,
70-
}))
71-
.filter(binding => binding.members.length > 0);
72-
} else if (!memberToRevoke && roleToRevoke) {
73-
// Remove all bindings for the specified role
74-
newBindings = policy.bindings.filter(
75-
binding => binding.role !== roleToRevoke
76-
);
77-
} else {
78-
// Keep the current binding as it is
79-
newBindings = policy.bindings;
80-
}
69+
// To revoke access to a table or view,
70+
// remove bindings from the Table or View policy.
71+
//
72+
// Find more details about Policy objects here:
73+
// https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Policy
8174

82-
// Create new policy with updated bindings
83-
const newPolicy = {
84-
bindings: newBindings,
85-
};
75+
if (roleToRemove) {
76+
// Filter out all bindings with the `roleToRemove`
77+
// and assign a new list back to the policy bindings.
78+
policy.bindings = policy.bindings.filter(b => b.role !== roleToRemove);
79+
}
8680

87-
// Set the new IAM policy
88-
await table.iam.setPolicy(newPolicy);
89-
console.log(`Access revoked successfully for ${resourceId}`);
81+
if (principalToRemove) {
82+
// Create a copy to match original code structure.
83+
const bindings = [...policy.bindings];
9084

91-
// Verify the changes
92-
const [updatedPolicy] = await table.iam.getPolicy();
93-
console.log(
94-
'Updated IAM Policy:',
95-
JSON.stringify(updatedPolicy.bindings, null, 2)
85+
// Filter out the principal from each binding.
86+
for (const binding of bindings) {
87+
if (binding.members) {
88+
binding.members = binding.members.filter(m => m !== principalToRemove);
89+
}
90+
}
91+
92+
// Filter out bindings with empty members
93+
policy.bindings = bindings.filter(
94+
binding => binding.members && binding.members.length > 0
9695
);
96+
}
97+
98+
try {
99+
// Set the IAM access policy with updated bindings
100+
await table.setIamPolicy(policy);
101+
102+
// Get the policy again to confirm it's set correctly
103+
const [verifiedPolicy] = await table.getIamPolicy();
104+
105+
if (verifiedPolicy && verifiedPolicy.bindings) {
106+
return verifiedPolicy.bindings;
107+
} else {
108+
return [];
109+
}
97110
} catch (error) {
98-
console.error('Error revoking access:', error);
111+
console.error('Error settings IAM policy:', error);
99112
throw error;
100113
}
114+
// [END bigquery_revoke_access_to_table_or_view]
101115
}
102116

103-
// [END bigquery_revoke_access_to_table_or_view]
104-
105-
module.exports = {revokeTableOrViewAccess};
117+
module.exports = {revokeAccessToTableOrView};

0 commit comments

Comments
 (0)