feat: add OAuth 2.0 support for GSC monitoring
Some checks failed
Build and Deploy / build (push) Has been cancelled

- Updated monitor.py to support both OAuth and Service Account
- Created setup-oauth-local.py for easy local authorization
- Created cronjob-oauth.yaml for OAuth-based deployment
- Updated README with both authentication options
- OAuth is now the recommended method (no key file needed)
This commit is contained in:
Unchained
2026-03-30 17:56:49 +02:00
parent 771e9dc20b
commit 36915a3f75
5 changed files with 458 additions and 10 deletions

View File

@@ -2,6 +2,10 @@
"""
Google Search Console Monitoring Script
Monitors search performance, crawl errors, and indexing status
Supports both:
1. Service Account (with JSON key file)
2. OAuth 2.0 (user authentication)
"""
import os
@@ -9,6 +13,8 @@ import json
import sys
from datetime import datetime, timedelta
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials as OAuthCredentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
@@ -16,14 +22,54 @@ from googleapiclient.errors import HttpError
SITE_URL = "https://manoonoils.com/"
SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
KEY_FILE = os.environ.get("GSC_KEY_FILE", "/etc/gsc-monitoring/service-account.json")
OAUTH_FILE = os.environ.get(
"GSC_OAUTH_FILE", "/etc/gsc-monitoring/oauth-credentials.json"
)
def get_service():
"""Authenticate and return Search Console service"""
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE, scopes=SCOPES
)
return build("webmasters", "v3", credentials=credentials)
# Try OAuth first
if os.path.exists(OAUTH_FILE):
print("Using OAuth authentication...")
with open(OAUTH_FILE, "r") as f:
creds_info = json.load(f)
creds = OAuthCredentials(
token=creds_info["token"],
refresh_token=creds_info["refresh_token"],
token_uri=creds_info["token_uri"],
client_id=creds_info["client_id"],
client_secret=creds_info["client_secret"],
scopes=creds_info["scopes"],
)
# Refresh if expired
if creds.expired:
creds.refresh(Request())
# Save updated credentials
creds_info["token"] = creds.token
with open(OAUTH_FILE, "w") as f:
json.dump(creds_info, f, indent=2)
return build("webmasters", "v3", credentials=creds)
# Fall back to service account
elif os.path.exists(KEY_FILE):
print("Using Service Account authentication...")
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE, scopes=SCOPES
)
return build("webmasters", "v3", credentials=credentials)
else:
raise FileNotFoundError(
f"No credentials found. Please set up either:\n"
f" 1. OAuth: {OAUTH_FILE}\n"
f" 2. Service Account: {KEY_FILE}\n"
f"\nSee README.md for setup instructions."
)
def get_search_analytics(service, days=7):
@@ -157,12 +203,6 @@ def main():
"""Main monitoring function"""
print("🔍 Starting Google Search Console monitoring...")
# Check for credentials
if not os.path.exists(KEY_FILE):
print(f"❌ Error: Service account key file not found at {KEY_FILE}")
print("Please set up Google Cloud credentials first.")
sys.exit(1)
try:
service = get_service()
@@ -182,6 +222,9 @@ def main():
f.write(report)
print(f"\n💾 Report saved to: {report_file}")
except FileNotFoundError as e:
print(f"{e}")
sys.exit(1)
except Exception as e:
print(f"❌ Error: {e}")
sys.exit(1)