from authentic2.idp.signals import add_attributes_to_response
import xml.etree.ElementTree as ET
from hashlib import sha1
from django.conf import settings
import syslog

def add_attributes(request, user, audience, **kwargs):

    # <saml:Attribute Name="urn:oid:2.16.840.1.113730.3.1.241"
    #     NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
    #     FriendlyName="displayName">
    #         <saml:AttributeValue>Jean Dupont</saml:AttributeValue>
    # </saml:Attribute>

    displayName = ('urn:oid:2.16.840.1.113730.3.1.241',
            'urn:oasis:names:tc:SAML:2.0:attrname-format:uri',
            'displayName')
    displayName_value = user.displayname

    # <saml:Attribute Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10"
    #     NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
    #     FriendlyName="eduPersonTargetedID">
    #         <saml:AttributeValue><saml:NameID
    #             Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
    #             NameQualifier="https://services-federation.renater.fr/test/idp"
    #             SPNameQualifier="https://univnautes.entrouvert.lan/authsaml2/metadata">
    #                 C8NQsm1Y3Gas9m0AMDhxU7UxCSI=
    #         </saml:NameID>
    #     </saml:AttributeValue>
    # </saml:Attribute>

    eduPersonTargetedID = ('urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
            'urn:oasis:names:tc:SAML:2.0:attrname-format:uri',
            'eduPersonTargetedID')

    pseudoid = sha1(user.username + audience + settings.SECRET_KEY).hexdigest()
    eduPersonTargetedID_value = ET.Element('saml:NameID')
    eduPersonTargetedID_value.attrib['Format'] = 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
    eduPersonTargetedID_value.attrib['NameQualifier'] = request.build_absolute_uri('/idp/saml2/metadata')
    eduPersonTargetedID_value.attrib['SPNameQualifier'] = audience
    eduPersonTargetedID_value.attrib['xmlns:saml'] = 'urn:oasis:names:tc:SAML:2.0:assertion'
    eduPersonTargetedID_value.text = pseudoid

    privileges = getattr(user, 'univnautes_privileges', [])

    syslog.openlog("idpauth", syslog.LOG_PID)
    syslog.syslog(syslog.LOG_LOCAL4 | syslog.LOG_INFO,
        'send user:%s to %s with eduPersonTargetedID:%s, privileges %s' %
        (user.username, audience, pseudoid, privileges))

    return { 'attributes': {
        displayName: [displayName_value],
        eduPersonTargetedID: [eduPersonTargetedID_value],
        'univnautesPrivileges': privileges,
        } }

add_attributes_to_response.connect(add_attributes)

