Skip to content

fix: docs, add python script I used in debugging the MP setup #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions examples/import-existing-org/debugging-script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#
# We at Masterpoint found this python script to be useful when debugging import
# issues with existing users and roles into the terraform module to confirm the
# expected data values. For example, confirm data and formatting of
# exsting users' custom schema keys, values, and json encoded strings.
#
# This is intended only for ad-hoc debugging purposes and has not been thorughly
# reviewed or tested. Use at your own risk.
#

from google.oauth2 import service_account
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify the Google OAuth2 import is available.

The static analysis tool flagged this import, but it appears to be the correct import for the google-auth library. Please ensure the google-auth package is installed.


🏁 Script executed:

#!/bin/bash
# Check if the google-auth package provides the oauth2 module
python -c "from google.oauth2 import service_account; print('Import successful')" 2>/dev/null || echo "Import failed - google-auth package may not be installed"

Length of output: 212


🏁 Script executed:

#!/bin/bash
# Search for google-auth in common Python dependency files
set -e
FILES=$(find . -maxdepth 2 -type f \( -iname "requirements*.txt" -o -iname "pyproject.toml" -o -iname "setup.cfg" -o -iname "setup.py" \))
if [[ -z "$FILES" ]]; then
  echo "No dependency files found"
  exit 0
fi
for f in $FILES; do
  echo "=== $f ==="
  grep -n "google-auth" "$f" || echo "google-auth not found in $f"
done

Length of output: 230


Ensure google-auth is declared as a dependency

  • The import
    from google.oauth2 import service_account
    is correct, but it fails at runtime because the google-auth package isn’t installed.
  • No dependency file (requirements.txt, pyproject.toml, setup.cfg, etc.) was found in the repo.
  • Please add google-auth to your project’s dependencies so tooling and runtime environments can resolve the module.

For example, you can create or update a requirements file:

# examples/import-existing-org/requirements.txt
+ google-auth

Or in pyproject.toml:

[tool.poetry.dependencies]
+ google-auth = "^2.20.0"
🧰 Tools
🪛 Pylint (3.3.7)

[error] 11-11: No name 'oauth2' in module 'google'

(E0611)

🤖 Prompt for AI Agents
In examples/import-existing-org/debugging-script.py at line 11, the import from
google.oauth2 import service_account is correct but fails at runtime due to the
missing google-auth package. To fix this, add google-auth as a dependency in
your project by creating or updating a requirements.txt or pyproject.toml file
with google-auth included, ensuring the package is installed in your
environment.

from googleapiclient.discovery import build

# Path to your service account JSON key
SERVICE_ACCOUNT_FILE = 'my-google-admin-api-key.json'

# Replace with your impersonated Google Workspace admin email
DELEGATED_ADMIN = 'first.last@your-company.io'

SCOPES = [
"https://www.googleapis.com/auth/admin.directory.group",
"https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/admin.directory.userschema",
"https://www.googleapis.com/auth/apps.groups.settings",
"https://www.googleapis.com/auth/iam",
]

# Load credentials and delegate to admin
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,
scopes=SCOPES
).with_subject(DELEGATED_ADMIN)


# Build the service
service = build('admin', 'directory_v1', credentials=credentials)


# Call the Directory API to list all user schemas
def list_user_schemas(customer_id='my_customer'):
try:
schemas = service.schemas().list(customerId=customer_id).execute()
for schema in schemas.get('schemas', []):
print(f"Schema ID: {schema['schemaId']}")
print(f"Schema Name: {schema['schemaName']}")
print(f"Fields:")
for field in schema.get('fields', []):
print(field)
# print(f" - '{field['fieldName']}' ({field['fieldType']})")
print(f" - '{field['fieldName']}': '{field['fieldValues']}'")
except Exception as e:
print(f"Failed to retrieve schemas: {e}")


def get_user_custom_schemas(user_email):
try:
# Use projection='full' to include custom schemas in the response
user = service.users().get(userKey=user_email, projection='full').execute()
print(user)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove or conditionally log sensitive user data.

Printing the entire user object may expose sensitive PII data. Consider removing this debug print or making it conditional.

-        print(user)
+        # Uncomment below for detailed debugging (contains sensitive data)
+        # print(user)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
print(user)
# Uncomment below for detailed debugging (contains sensitive data)
# print(user)
🤖 Prompt for AI Agents
In examples/import-existing-org/debugging-script.py at line 59, the code prints
the entire user object, which may expose sensitive PII data. Remove this print
statement or modify it to log only non-sensitive information conditionally, such
as when a debug flag is enabled, to avoid exposing sensitive data in production
or shared logs.

custom_schemas = user.get('customSchemas', {})

print(f"Custom schemas for {user_email}:")
for schema_name, schema_data in custom_schemas.items():
print(f" Schema: {schema_name}")
for field_name, field_value in schema_data.items():
print(f" {field_name}: {field_value}")

return custom_schemas
except Exception as e:
print(f"Failed to retrieve user custom schemas: {e}")
return None


def list_group_members(group_email):
results = service.members().list(groupKey=group_email).execute()
members = results.get('members', [])
for member in members:
# print(member['email'])
print(member)
Comment on lines +74 to +79
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add exception handling and clean up commented code.

This function lacks exception handling unlike the other functions. Add consistent error handling and remove commented debug code.

 def list_group_members(group_email):
-    results = service.members().list(groupKey=group_email).execute()
-    members = results.get('members', [])
-    for member in members:
-        # print(member['email'])
-        print(member)
+    try:
+        results = service.members().list(groupKey=group_email).execute()
+        members = results.get('members', [])
+        for member in members:
+            print(member)
+    except Exception as e:
+        print(f"Failed to retrieve group members: {e}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def list_group_members(group_email):
results = service.members().list(groupKey=group_email).execute()
members = results.get('members', [])
for member in members:
# print(member['email'])
print(member)
def list_group_members(group_email):
try:
results = service.members().list(groupKey=group_email).execute()
members = results.get('members', [])
for member in members:
print(member)
except Exception as e:
print(f"Failed to retrieve group members: {e}")
🤖 Prompt for AI Agents
In examples/import-existing-org/debugging-script.py between lines 74 and 79, the
list_group_members function lacks exception handling and contains commented-out
debug code. Add a try-except block around the API call and member iteration to
catch and log any exceptions consistently with other functions. Remove the
commented-out print statement to clean up the code.



if __name__ == '__main__':
# list_group_members('team@your-company.io')
# list_user_schemas()
get_user_custom_schemas('first.last@your-company.io')