পরিষেবা অ্যাকাউন্ট

একটি পরিষেবা অ্যাকাউন্ট হল এক ধরনের Google অ্যাকাউন্ট যা একটি অ্যাপ্লিকেশন দ্বারা OAuth 2.0 এর মাধ্যমে প্রোগ্রাম্যাটিকভাবে Google API অ্যাক্সেস করতে ব্যবহার করা যেতে পারে। এর জন্য মানুষের অনুমোদনের প্রয়োজন হয় না কিন্তু পরিবর্তে একটি কী ফাইল ব্যবহার করে যা শুধুমাত্র আপনার অ্যাপ্লিকেশন অ্যাক্সেস করতে পারে।

পরিষেবা অ্যাকাউন্টগুলি সম্পর্কে আরও পড়ার আগে OAuth 2.0 ইনস্টল করা অ্যাপ্লিকেশন ফ্লো বাস্তবায়নের অনেক সহজ, এবং অত্যন্ত প্রস্তাবিত বিকল্প বিবেচনা করুন৷ এই পদ্ধতির জন্য একজন ব্যবহারকারীকে একটি রিফ্রেশ টোকেন তৈরি করার জন্য অ্যাপ্লিকেশনটিকে ম্যানুয়ালি অনুমোদন করতে হবে, তবে এটি শুধুমাত্র একবার করা দরকার কারণ এই টোকেনগুলির মেয়াদ শেষ হয় না।

এখনও পড়ছেন? ঠিক আছে, আপনি নিম্নলিখিত যে কোনও উপায়ে একটি পরিষেবা অ্যাকাউন্ট বাস্তবায়ন করতে পারেন:

  • যদি আপনার ব্যবহারকারীরা বিভিন্ন ডোমেনে থাকেন, তাহলে ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী হিসাবে একটি পরিষেবা অ্যাকাউন্ট ব্যবহার করে প্রয়োগ করুন৷ এটি আপনাকে প্রতিটি অ্যাকাউন্টে একটি নতুন ব্যবহারকারী প্রোফাইল তৈরি করে এবং একটি একক পরিষেবা অ্যাকাউন্টের সাথে সংযুক্ত করে বিভিন্ন সংস্থার মালিকানাধীন একাধিক অ্যাকাউন্টের সাথে সংযোগ করতে সক্ষম করে। ক্যাম্পেইন ম্যানেজার 360 এর সাথে পরিষেবা অ্যাকাউন্টগুলি ব্যবহার করার জন্য এটি পছন্দের উপায়।
  • যদি আপনার ব্যবহারকারীরা আপনার মালিকানাধীন একটি একক ডোমেনে থাকেন, তাহলে ডোমেন-ব্যাপী প্রতিনিধিত্ব বাস্তবায়ন করুন। এই ক্ষেত্রে আপনার অবশ্যই G Suite- এর সাথে নিবন্ধিত একটি ডোমেনে প্রশাসকের অ্যাক্সেস থাকতে হবে। G Suite এবং/অথবা ডোমেন কনফিগারেশনে সাহায্যের জন্য G Suite সমর্থন পৃষ্ঠাটি দেখুন।

পূর্বশর্ত

ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী হিসাবে একটি পরিষেবা অ্যাকাউন্ট বাস্তবায়ন করতে, ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী ট্যাব নির্বাচন করুন। ডোমেইন-ওয়াইড ডেলিগেশন বাস্তবায়ন করতে, নিচের ডেলিগেশন ট্যাবটি নির্বাচন করুন।

ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী

API অ্যাক্সেস সক্ষম সহ একটি ক্যাম্পেইন ম্যানেজার 360 অ্যাকাউন্টে আপনার অ্যাক্সেস থাকতে হবে।

প্রতিনিধি দল
  1. API অ্যাক্সেস সক্ষম সহ একটি ক্যাম্পেইন ম্যানেজার 360 অ্যাকাউন্টে আপনার অ্যাক্সেস থাকতে হবে।
  2. আপনার অবশ্যই G Suite- এর সাথে নিবন্ধিত একটি ডোমেনে প্রশাসকের অ্যাক্সেস থাকতে হবে।
  3. আপনার একটি ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী প্রোফাইল আপনার G Suite-রেজিস্টার করা ডোমেনের অধীনে এক বা একাধিক অ্যাকাউন্টের সাথে লিঙ্ক করা থাকতে হবে। অন্যান্য ডোমেনের অধীনে অ্যাকাউন্টগুলির সাথে লিঙ্কযুক্ত ব্যবহারকারীর প্রোফাইলগুলি, উদাহরণস্বরূপ, gmail.com ব্যবহার করা যাবে না৷

