def main(argv):
  """A script to test Apps Security APIs: summarizing oauth2 tokens."""
  flags = common_flags.ParseFlags(argv,
                                  'Gather token status for entire domain.',
                                  AddFlags)
  # Tracks stats for each domain-scope:
  # {
  #   (scope1, domain1): [user1, user2, ...],
  #   (scope2, domain1): [user1, user3, ...],
  #   (scope1, domain2): [user4, user5, ...],
  #   (scope3, domain3): [user6, user7, ...],
  # }
  # Issue domains (e.g.twitter.com) are the domains to whom the token was
  # issued and scopes reflect the data accessed.
  #
  # This is simple to minimize memory footprint.  Later processing of this data
  # structure will report most frequent: issue domains, scopes and users.
  token_stats = {}

  if not flags.resume:
    # Early check if file exists and not --force.
    filename_path = token_report_utils.WriteTokensIssuedJson(token_stats,
                                                             flags.force)
  else:
    token_stats = token_report_utils.GetTokenStats()

  http = auth_helper.GetAuthorizedHttp(flags)
  apps_security_api = tokens_api.TokensApiWrapper(http)

  iterator_purpose = 'collection'  # Used to tag iterator progress data.

  # The user list holds a tuple for each user of: email, id, full_name
  # (e.g. 'larry', '112351558298938768732', 'Larry Summon').
  print 'Scanning domain users for %s' % iterator_purpose
  for user in user_iterator.StartUserIterator(http, iterator_purpose, flags):
    user_email, user_id, checkpoint = user
    try:
      token_list = apps_security_api.GetTokensForUser(user_id)
    except admin_api_tool_errors.AdminAPIToolTokenRequestError as e:
      # This suggests an unexpected response from the apps security api.
      # As much detail as possible is provided by the raiser.
      sys.stdout.write('%80s\r' % '')  # Clear the previous entry.
      sys.stdout.flush()
      log_utils.LogError('Unable to get user tokens.', e)
      sys.exit(1)

    for token in token_list:
      # Save lists of users with tokens.
      for scope in token['scopes']:
        stat_key = token_report_utils.PackStatKey(token['clientId'], scope)
        token_stats.setdefault(stat_key, [])
        token_stats[stat_key].append(user_email)

    if checkpoint:
      # Save progress every n users.
      filename_path = token_report_utils.WriteTokensIssuedJson(
          token_stats, overwrite_ok=True)
  print 'Token report written: %s' % filename_path
def main(argv):
    """A script to test Apps Security APIs: revoking oauth2 tokens."""
    flags = common_flags.ParseFlags(argv,
                                    'Revoke tokens issued for a client id.',
                                    AddFlags)
    log_border = (40 * '-')
    log_utils.LogInfo('revoke_tokens_for_domain_clientid starting...\n%s' %
                      log_border)

    if flags.use_local_token_stats:
        stats_user_list = token_report_utils.GetUsersInDomain(
            token_report_utils.GetTokenStats(), flags.client_id)
    else:
        stats_user_list = []  # List of users with a token for an issue domain

    http = auth_helper.GetAuthorizedHttp(flags)
    apps_security_api = tokens_api.TokensApiWrapper(http)

    # The user list holds a tuple for each user of: email, id, full_name
    # (e.g. '*****@*****.**', '000000000098938768732', 'Larry Summon').
    print 'Scanning domain users for %s...' % PREFIX
    for user in user_iterator.StartUserIterator(http, PREFIX, flags):
        user_email, _, _ = user
        # Skip revocation attempts if tokens not found in the latest report.
        if flags.use_local_token_stats and user_email not in stats_user_list:
            continue

        try:
            # NOTE: attempting to revoke a non-existent token causes no
            #       discernible output (no failure message or fail status).
            apps_security_api.DeleteToken(user_email, flags.client_id)
        except admin_api_tool_errors.AdminAPIToolTokenRequestError as e:
            # This suggests an unexpected response from the apps security api.
            # As much detail as possible is provided by the raiser.
            sys.stdout.write('%80s\r' % '')  # Clear the previous entry.
            sys.stdout.flush()
            log_utils.LogError(
                'Unable to revoke token for user %s and client_id %s.' %
                (user, flags.client_id), e)
            sys.exit(1)
        # If attempting to revoke tokens for the whole domain, do not print
        # confirmation because we're not sure which users actually had the tokens.
        if flags.use_local_token_stats:
            log_utils.LogInfo(
                'Successfully revoked token for user %s for client_id %s.' %
                (user_email, flags.client_id))
    log_utils.LogInfo('revoke_tokens_for_domain_clientid done.\n%s' %
                      log_border)
    print 'Revocation details logged to: %s.' % log_utils.GetLogFileName()
    if not flags.use_local_token_stats:
        print 'NOTE: To save time, revocation is attempted for all domain users '
        print '      without checking in advance if a token was granted.  Because '
        print '      revocation returns no indication of actual token revocation, '
        print '      the actual clients of tokens revoked are not logged. If it '
        print '      is required to log the actual client ids of revoked tokens, '
        print '      run the gather token stats command and use '
        print '      --use_local_token_stats with this command. '
