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6MAh8h4cg+CB8F/JJqZCen16764vefPSzLEWCGAbXuCQ5+iSbj
sKpNgufKmUR7jsM1X5nSJ7ccFntCRgOVD6OMERjwjN7lbnn82ELYN+9IPKuyMvKN
jyohQkcQrxzBjwyZiIIqHB7uaSnsHvnpKKsonrmm9dS6+kZ7r+agN4Q=
-----END CERTIFICATE-----
<?xml version="1.0" encoding="UTF-8"?>
<notary xmlns="http://podepsano.cz/">
<provider_id>foovider</provider_id>
<provider_request_id>abc12345</provider_request_id>
<provider_return_url>http://www.provider.foo/return/url</provider_return_url>
<provider_requested_id_attributes>
<req_id_att>http://axschema.org/contact/state/home</req_id_att>
<req_id_att>http://specs.nic.cz/attr/addr/mail/cc</req_id_att>
<req_id_att>http://specs.nic.cz/attr/phone/main</req_id_att>
</provider_requested_id_attributes>
<request>
<subject>Order confirmation</subject>
<request_content>
<content_type>plain</content_type>
<content>I confirm the order of 10 ...</content>
</request_content>
</request>
</notary>
\ No newline at end of file
var xml_parts = new Array();
xml_parts[1] = "<?xml version='1.0' encoding='UTF-8'?>\n<request_bundle xmlns='http://podepsano.cz/'>\n <provider_id>";
xml_parts[2] = "</provider_id>\n <provider_request_id>";
xml_parts[3] = "</provider_request_id>\n <provider_return_url>";
xml_parts[4] = "</provider_return_url>\n <provider_requested_id_attributes>\n";
xml_parts[5] = " </provider_requested_id_attributes>\n <request>\n <subject>";
xml_parts[6] = "</subject>\n <content type='text/plain'>\n";
xml_parts[7] = "\n </content>\n </request>\n</request_bundle>";
/*
xml_parts[1] = "&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\n&lt;request_bundle xmlns=&quot;http://podepsano.cz/&quot;&gt;\n &lt;provider_id&gt;";
xml_parts[2] = "&lt;/provider_id&gt;\n &lt;provider_request_id&gt;";
xml_parts[3] = "&lt;/provider_request_id&gt;\n &lt;provider_return_url&gt;";
xml_parts[4] = "&lt;/provider_return_url&gt;\n &lt;provider_requested_id_attributes&gt;\n";
xml_parts[5] = " &lt;/provider_requested_id_attributes&gt;\n &lt;request&gt;\n &lt;subject&gt;";
xml_parts[6] = "&lt;/subject&gt;\n &lt;content type=&quot;text/plain&quot;&gt;";
xml_parts[7] = "\n &lt;/content&gt;\n &lt;/request&gt;\n&lt;/request_bundle&gt;";
*/
function fillXML() {
for (var i = 1; i < xml_parts.length; i++) {
var xml_active = document.getElementById("xml_part"+i);
xml_active.textContent = xml_parts[i];
}
}
fillXML();
var active_field = null;
function fieldFocus(elem) {
//console.log("focus");
//console.log(elem.name);
active_field = elem;
}
function fieldBlur(elem) {
//console.log("end");
active_field = null;
Deactive(elem);
}
function Active() {
if (active_field) {
//console.log(active_field.name);
var xml_active = document.getElementById("xml_"+active_field.name);
//xml_active.style.color = "#f00";
//xml_active.style.fontWeight = "bold";
xml_active.style.background = "#f00";
xml_active.textContent = active_field.value;
}
}
function Deactive(elem) {
var xml_active = document.getElementById("xml_"+elem.name);
//xml_active.style.color = "#000";
//xml_active.style.fontWeight = "normal";
xml_active.style.background = "#fff";
}
function fieldCheckbox() {
var xml_active = document.getElementById("xml_checkbox");
xml_active.textContent = "";
xml_active.style.color = "#f00";
var element;
for (var i = 1; element = document.getElementById("check"+i); i++) {
if (element.checked) {
//console.log(element.name);
//&lt;req_id_attr&gt;http://specs.nic.cz/attr/phone/main&lt;/req_id_attr&gt;
//var text = " &lt;req_id_attr&gt;" + element.name + "&lt;/req_id_attr&gt;\n";
var text = " <req_id_attr>" + element.name + "</req_id_attr>\n";
xml_active.appendChild(document.createTextNode(text));
}
}
}
function send() {
// generating XML
var spans = document.getElementsByTagName('span');
var together = ""
for (var i = 0; i < spans.length; i++) {
together += spans[i].textContent;
}
//console.log(together);
// filling hidden element
var xmldata = document.getElementById("xmldata");
xmldata.value = together;
// sending form
document.getElementById('sending_form').submit();
}
function mainLoop() {
Active();
setTimeout(mainLoop, 10);
}
mainLoop();
This diff is collapsed.
#!/usr/bin/python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="{{links.media}}img/favicon.ico"></link>
<title>Podepsáno.cz - Zkušební e-shop</title>
<style>
body {
margin: 50px 0px;
padding: 0px;
text-align: left;
background: #888;
color: #333;
font: 70%/1.5 Verdana, Tahoma, Arial, Helvetica, sans-serif;
}
.main {
float: none;
padding: 20px;
min-height: 600px;
background: #fff;
border-radius: 6px;
}
.wrapper {
margin: auto;
position: relative;
width: 960px;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="main">
<h1><img src="{{links.media}}img/podepsano_logo.png" alt="PODEPSANO.cz" /> Zkušební e-shop</h1>
<hr/>
<br/><br/>
<h2>
{% if confirmed != NULL %}
Vítejte zpátky.
{% if error %}
V průběhu nasala chyba mojeID.
{% else %}
Vaše objednávka byla
{% if confirmed %}
POTVRZENA.
{% else %}
ODMÍTNUTA.
{% endif %}
{% endif %}
{% else %}
Mock shop end point.
{% endif %}
</h2>
<br/><br/>
{% if requested_attrs %}
<h3>Získané údaje:</h3>
{% for one in requested_attrs %}
<li><b>{{one.0}}</b> ({{one.1}})</li>
{% endfor %}
<br/>
{% endif %}
{% if sig_ok != NULL %}
{% if sig_ok == "Error" %}
<p><b>Error:</b> Nemohu ověřit podpis.</p>
{% else %}
<p><b>Ověření podpisu:</b> {{sig_ok}}</p>
{% endif %}
<br/>
{% endif %}
<p>Vytvořit <a href="{{links.start}}">novou objednávku</a>.</p>
</div>
<p>Developed by: <a href="http://nic.cz" target="_blank">CZ.NIC</a></p>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="{{links.media}}img/favicon.ico"></link>
<title>Podepsáno.cz - XML Generator</title>
<style>
body {
margin: 50px 0px;
padding: 0px;
text-align: left;
background: #888;
color: #333;
font: 70%/1.5 Verdana, Tahoma, Arial, Helvetica, sans-serif;
}
.formular {
float: left;
width: 300px;
overflow: hidden;
}
.result {
float: right;
width: 650px;
overflow: hidden;
}
.block {
border: 1px solid;
padding: 10px;
text-align: left;
min-height: 500px;
background-color: #fff;
color: #000;
border-radius: 6px;
}
#result {
padding: 0px;
margin: 0px;
background-color: #fff;
color: #000;
font-family: Courier, monospace;
text-align: left;
}
.main {
float: none;
padding: 20px;
min-height: 600px;
background: #fff;
border-radius: 6px;
}
.wrapper {
margin: auto;
position: relative;
width: 1060px;
}
input {
font-size: 14px;
font-family: Courier;
}
textarea {
font-size: 14px;
font-family: Courier;
resize: vertical;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="main">
<h1><img src="{{links.media}}img/podepsano_logo.png" alt="PODEPSANO.cz" /> XML Generator</h1>
<div class="formular block">
<p><b>Vstupní formulář:</b></p>
<form>
Název společnosti:<br/><input type="text" name="var1" value="CZ.NIC" size="32" onFocus="fieldFocus(this);" onBlur="fieldBlur(this);" /><br/><br/>
ID žádosti:<br/><input type="text" name="var2" value="id12345" size="32" onFocus="fieldFocus(this);" onBlur="fieldBlur(this);" /><br/><br/>
Návratová URL:<br/><input type="text" name="var3" value="{{finish}}" size="32" onFocus="fieldFocus(this);" onBlur="fieldBlur(this);" /><br/><br/>
Požadovaná data od uživatele:<br/>
<input id="check1" type="checkbox" name="http://specs.nic.cz/attr/contact/name/last" onClick="fieldCheckbox();" />Příjmení<br/>
<input id="check2" type="checkbox" name="http://axschema.org/contact/email" onClick="fieldCheckbox();" />Email<br/>
<input id="check3" type="checkbox" name="http://specs.nic.cz/attr/phone/main" onClick="fieldCheckbox();" />Telefon<br/>
Další možné atributy naleznete v <a href="http://www.mojeid.cz/files/mojeid/mojeid_technicky.pdf" target="_blank">technické dokumentaci mojeID</a>.
<br/><br/>
Předmět zprávy:<br/><input type="text" name="var4" value="Zrušení domény" size="32" onFocus="fieldFocus(this);" onBlur="fieldBlur(this);" /><br/><br/>
Obsah zprávy:<br/><textarea name="var5" rows="5" cols="30" onFocus="fieldFocus(this);" onBlur="fieldBlur(this);">Závazně žádám o zrušení domény "http://nic.cz".</textarea><br/><br/>
<input type="button" name="" value="Objednat" onClick="send();" /><br/>
</form>
<form action="{{start}}" id="sending_form" method="post" enctype="multipart/form-data">
<input type="hidden" id="xmldata" name="xmldata" value="" />
</form>
</div>
<div class="result block">
<p><b>Vygenerované XML:</b></p>
<pre id="result"><span id="xml_part1"></span><span id="xml_var1">CZ.NIC</span><span id="xml_part2"></span><span id="xml_var2">id12345</span><span id="xml_part3"></span><span id="xml_var3">{{finish}}</span><span id="xml_part4"></span><span id="xml_checkbox"></span><span id="xml_part5"></span><span id="xml_var4">Zrušení domény</span><span id="xml_part6"></span><span id="xml_var5">Závazně žádám o zrušení domény "http://nic.cz".</span><span id="xml_part7"></span></pre>
</div>
<div style="clear: both;"></div><br/>
<p>Návrat na <a href="{{links.start}}">zkušební e-shop</a>.</p>
</div>
<script src="{{links.media}}js/generator.js"></script>
<p>Developed by: <a href="http://nic.cz" target="_blank">CZ.NIC</a></p>
</div>
</body>
</html>
\ No newline at end of file
This diff is collapsed.
from django.db import models
# Create your models here.
import xml.dom.minidom as dom
# built-in modules
import logging
# third party imports
import libxml2
import xmlsec
import yaml
from django.conf import settings
BASE_SHARE_DIR = settings.BASE_SHARE_DIR # path to directory with attribute.yaml
NOTARY_CERTIFICATE_PATH = settings.NOTARY_CERTIFICATE_PATH # path to podepsano_public_certificate.pem
log = logging.getLogger(__name__)
# SIGNATURE VALIDATION RESULT CONSTANTS
SIGNATURE_VALID = 0
SIGNATURE_INVALID = 1
SIGNATURE_VERIFY_FAILED = 2
SIGNATURE_ROOT_ELEMENT_NOT_FOUND = 3
SIGNATURE_XML_PARSING_FAILED = 4
SIGNATURE_CANNOT_CREATE_CONTEXT = 5
def create_xml(company_name, req_id, return_url, requested_attrs, subject, content):
"""
Returns string of generated XML.
"""
xml_parts = []
xml_parts.append("<?xml version='1.0' encoding='UTF-8'?>\n<request_bundle xmlns='http://podepsano.cz/'>\n <provider_id>")
xml_parts.append("</provider_id>\n <provider_request_id>")
xml_parts.append("</provider_request_id>\n <provider_return_url>")
xml_parts.append("</provider_return_url>\n <provider_requested_id_attributes>\n")
xml_parts.append(" </provider_requested_id_attributes>\n <request>\n <subject>")
xml_parts.append("</subject>\n <content type='text/plain'>\n")
xml_parts.append("\n </content>\n </request>\n</request_bundle>")
requested_attrs_result = ""
for one in requested_attrs:
requested_attrs_result += one + "\n"
result = xml_parts[0] + company_name + xml_parts[1] + req_id + xml_parts[2] + return_url + xml_parts[3] + requested_attrs_result + xml_parts[4] + subject + xml_parts[5] + content + xml_parts[6]
return result
def parse_xml(xml_data):
"""
Parse given xml_data.
"""
try:
parsed_data = dom.parseString(xml_data)
except Exception as exc:
return False
error = False
result = {}
requested_attrs = []
for one in parsed_data.getElementsByTagName("id_attr"):
requested_attrs.append([ one.getAttribute("name"), one.childNodes[0].nodeValue ])
result['requested_attrs'] = requested_attrs
for one in parsed_data.getElementsByTagName("confirmation"):
status = one.getAttribute("status")
if status == "confirmed":
result['confirmed'] = True
elif status == "rejected":
result['confirmed'] = False
else:
error = True
for conf in parsed_data.getElementsByTagName("err_code"):
error = True
for one in parsed_data.getElementsByTagName("subject"):
result['subject'] = one.childNodes[0].nodeValue
for one in parsed_data.getElementsByTagName("content"):
result['content'] = one.childNodes[0].nodeValue
if error:
return False
return result
def translate_attr(wanted, language_filter="cs"):
"""
Returns name of wanted attribute from yaml dictionary.
"""
try:
f = open(BASE_SHARE_DIR+'attribute.yaml','r')
except:
return wanted
data_yaml = yaml.load(f)
f.close()
wanted_attribute = 0
# looking for wanted_attribute
for one in data_yaml:
if len(one['fields'].keys()) == 2:
if one['fields']['url'] == wanted:
wanted_attribute = one['fields']['attribute']
# wanted_attribute not found
if not wanted_attribute:
return wanted
# looking for name
for one in data_yaml:
if len(one['fields'].keys()) == 3:
if one['fields']['master'] == wanted_attribute:
# language filter
if one['fields']['language_code'] == language_filter:
return one['fields']['name']
# no match
return wanted
def init():
# Init libxml library
#libxml2.initParser()
#libxml2.substituteEntitiesDefault(1)
# Init xmlsec library
if xmlsec.init() < 0:
log.error("Error: xmlsec initialization failed.")
return -1
# Check loaded library version
if xmlsec.checkVersion() != 1:
log.error("Error: loaded xmlsec library version is not compatible.\n")
return -1
# Init crypto library
if xmlsec.cryptoAppInit(None) < 0:
log.error("Error: crypto initialization failed.")
# Init xmlsec-crypto library
if xmlsec.cryptoInit() < 0:
log.error("Error: xmlsec-crypto initialization failed.")
def destroy():
# Shutdown xmlsec-crypto library
xmlsec.cryptoShutdown()
# Shutdown crypto library
xmlsec.cryptoAppShutdown()
# Shutdown xmlsec library
xmlsec.shutdown()
# Shutdown LibXML2
#libxml2.cleanupParser()
# cannot cleanup parser, because lxml also uses libxml and we get some segfaults....
pass
def get_keymanager():
mngr = xmlsec.KeysMngr()
if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
print "Error: failed to initialize keys manager."
mngr.destroy()
return False
if mngr.certLoad(NOTARY_CERTIFICATE_PATH, xmlsec.KeyDataFormatPem,
xmlsec.KeyDataTypeTrusted) < 0:
print "Error: failed to load pem certificate from \"%s\"", file
mngr.destroy()
return None
return mngr
def verify_xml(xml_data):
"""
Returns an integer from the SIGNATURE_* set described above in this module.
Anything other than SIGNATURE_VALID means the signature is not OK.
SIGNATURE_INVALID means the signature does not match, the rest is some kind
of error state.
"""
init()
mngr = get_keymanager()
if not mngr:
raise Exception("KeyManager init error")
doc = libxml2.parseMemory(xml_data, len(xml_data))
if doc is None or doc.getRootElement() is None:
log.error("Error: unable to parse file")
cleanup(doc)
destroy()
return SIGNATURE_XML_PARSING_FAILED
# Find start node
node = xmlsec.findNode(doc.getRootElement(),
xmlsec.NodeSignature, xmlsec.DSigNs)
if node is None:
log.error("Error: start node not found")
cleanup(doc)
destroy()
return SIGNATURE_ROOT_ELEMENT_NOT_FOUND
# Create signature context
dsig_ctx = xmlsec.DSigCtx(mngr)
if dsig_ctx is None:
log.error("Error: failed to create signature context")
cleanup(doc)
destroy()
return SIGNATURE_CANNOT_CREATE_CONTEXT
# Verify signature
if dsig_ctx.verify(node) < 0:
log.error("Error: signature verify")
cleanup(doc, dsig_ctx)
destroy()
return SIGNATURE_VERIFY_FAILED
# Print verification result to stdout
if dsig_ctx.status == xmlsec.DSigStatusSucceeded:
log.debug("Signature is OK")
res = SIGNATURE_VALID
else:
log.debug("Signature is INVALID")
res = SIGNATURE_INVALID
# Success
cleanup(doc, dsig_ctx, 1)
destroy()
return res
def cleanup(doc=None, dsig_ctx=None, res=-1):
if dsig_ctx is not None:
dsig_ctx.destroy()
if doc is not None:
doc.freeDoc()
return res
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin: