HR-ATS-Portal/backend/g_sheet/store_session.py

79 lines
2.5 KiB
Python

"""Capture a Google authorized_user session into credentials/.
Run on a machine with a browser (Windows/macOS). Copy the resulting JSON to
Linux prod — the API never opens a browser.
cd backend
python g_sheet/store_session.py
python g_sheet/store_session.py --force # re-consent, mint a new refresh token
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
# `python g_sheet/store_session.py` puts this file's dir on sys.path, not backend/.
_BACKEND=Path(__file__).resolve().parent.parent
if str(_BACKEND) not in sys.path:
sys.path.insert(0,str(_BACKEND))
from g_sheet.plugins import (
SCOPES,
SheetsAuthError,
load_credentials,
resolve_client_secret_path,
resolve_credentials_path,
store_authorized_session,
)
def _authorize_browser(client_secret_path):
try:
from google_auth_oauthlib.flow import InstalledAppFlow
except ImportError as e:
raise SystemExit(
"google-auth-oauthlib is required for browser login. "
"pip install google-auth-oauthlib==1.4.0"
) from e
if client_secret_path is None or not client_secret_path.exists():
raise SystemExit(
"OAuth client file not found. Set GOOGLE_OAUTH_CLIENT_ID_FILE "
"(credentials/client_secret.json)."
)
flow=InstalledAppFlow.from_client_secrets_file(str(client_secret_path),SCOPES)
return flow.run_local_server(port=0,prompt="consent",access_type="offline")
def main(argv=None):
parser=argparse.ArgumentParser(description="Store a Google authorized_user session on disk.")
parser.add_argument(
"--force",
action="store_true",
help="Ignore the existing ADC file and open a browser consent screen.",
)
args=parser.parse_args(argv)
path=resolve_credentials_path()
if path is None:
raise SystemExit("GOOGLE_APPLICATION_CREDENTIALS is not set.")
credentials=None
if not args.force:
try:
credentials=load_credentials()
except SheetsAuthError as e:
print(f"existing session unusable ({e}); opening browser…",file=sys.stderr)
if credentials is None:
credentials=_authorize_browser(resolve_client_secret_path())
stored=store_authorized_session(credentials)
else:
stored=path
if stored is None:
raise SystemExit("failed to write the authorized session file")
print(f"stored authorized session: {stored}")
return 0
if __name__=="__main__":
raise SystemExit(main())