def main(argv):
  """Retrieve and print the customer_id for a given apps domain."""
  flags = common_flags.ParseFlags(argv, 'List the Google Apps Customer ID.',
                                  AddFlags)
  http = auth_helper.GetAuthorizedHttp(flags)
  api_wrapper = users_api.UsersApiWrapper(http)
  try:
    api_wrapper.PrintCustomerId(flags.apps_domain)
  except admin_api_tool_errors.AdminAPIToolUserError as e:
    log_utils.LogError('Unable to enumerate one user.', e)
    sys.exit(1)
Example #4
0
def main(argv):
  """A script to test Apps Security APIs: summarizing oauth2 tokens."""
  flags = common_flags.ParseFlags(argv,
                                  'Create report of domain token info.',
                                  AddFlags)
  if flags.show_users:
    flags.long_list = True
  client_id_summary, scope_summary = token_report_utils.SummarizeTokenStats(
      token_report_utils.GetTokenStats())
  ReportCommonClientIDs(client_id_summary, flags)
  ReportCommonScopes(scope_summary, flags)
Example #5
0
def main(argv):
  """A script to test Admin SDK Directory APIs: delete."""
  flags = common_flags.ParseFlags(argv, 'Remove a domain user.', AddFlags)
  http = auth_helper.GetAuthorizedHttp(flags)
  api_wrapper = users_api.UsersApiWrapper(http)
  try:
    api_wrapper.DeleteDomainUser(flags.user_email)
  except admin_api_tool_errors.AdminAPIToolUserError as e:
    log_utils.LogError('Unable to rm user %s.' % flags.user_email, e)
    sys.exit(1)
  log_utils.LogInfo('User %s successfully removed.' % flags.user_email)
Example #6
0
def main(argv):
    """A script to test Admin SDK Directory APIs."""
    flags = common_flags.ParseFlags(argv, 'Add a domain user.', AddFlags)
    http = auth_helper.GetAuthorizedHttp(flags)
    api_wrapper = users_api.UsersApiWrapper(http)
    try:
        api_wrapper.AddDomainUser(flags.first_name, flags.last_name,
                                  flags.user_email, flags.password)
    except admin_api_tool_errors.AdminAPIToolUserError as e:
        # Could not add user. Details provided by api wrapper in the e string.
        log_utils.LogError('Unable to add user %s.' % flags.user_email, e)
        sys.exit(1)
    log_utils.LogInfo('User %s added.' % flags.user_email)
def main(argv):
    """Run report_users, parse and print a summary of its results."""
    flags = common_flags.ParseFlags(argv, 'Create a report of org counts.',
                                    AddFlags)
    if flags.csv:
        FILE_MANAGER.ExitIfCannotOverwriteFile(
            _REPORT_ORGS_BY_ACTIVE_FILE_NAME, overwrite_ok=flags.force)
        FILE_MANAGER.ExitIfCannotOverwriteFile(_REPORT_ORGS_BY_OU_FILE_NAME,
                                               overwrite_ok=flags.force)
    GenerateUserReport(flags)
    orgs_by_active, orgs_by_ou = SummarizeUserOrgReport()
    PrintOrgCounts(orgs_by_active, orgs_by_ou)
    if flags.csv:
        WriteOrgCounts(orgs_by_active, orgs_by_ou, flags)
Example #8
0
def main(argv):
  """Run report_users, parse and print a summary of its results."""
  flags = common_flags.ParseFlags(argv,
                                  'Create report of domain Google+ user info.',
                                  AddFlags)
  if flags.create_state_report_csv:
    FILE_MANAGER.ExitIfCannotOverwriteFile(
        _REPORT_USERS_PROFILE_STATE_FILE_NAME, overwrite_ok=flags.force)
  if not flags.use_local_profile_data:
    _GatherProfileStatus(flags)
  user_count, profile_count, domain_profile_status = _SummarizeProfileStatus()
  _PrintProfileReport(user_count, profile_count, domain_profile_status, flags)
  if flags.create_state_report_csv:
    _WriteUserProfileState(domain_profile_status, flags)
Example #9
0
def main(argv):
    """A script to test Admin SDK Directory APIs: ls (show) user."""
    flags = common_flags.ParseFlags(argv, 'List info about a domain user.',
                                    AddFlags)
    http = auth_helper.GetAuthorizedHttp(flags)
    if flags.plus_domains:
        user_api = people_api.PlusDomains(http)
    else:
        user_api = users_api.UsersApiWrapper(http)
    try:
        user_api.PrintDomainUser(flags.user_email, flags.long_list)
    except admin_api_tool_errors.AdminAPIToolUserError as e:
        # Could not ls user. Details provided by api wrapper in the e string.
        log_utils.LogError('Unable to locate user %s.' % flags.user_email, e)
        sys.exit(1)
