#!/usr/bin/env python3
import json, subprocess, time
from curl_cffi import requests
AUTH='https://mein-portal.baloise.de'
GW='https://gwde.baloise.de'
H={'X-Bug-Bounty':'dwbzn'}
principal=subprocess.check_output(['toadcli','cred','show','cred-1d4516f308d74b2d9b63a73243ee6899','-f','principal'],text=True).strip()
secret=subprocess.check_output(['toadcli','cred','show','cred-1d4516f308d74b2d9b63a73243ee6899','-f','secret'],text=True).strip()
s=requests.Session()
def rec(stage,r,redact=False):
 out={'stage':stage,'status':r.status_code,'url':r.url,'exchange_id':getattr(r,'toadex_exchange_id',None),'location':r.headers.get('location'),'x_forward_url':r.headers.get('x-forward-url'),'content_type':r.headers.get('content-type')}
 try:
  j=r.json(); out['json']=j
 except Exception: out['body']=r.text[:1500]
 print(json.dumps(out,ensure_ascii=False))
 return out
# Create the application handoff on GWDE and carry its target to canonical IAM.
r=s.get(GW+'/pc/',headers=H,allow_redirects=False,timeout=30); rec('gw_pc_init',r)
loc=r.headers.get('location') or '/auth/login?Location=https%3A%2F%2Fgwde%2Ebaloise%2Ede%2Fpc%2F'
r=s.get(GW+loc if loc.startswith('/') else loc,headers=H,allow_redirects=False,timeout=30); rec('gw_auth_redirect',r)
# Initialize cookies/UI on the canonical IAM host.
r=s.get(AUTH+'/auth/ui/app',headers=H,allow_redirects=False,timeout=30); rec('iam_init',r)
csrf=s.cookies.get('CSRFT759-S',domain='mein-portal.baloise.de') or s.cookies.get('CSRFT759-S')
h={**H,'Accept':'application/json','Content-Type':'application/json','X-Same-Domain':'1'}
if csrf: h['X-CSRFT759']=csrf
r=s.post(AUTH+'/auth/rest/public/authentication/applications/guidewire_pc/access',headers=h,data='null',allow_redirects=False,timeout=30); rec('select_guidewire_pc',r)
time.sleep(1)
csrf=s.cookies.get('CSRFT759-S',domain='mein-portal.baloise.de') or s.cookies.get('CSRFT759-S')
if csrf: h['X-CSRFT759']=csrf
h['X-Continue-Flow']='true'
# Exactly one credential submission; do not retry variants.
r=s.post(AUTH+'/auth/rest/public/authentication/password/check',headers=h,json={'username':principal,'password':secret},allow_redirects=False,timeout=30); rec('password_check',r)
csrf=s.cookies.get('CSRFT759-S',domain='mein-portal.baloise.de') or s.cookies.get('CSRFT759-S')
if csrf: h['X-CSRFT759']=csrf
r=s.get(AUTH+'/auth/rest/public/flow',headers=h,allow_redirects=False,timeout=30); rec('flow_after',r)
r=s.get(GW+'/pc/',headers=H,allow_redirects=False,timeout=30); rec('gw_pc_after',r)