একটি পরিষেবা অ্যাকাউন্ট কনফিগার করা এবং ব্যবহার করা

ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী হিসাবে একটি পরিষেবা অ্যাকাউন্ট ব্যবহার করে বাস্তবায়ন করতে, ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী ট্যাব নির্বাচন করুন। ডোমেইন-ওয়াইড ডেলিগেশন বাস্তবায়ন করতে, নিচের ডেলিগেশন ট্যাবটি নির্বাচন করুন।

ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারী
  1. Google API কনসোলে একটি পরিষেবা অ্যাকাউন্ট কী তৈরি করুন৷

    সতর্কতা: মূল ফাইলটি রক্ষা করা গুরুত্বপূর্ণ যা Google পরিষেবাগুলিতে একটি পরিষেবা অ্যাকাউন্ট অ্যাক্সেস দেয় যার জন্য এটি অনুমোদিত হয়েছে৷
  2. পূর্ববর্তী ধাপে প্রাপ্ত পরিষেবা অ্যাকাউন্ট ইমেলের সাথে ক্যাম্পেইন ম্যানেজার 360 ব্যবহারকারীর প্রোফাইল যুক্ত করুন যেমন ব্যবহারকারীর অ্যাক্সেস পরিচালনা সহায়তা কেন্দ্র নিবন্ধে বর্ণিত হয়েছে৷
  3. আপনার নতুন তৈরি পরিষেবা অ্যাকাউন্ট ব্যবহার করে আপনার অ্যাপ্লিকেশনে সার্ভার-টু-সার্ভার OAuth 2.0 ফ্লো প্রয়োগ করুন। আরও তথ্যের জন্য, উদাহরণ বিভাগ দেখুন।
প্রতিনিধি দল
  1. Google API কনসোলে একটি পরিষেবা অ্যাকাউন্ট কী তৈরি করুন৷

    সতর্কতা: মূল ফাইলটি রক্ষা করা গুরুত্বপূর্ণ যা Google পরিষেবাগুলিতে একটি পরিষেবা অ্যাকাউন্ট অ্যাক্সেস দেয় যার জন্য এটি অনুমোদিত হয়েছে৷ G Suite-এর ডোমেন-লেভেল কন্ট্রোলের কারণে এটি ডোমেন-ওয়াইড ডেলিগেশন প্রবাহের ক্ষেত্রে বিশেষভাবে সত্য যা পরিষেবা অ্যাকাউন্টকে ডোমেনের যেকোনো ব্যবহারকারীর ছদ্মবেশী করার ক্ষমতা দেয়। পরিষেবা অ্যাকাউন্টগুলিকে শুধুমাত্র একটি Google API অ্যাক্সেস করার অনুমতি দেওয়াও ভাল অনুশীলন (পরবর্তী ধাপে বর্ণিত "স্কোপ" ক্ষেত্র ব্যবহার করে)। এটি একটি প্রতিরোধমূলক ব্যবস্থা যা একটি পরিষেবা অ্যাকাউন্টের কী ফাইলের সাথে আপস করা হলে আক্রমণকারী যে পরিমাণ ডেটা অ্যাক্সেস করতে পারে তা হ্রাস করার জন্য।
  2. আপনার ডোমেনের মধ্যে ব্যবহারকারীদের ছদ্মবেশী করার অনুমতি দেওয়ার জন্য এই পরিষেবা অ্যাকাউন্টে ডোমেন-ব্যাপী কর্তৃত্ব অর্পণ করুন৷ অনুরোধ করা হলে, নিম্নলিখিত API স্কোপগুলি প্রদান করুন:
    ব্যাপ্তি অর্থ
    https://www.googleapis.com/auth/dfatrafficking ক্যাম্পেইন ম্যানেজার 360 পাচারের অ্যাক্সেস পড়ুন/লিখুন।
    https://www.googleapis.com/auth/dfareporting ক্যাম্পেইন ম্যানেজার 360 রিপোর্টিং পড়ুন/লিখুন।
    https://www.googleapis.com/auth/ddmconversions ক্যাম্পেইন ম্যানেজার 360 অফলাইন রূপান্তরগুলি পড়ুন/লিখুন।
  3. আপনার নতুন তৈরি পরিষেবা অ্যাকাউন্ট ব্যবহার করে আপনার অ্যাপ্লিকেশনে সার্ভার-টু-সার্ভার OAuth 2.0 ফ্লো প্রয়োগ করুন। আরও তথ্যের জন্য, উদাহরণ বিভাগ দেখুন। মনে রাখবেন যে ছদ্মবেশী করার জন্য আপনাকে একটি অ্যাকাউন্ট সরবরাহ করতে হবে এবং এটি অবশ্যই সেই ডোমেনের অন্তর্গত হতে হবে যার জন্য আপনার পরিষেবা অ্যাকাউন্টটি পূর্ববর্তী ধাপে ডোমেন-ব্যাপী কর্তৃপক্ষকে অর্পণ করা হয়েছিল৷