def main(argv):
    """A script to test Apps Security APIs."""
    flags = common_flags.ParseFlags(
        argv, 'List token info about a user and client.', AddFlags)
    http = auth_helper.GetAuthorizedHttp(flags)
    user_api = users_api.UsersApiWrapper(http)
    if not user_api.IsDomainUser(flags.user_email):
        print 'User %s not found.' % flags.user_email
        sys.exit(1)
    apps_security_api = tokens_api.TokensApiWrapper(http)
    try:
        apps_security_api.PrintTokenForUserClientId(flags.user_email,
                                                    flags.client_id,
                                                    flags.long_list)
    except admin_api_tool_errors.AdminAPIToolTokenRequestError as e:
        log_utils.LogError(
            'Unable to retrieve tokens for user %s.' % flags.user_email, e)
        sys.exit(1)
def main(argv):
    """A script to test Apps Security APIs."""
    flags = common_flags.ParseFlags(argv,
                                    'List token info about a domain user.',
                                    AddFlags)
    http = auth_helper.GetAuthorizedHttp(flags)
    user_api = users_api.UsersApiWrapper(http)
    if not user_api.IsDomainUser(flags.user_email):
        print 'User %s not found.' % flags.user_email
        sys.exit(1)

    apps_security_api = tokens_api.TokensApiWrapper(http)
    try:
        apps_security_api.PrintTokensForUser(flags.user_email, flags.long_list)
    except admin_api_tool_errors.AdminAPIToolTokenRequestError as e:
        # This suggests an unexpected response from the apps security api.
        # As much detail as possible is provided by the raiser.
        log_utils.LogError(
            'Unable to retrieve tokens for user %s.' % flags.user_email, e)
        sys.exit(1)
Example #12
0
def main(argv):
    """Produce a user report with contents stipulated by flags."""
    flags = common_flags.ParseFlags(argv,
                                    'Create a report of domain user info.',
                                    AddFlags)
    FILE_MANAGER.ExitIfCannotOverwriteFile(flags.output_file,
                                           overwrite_ok=flags.force)
    http = auth_helper.GetAuthorizedHttp(flags)
    api_wrapper = users_api.UsersApiWrapper(http)

    max_results = flags.first_n if flags.first_n > 0 else None
    try:
        user_list = api_wrapper.GetDomainUsers(flags.apps_domain,
                                               basic=False,
                                               max_results=max_results,
                                               query_filter=flags.query_filter)
    except admin_api_tool_errors.AdminAPIToolUserError as e:
        log_utils.LogError(
            'Unable to enumerate users from domain %s.' % flags.apps_domain, e)
        sys.exit(1)

    ReportDomainUsers(user_list, flags)
Example #13
0
def main(argv):
    """Save the domain to a file to avoid constantly passing a flag."""
    flags = common_flags.ParseFlags(argv,
                                    'Save default domain for all commands.',
                                    AddFlags)

    # Fail if the defaults file exists. Better than waiting for write to check.
    FILE_MANAGER.ExitIfCannotOverwriteFile(
        FILE_MANAGER.DEFAULT_DOMAIN_FILE_NAME,
        work_dir=False,
        overwrite_ok=flags.force)
    http = auth_helper.GetAuthorizedHttp(flags)
    api_wrapper = users_api.UsersApiWrapper(http)
    try:
        customer_id = api_wrapper.GetCustomerId(flags.apps_domain)
    except admin_api_tool_errors.AdminAPIToolUserError as e:
        log_utils.LogError(
            'Unable to retrieve customer_id for domain %s.' %
            flags.apps_domain, e)
        sys.exit(1)
    filename_path = FILE_MANAGER.WriteDefaults(flags.apps_domain, customer_id,
                                               flags.force)
    print 'Default domain stored in %s.' % filename_path
Example #14
0
def main(argv):
    """A script to revoke tokens issued to users."""
    flags = common_flags.ParseFlags(
        argv, 'Revoke token issued by a user for a client.', AddFlags)
    http = auth_helper.GetAuthorizedHttp(flags)
    user_api = users_api.UsersApiWrapper(http)
    if not user_api.IsDomainUser(flags.user_email):
        print 'User %s not found.' % flags.user_email
        sys.exit(1)

    apps_security_api = tokens_api.TokensApiWrapper(http)
    try:
        # NOTE: attempting to revoke a non-existent token causes no
        #       discernible output (no failure message or fail status).
        apps_security_api.DeleteToken(flags.user_email, flags.client_id)
    except admin_api_tool_errors.AdminAPIToolTokenRequestError as e:
        log_utils.LogError(
            'Unable to revoke token for user %s and client_id %s.' %
            (flags.user_email, flags.client_id), e)
        sys.exit(1)
    log_utils.LogInfo(
        'Successfully revoked token for user %s for client_id %s.' %
        (flags.user_email, flags.client_id))