Methods

getPolicy

getPolicy(options, callback) returns Promise containing GetPolicyResponse

Get the IAM policy.

Parameter

options

Optional

GetPolicyRequest

Request options.

callback

Optional

GetPolicyCallback

Callback function.

See also

Buckets: setIamPolicy API Documentation

Returns

Promise containing GetPolicyResponse 

Example

var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('my-bucket');
bucket.iam.getPolicy(function(err, policy, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.iam.getPolicy().then(function(data) {
  var policy = data[0];
  var apiResponse = data[1];
});

Example of retrieving a bucket's IAM policy:

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Gets and displays the bucket's IAM policy
storage
  .bucket(bucketName)
  .iam.getPolicy()
  .then(results => {
    const policy = results[0].bindings;

    // Displays the roles in the bucket's IAM policy
    console.log(`Roles for bucket ${bucketName}:`);
    policy.forEach(role => {
      console.log(`  Role: ${role.role}`);
      console.log(`  Members:`);

      const members = role.members;
      members.forEach(member => {
        console.log(`    ${member}`);
      });
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

setPolicy

setPolicy(policy, options, callback) returns Promise containing SetPolicyResponse

Set the IAM policy.

Parameter

policy

object

The policy.

Values in policy have the following properties:

Parameter

bindings

array

Bindings associate members with roles.

etag

Optional

string

Etags are used to perform a read-modify-write.

options

Optional

object

Configuration opbject.

Values in options have the following properties:

Parameter

userProject

Optional

string

The ID of the project which will be billed for the request.

callback

SetPolicyCallback

Callback function.

See also

Buckets: setIamPolicy API Documentation

IAM Roles

Throws

Error 

If no policy is provided.

Returns

Promise containing SetPolicyResponse 

Example

var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('my-bucket');

var myPolicy = {
  bindings: [
    {
      role: 'roles/storage.admin',
      members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com']
    }
  ]
};

bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.iam.setPolicy(myPolicy).then(function(data) {
  var policy = data[0];
  var apiResponse = data[1];
});

Example of adding to a bucket's IAM policy:

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];

// Creates a client
const storage = new Storage();

// Get a reference to a Google Cloud Storage bucket
const bucket = storage.bucket(bucketName);

// Gets and updates the bucket's IAM policy
bucket.iam
  .getPolicy()
  .then(results => {
    const policy = results[0];

    // Adds the new roles to the bucket's IAM policy
    policy.bindings.push({
      role: roleName,
      members: members,
    });

    // Updates the bucket's IAM policy
    return bucket.iam.setPolicy(policy);
  })
  .then(() => {
    console.log(
      `Added the following member(s) with role ${roleName} to ${bucketName}:`
    );
    members.forEach(member => {
      console.log(`  ${member}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of removing from a bucket's IAM policy:

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];

// Creates a client
const storage = new Storage();

// Get a reference to a Google Cloud Storage bucket
const bucket = storage.bucket(bucketName);

// Gets and updates the bucket's IAM policy
bucket.iam
  .getPolicy()
  .then(data => {
    const policy = data[0];

    // Finds and updates the appropriate role-member group
    const index = policy.bindings.findIndex(role => role.role === roleName);
    let role = policy.bindings[index];
    if (role) {
      role.members = role.members.filter(
        member => members.indexOf(member) === -1
      );

      // Updates the policy object with the new (or empty) role-member group
      if (role.members.length === 0) {
        policy.bindings.splice(index, 1);
      } else {
        policy.bindings.index = role;
      }

      // Updates the bucket's IAM policy
      return bucket.iam.setPolicy(policy);
    } else {
      // No matching role-member group(s) were found
      throw new Error('No matching role-member group(s) found.');
    }
  })
  .then(() => {
    console.log(
      `Removed the following member(s) with role ${roleName} from ${bucketName}:`
    );
    members.forEach(member => {
      console.log(`  ${member}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

testPermissions

testPermissions(permissions, options, callback) returns Promise containing TestIamPermissionsResponse

Test a set of permissions for a resource.

Parameter

permissions

(string or Array of string)

The permission(s) to test for.

options

Optional

object

Configuration object.

Values in options have the following properties:

Parameter

userProject

Optional

string

The ID of the project which will be billed for the request.

callback

Optional

TestIamPermissionsCallback

Callback function.

See also

Buckets: testIamPermissions API Documentation

Throws

Error 

If permissions are not provided.

Returns

Promise containing TestIamPermissionsResponse 

Example

var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('my-bucket');

//-
// Test a single permission.
//-
var test = 'storage.buckets.delete';

bucket.iam.testPermissions(test, function(err, permissions, apiResponse) {
  console.log(permissions);
  // {
  //   "storage.buckets.delete": true
  // }
});

//-
// Test several permissions at once.
//-
var tests = [
  'storage.buckets.delete',
  'storage.buckets.get'
];

bucket.iam.testPermissions(tests, function(err, permissions) {
  console.log(permissions);
  // {
  //   "storage.buckets.delete": false,
  //   "storage.buckets.get": true
  // }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.iam.testPermissions(test).then(function(data) {
  var permissions = data[0];
  var apiResponse = data[1];
});