G Suite এবং/অথবা ডোমেন কনফিগারেশনে সাহায্যের জন্য G Suite সমর্থন পৃষ্ঠাটি দেখুন।

উদাহরণ

সি#

/*
 * Copyright 2015 Google Inc
 *
 * 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.
*/

using Google.Apis.Auth.OAuth2;
using Google.Apis.Dfareporting.v4;
using Google.Apis.Dfareporting.v4.Data;
using Google.Apis.Json;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;

namespace DfaReporting.Samples {
  /// <summary>
  /// This example demonstrates how to authenticate and make a basic request using a service
  /// account.
  /// </summary>
  class AuthenticateUsingServiceAccount : SampleBase {
    /// <summary>
    /// The OAuth 2.0 scopes to request.
    /// </summary>
    private static readonly IEnumerable<string> OAuthScopes = new[] {
      DfareportingService.Scope.Dfareporting
    };

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This example demonstrates how to authenticate and make a basic request" +
               " using a service account.\n";
      }
    }

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      SampleBase codeExample = new AuthenticateUsingServiceAccount();
      Console.WriteLine(codeExample.Description);
      codeExample.Run(null);
    }

    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="service">Unused</param>
    public override void Run(DfareportingService service) {
      string pathToJsonFile = _T("ENTER_PATH_TO_JSON_FILE_HERE");

      // An optional Google account email to impersonate. Only applicable to service accounts which
      // have enabled domain-wide delegation and wish to make API requests on behalf of an account
      // within their domain. Setting this field will not allow you to impersonate a user from a
      // domain you don't own (e.g., gmail.com).
      string emailToImpersonate = _T("");

      // Build service account credential.
      ServiceAccountCredential credential =
          getServiceAccountCredential(pathToJsonFile, emailToImpersonate);

      // Create a Dfareporting service object.
      //
      // Note: application name should be replaced with a value that identifies your application.
      service = new DfareportingService(
          new BaseClientService.Initializer {
            HttpClientInitializer = credential,
            ApplicationName = "C# service account sample"
          }
      );

      // Retrieve and print all user profiles for the current authorized user.
      UserProfileList profiles = service.UserProfiles.List().Execute();

      foreach (UserProfile profile in profiles.Items) {
        Console.WriteLine("Found user profile with ID {0} and name \"{1}\".",
            profile.ProfileId, profile.UserName);
      }
    }

    private ServiceAccountCredential getServiceAccountCredential(String pathToJsonFile,
        String emailToImpersonate) {
      // Load and deserialize credential parameters from the specified JSON file.
      JsonCredentialParameters parameters;
      using (Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) {
        parameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(json);
      }

      // Create a credential initializer with the correct scopes.
      ServiceAccountCredential.Initializer initializer =
          new ServiceAccountCredential.Initializer(parameters.ClientEmail) {
            Scopes = OAuthScopes
          };

      // Configure impersonation (if applicable).
      if (!String.IsNullOrEmpty(emailToImpersonate)) {
        initializer.User = emailToImpersonate;
      }

      // Create a service account credential object using the deserialized private key.
      ServiceAccountCredential credential =
          new ServiceAccountCredential(initializer.FromPrivateKey(parameters.PrivateKey));

      return credential;
    }
  }
}

জাভা

// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.services.samples.dfareporting.auth;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.dfareporting.Dfareporting;
import com.google.api.services.dfareporting.DfareportingScopes;
import com.google.api.services.dfareporting.model.UserProfileList;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import java.io.FileInputStream;

/**
 * This example demonstrates how to authenticate and make a basic request using a service account.
 */
public class AuthenticateUsingServiceAccount {
  private static final String PATH_TO_JSON_FILE = "ENTER_PATH_TO_JSON_FILE_HERE";

  /**
   * An optional Google account email to impersonate. Only applicable to service accounts which have
   * enabled domain-wide delegation and wish to make API requests on behalf of an account within
   * their domain. Setting this field will not allow you to impersonate a user from a domain you
   * don't own (e.g., gmail.com).
   */
  private static final String EMAIL_TO_IMPERSONATE = "";

  // The OAuth 2.0 scopes to request.
  private static final ImmutableSet<String> OAUTH_SCOPES =
      ImmutableSet.of(DfareportingScopes.DFAREPORTING);

  private static Credential getServiceAccountCredential(
      String pathToJsonFile, String emailToImpersonate) throws Exception {
    // Generate a credential object from the specified JSON file.
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(pathToJsonFile));

    // Update the credential object with appropriate scopes and impersonation info (if applicable).
    if (Strings.isNullOrEmpty(emailToImpersonate)) {
      credential = credential.createScoped(OAUTH_SCOPES);
    } else {
      credential =
          new GoogleCredential.Builder()
              .setTransport(credential.getTransport())
              .setJsonFactory(credential.getJsonFactory())
              .setServiceAccountId(credential.getServiceAccountId())
              .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
              .setServiceAccountScopes(OAUTH_SCOPES)
              // Set the email of the user you are impersonating (this can be yourself).
              .setServiceAccountUser(emailToImpersonate)
              .build();
    }

    return credential;
  }

  public static void runExample(Dfareporting reporting) throws Exception {
    // Retrieve and print all user profiles for the current authorized user.
    UserProfileList profiles = reporting.userProfiles().list().execute();
    for (int i = 0; i < profiles.getItems().size(); i++) {
      System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName());
    }
  }

  public static void main(String[] args) throws Exception {
    // Build service account credential.
    Credential credential = getServiceAccountCredential(PATH_TO_JSON_FILE, EMAIL_TO_IMPERSONATE);

    // Create a Dfareporting client instance.
    //
    // Note: application name below should be replaced with a value that identifies your
    // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion".
    Dfareporting reporting =
        new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("dfareporting-java-service-acct-sample")
            .build();

    runExample(reporting);
  }
}

পিএইচপি

<?php
/*
 * Copyright 2017 Google Inc.
 *
 * 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.
 */

require_once dirname(__DIR__) . '/vendor/autoload.php';

/**
 * This example demonstrates how to authenticate and make a basic request using
 * a service account.
 *
 * This example is written to be run as a command line application, not as a
 * webpage. An optional Google account email to impersonate may be specified as
 * follows:
 *
 *     AuthenticateUsingServiceAccount.php /path/to/client_secrets.json <email>
 *
 * This optional flag only applies to service accounts which have domain-wide
 * delegation enabled and wish to make API requests on behalf of an account
 * within that domain. Using this flag will not allow you to impersonate a user
 * from a domain that you don't own (e.g., gmail.com).
 */
class AuthenticateUsingServiceAccount
{
    // The OAuth 2.0 scopes to request.
    private static $OAUTH_SCOPES = [
        Google_Service_Dfareporting::DFAREPORTING
    ];

    public function run($pathToJsonFile, $email = null)
    {
        // Create an authenticated client object.
        $client = $this->createAuthenticatedClient($pathToJsonFile, $email);

        // Create a Dfareporting service object.
        $service = new Google_Service_Dfareporting($client);

        $this->getUserProfiles($service);
    }

    private function createAuthenticatedClient($pathToJsonFile, $email)
    {
        // Create a Google_Client instance.
        //
        // Note: application name should be replaced with a value that identifies
        // your application. Suggested format is "MyCompany-ProductName".
        $client = new Google_Client();
        $client->setApplicationName('PHP service account sample');
        $client->setScopes(self::$OAUTH_SCOPES);

        // Load the service account credentials.
        $client->setAuthConfig($pathToJsonFile);

        // Configure impersonation (if applicable).
        if (!is_null($email)) {
            $client->setSubject($email);
        }

        return $client;
    }

    private function getUserProfiles($service)
    {
        // Retrieve and print all user profiles for the current authorized user.
        $result = $service->userProfiles->listUserProfiles();
        foreach ($result['items'] as $userProfile) {
            printf(
                "User profile \"%s\" (ID: %d) found for account %d.\n",
                $userProfile->getUserName(),
                $userProfile->getProfileId(),
                $userProfile->getAccountId()
            );
        }
    }
}

if ($argc < 2 || $argc >= 4) {
    printf(
        "Usage: %s /path/to/client_secrets.json [email_to_impersonate]\n",
        $argv[0]
    );
} else {
    $sample = new AuthenticateUsingServiceAccount();

    if ($argc == 2) {
        $sample->run($argv[1]);
    } else {
        $sample->run($argv[1], $argv[2]);
    }
}

পাইথন

#!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This example demonstrates how to authenticate using a service account.

An optional Google account email to impersonate may be specified as follows:
    authenticate_using_service_account.py <path_to_json_file> -i <email>

This optional flag only applies to service accounts which have domain-wide
delegation enabled and wish to make API requests on behalf of an account
within that domain. Using this flag will not allow you to impersonate a
user from a domain you don't own (e.g., gmail.com).
"""

import argparse
import sys

from googleapiclient import discovery
import httplib2
from oauth2client import client
from oauth2client import tools
from oauth2client.service_account import ServiceAccountCredentials

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
    'path_to_service_account_json_file',
    help='Path to the service account JSON file to use for authenticating.')
argparser.add_argument(
    '-i',
    '--impersonation_email',
    help='Google account email to impersonate.')

# The OAuth 2.0 scopes to request.
OAUTH_SCOPES = ['https://www.googleapis.com/auth/dfareporting']


def main(argv):
  # Retrieve command line arguments.
  parser = argparse.ArgumentParser(
      description=__doc__,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser, argparser])
  flags = parser.parse_args(argv[1:])

  # Authenticate using the supplied service account credentials
  http = authenticate_using_service_account(
      flags.path_to_service_account_json_file,
      flags.impersonation_email)

  # Construct a service object via the discovery service.
  service = discovery.build('dfareporting', 'v4', http=http)

  try:
    # Construct the request.
    request = service.userProfiles().list()

    # Execute request and print response.
    response = request.execute()

    for profile in response['items']:
      print('Found user profile with ID %s and user name "%s".' %
            (profile['profileId'], profile['userName']))

  except client.AccessTokenRefreshError:
    print('The credentials have been revoked or expired, please re-run the '
          'application to re-authorize')


def authenticate_using_service_account(path_to_service_account_json_file,
                                       impersonation_email):
  """Authorizes an httplib2.Http instance using service account credentials."""
  # Load the service account credentials from the specified JSON keyfile.
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      path_to_service_account_json_file,
      scopes=OAUTH_SCOPES)

  # Configure impersonation (if applicable).
  if impersonation_email:
    credentials = credentials.create_delegated(impersonation_email)

  # Use the credentials to authorize an httplib2.Http instance.
  http = credentials.authorize(httplib2.Http())

  return http


if __name__ == '__main__':
  main(sys.argv)

রুবি

#!/usr/bin/env ruby

#
# Copyright:: Copyright 2016, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# This example demonstrates how to authenticate using a service account.
#
# An optional Google account email to impersonate may be specified as follows:
#    authenticate_using_service_account.rb <path_to_json_file> --i <email>
#
# This optional flag only applies to service accounts which have domain-wide
# delegation enabled and wish to make API requests on behalf of an account
# within that domain. Using this flag will not allow you to impersonate a
# user from a domain you don't own (e.g., gmail.com).

require 'google/apis/dfareporting_v4'
require 'googleauth'
require 'optparse'

API_NAMESPACE = Google::Apis::DfareportingV4

def authenticate_using_service_account(path_to_json_file, impersonation_email)
  # Create a Dfareporting service object.
  #
  # Note: application name should be replaced with a value that identifies
  # your application. Suggested format is "MyCompany-ProductName".
  service = API_NAMESPACE::DfareportingService.new
  service.client_options.application_name = 'Ruby service account sample'
  service.client_options.application_version = '1.0.0'

  # Generate an authorization object from the specified JSON file.
  File.open(path_to_json_file, 'r+') do |json|
    service.authorization =
      Google::Auth::ServiceAccountCredentials.make_creds(
        json_key_io: json,
        scope: [API_NAMESPACE::AUTH_DFAREPORTING]
      )
  end

  # Configure impersonation (if applicable).
  service.authorization.sub = impersonation_email unless
    impersonation_email.nil?

  service
end

def get_userprofiles(service)
  # Get all user profiles.
  result = service.list_user_profiles

  # Display results.
  result.items.each do |profile|
    puts format(
      'User profile with ID %d and name "%s" was found for account %d.',
      profile.profile_id, profile.user_name, profile.account_id
    )
  end
end

if $PROGRAM_NAME == __FILE__
  # Retrieve command line arguments.
  impersonation_email = nil
  optparse = OptionParser.new do |opts|
    opts.banner = format('Usage: %s path_to_json_file [options]', $PROGRAM_NAME)
    opts.on_tail('-i', '--impersonate EMAIL',
      'Google account email to impersonate') do |email|
      impersonation_email = email
    end
  end
  optparse.parse!

  if ARGV.empty?
    puts optparse
    exit(-1)
  end

  # Authenticate and initialize API service using service account.
  service = authenticate_using_service_account(ARGV.shift, impersonation_email)

  get_userprofiles(service)
end