source: prototipo_portal_2018/prototipo/static/js/functions/firmarDocumentoPdf.js @ cd9dc46

Last change on this file since cd9dc46 was cd9dc46, checked in by Antonio Araujo <aaraujo@…>, 7 years ago

Se cambia URL para apuntar a servidor de prueba de murachi y ver comportamiento de recurso /listado

  • Property mode set to 100644
File size: 8.9 KB
Line 
1
2function True_False(data){
3
4    if (data == "true" ){
5      return "Verdadero";
6    }
7    if (data ==  "false"){
8      return "Falso";
9    }
10
11}
12
13function SerealizeMyJson(data){
14  for (var i = 0; i < data.signatures.length; i++) {
15      data.signatures[i].integrityCheck = True_False(data.signatures[i].integrityCheck);
16      data.signatures[i].signerCertificateStillValid = True_False(data.signatures[i].signerCertificateStillValid);
17      data.signatures[i].signerCertificateValidAtTimeOfSigning = True_False(data.signatures[i].signerCertificateValidAtTimeOfSigning);
18      data.signatures[i].signatureCoversWholeDocument = True_False(data.signatures[i].signatureCoversWholeDocument);
19      data.signatures[i].certificatesVerifiedAgainstTheKeyStore = True_False(data.signatures[i].certificatesVerifiedAgainstTheKeyStore);         
20  }
21  return data;
22}
23
24
25//Obtenemos la  informacion de documento
26function InfoDocumentDataTablePDF(signedFileId){
27
28    $.ajax({
29        //url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/"+signedFileId,
30        url: "https://192.168.12.154:8443/Murachi/0.1/archivos/"+signedFileId,
31        type: "get",
32        dataType: "json",       
33        headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
34        success: function(response) {
35           
36                        if (FIRMA_VISIBLE == true){             
37
38                        INFO_DATATABLE = SerealizeMyJson(response);
39                               
40                                CONT += 1;
41                                if (CONT == 1){
42                                        DATATABLE_SIGN_VISIBLE = DataTablePDF(response);       
43
44                                }
45                                if (CONT > 1){
46                                        DATATABLE_SIGN_VISIBLE.destroy();
47                                        DATATABLE_SIGN_VISIBLE = DataTablePDF(response);       
48                                }       
49
50                                CONTAINER = false;
51                                $("#firmar-documento").hide();
52                                $("#pdf-main-container").hide();
53                                $("#myJson_wrapper").show();                                   
54                        }
55                        else{
56
57
58                        INFO_DATATABLE_NO_VISIBLE = SerealizeMyJson(response);
59                               
60                                CONT_NO_VISIBLE += 1;
61                                if (CONT_NO_VISIBLE == 1){
62                                        DATATABLE_SIGN_NO_VISIBLE = DataTablePDFNoVisible(response);   
63
64                                }
65                                if (CONT_NO_VISIBLE > 1){
66                                        DATATABLE_SIGN_NO_VISIBLE.destroy();
67                                        DATATABLE_SIGN_NO_VISIBLE = DataTablePDFNoVisible(response);   
68                                }       
69
70                                CONTAINER2 = false;                             
71                                $("#firmar-doc-noVisible").hide();
72                                $("#pdf-main-container2").hide();
73                                $("#myJsonPDF_NO_VISIBLE_wrapper").show();
74
75
76                        }
77                       
78        },
79        error: function(jqXHR, textStatus, errorThrown){
80                alert(textStatus+", "+ errorThrown+" el documento PDF para mostrar la info de la sign");     
81        }
82        });
83}
84
85
86// Cuarto paso (Se envia la información del token para terminar la firma)
87function FinalizarFirma(signature){
88
89        $.ajax({
90                type: 'POST',
91                contentType: 'application/json',
92                url:"https://192.168.12.154:8443/Murachi/0.1/archivos/pdfs/resenas",
93                //url:"https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/pdfs/resenas",
94                dataType: 'json',
95                data: JSON.stringify({"signature":signature}),
96                xhrFields: {withCredentials: true},
97                headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
98                success: function(data, textStatus, jqXHR){
99
100                        //var linkToDownload = "<a href=\"https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/descargas/" + data['signedFileId'] +"\"><h4>Descargar archivo firmado</h4></a>";
101                        var linkToDownload = "<a href=\"https://192.168.12.154:8443/Murachi/0.1/archivos/descargas/" + data['signedFileId'] +"\"><h4>Descargar archivo firmado</h4></a>";
102                        document.getElementById("log").innerHTML = '';   
103                        document.getElementById("respuesta").innerHTML = '<center><h2>Archivo firmado correctamente:</h2> <br>'+linkToDownload+'</center>';                     
104
105                        InfoDocumentDataTablePDF(data['signedFileId']);         
106
107                },
108                error: function(jqXHR, textStatus, errorThrown){
109                        alert('error en pdfs/resenas: ' + textStatus);
110                        $("#respuesta").html("error en pdfs/resenas: " + textStatus);
111                }
112        });
113
114}
115
116
117//Tercer paso (Obtenemos el hash de pdf enviado por el servidor y luego procesa la información en el token)
118function ObtenerHashPDFServer(parameters,cert){
119
120        $.ajax({
121                type: 'POST',
122                contentType: 'application/json',                               
123                url:"https://192.168.12.154:8443/Murachi/0.1/archivos/pdfs2",
124                //url:"https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/pdfs",
125                dataType: "json",
126                data: parameters,               
127                xhrFields: {withCredentials: true},
128                headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
129                success: function(data, textStatus, jqXHR){
130                        var json_x = data;
131                        var hash = json_x['hash']; 
132                        //alert("hash recibido del servidor "+hash);           
133                        var hashtype = "SHA-256";
134                        var lang = "eng";
135                       
136                        //Procesa la información
137                        window.hwcrypto.sign(cert, {type: hashtype, hex: hash}, {lang: lang}).then(
138                                function(signature) {
139                                        FinalizarFirma(signature.hex);
140                        }, 
141                        function(err) {
142                                log_text("sign() failed: " + err);
143                                        var error;
144                    log_text("sign() failed: " + err);
145                    if(err == "Error: user_cancel") {
146                        alert("sign() failed: El usuario cancelo la operación");
147                        error = "El usuario cancelo la operación"; 
148                     }     
149                     else if(err == "Error: no_certificates") {
150                         alert("sign() failed: No hay certificado disponible");
151                         error = "No hay certificado disponible";
152                     }
153                     else if(err == "Error: no_implementation") {
154                         alert("sign() failed: No hay soporte para el manejo del certificado");
155                         error = "No hay soporte para el manejo del certificado";
156                     }
157
158                                //alert("sign() failed: " + err);
159                                $("#respuesta").html("sign() failed: " + error);
160                });
161                       
162                },                                                             
163                error: function(jqXHR, textStatus, errorThrown){
164                        //alert('error: ' + textStatus);
165                        //var responseText = jQuery.parseJSON(jqXHR.responseText);
166                        alert('ajax error function: ' + jqXHR.responseText);
167                        $("#respuesta").html("error function: " + jqXHR.responseText);
168                }
169               
170        });
171               
172}
173
174
175//Segundo paso (Seleccionamos el Certificado Firmante)
176function ObtenerCertificadoFirmante(response){
177
178        // identificador del archivo en el servidor
179        var fileId = response.fileId.toString();
180        var cert;
181
182        window.hwcrypto.getCertificate({lang: "en"}).then(
183                function(response) {
184                        var cert = response;
185                        var parameters = "";
186
187                        if (FIRMA_VISIBLE == true){             
188                                parameters = JSON.stringify({
189                                        "fileId":fileId,
190                                        "certificate":cert.hex,
191                                        "reason":"Certificado",
192                                        "location":"CENDITEL",
193                                        "contact":"582746574336",
194                                        "signatureVisible":"true",
195                                        "signaturePage": VALOR_PAGE,
196                                        "xPos": VALOR_X,
197                                        "yPos": VALOR_Y
198                                        });
199                        }
200                        else{
201                                parameters = JSON.stringify({
202                                        "fileId":fileId,
203                                        "certificate":cert.hex,
204                                        "reason":"Certificado",
205                                        "location":"CENDITEL",
206                                        "contact":"582746574336",
207                                        "signatureVisible":"false",
208                                        "signaturePage": "",
209                                        "xPos": "",
210                                        "yPos": ""
211                                        });                             
212                        }
213                        // ahora llamar al ajax de obtener la resena del pdf
214                        ObtenerHashPDFServer(parameters, cert); 
215
216                }, 
217                function(err) {
218                        log_text("getCertificate() failed: " + err);
219            var error;
220            if(err == "Error: user_cancel") {
221                alert("getCertificate() failed: El usuario cancelo la operación"    );
222                error = "El usuario cancelo la operación"; 
223             }     
224             else if(err == "Error: no_certificates") {
225                 alert("getCertificate() failed: No hay certificado disponible")    ;
226                 error = "No hay certificado disponible";
227             }
228             else if(err == "Error: no_implementation") {
229                 alert("getCertificate() failed: No hay soporte para el manejo del certificado");
230                 error = "No hay soporte para el manejo del certificado";
231                        }
232                        //alert("getCertificate() failed: " + err);
233                        $("#respuesta").html("getCertificate() failed: " + error);
234                }
235
236        );
237}
238
239
240
241
242// Primer paso (Subir el documento al servidor)
243function SubirDocumentServer(formData){
244
245    $.ajax({
246        url: "https://192.168.12.154:8443/Murachi/0.1/archivos",               
247        //url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos",
248        type: "post",
249        dataType: "json",
250        data: formData,
251        cache: false,
252        contentType: false,
253                processData: false,
254                xhrFields: {withCredentials: true},
255                headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
256                success: function(response) {
257
258                        document.getElementById("respuesta").innerHTML = manejoJsonPDF(JSON.stringify(response));       
259                        ObtenerCertificadoFirmante(response);
260        },
261        error: function(response) {
262                //Que se ejecuta cuando finalice la petición de con error
263                        $("#respuesta").html('Error, al subir el archivo al servidor...!!!');
264                alert("ocurrio un error, al subir el archivo al servidor")
265                }
266    });
267
268}
269
270
271$("#Form-Format-Visible").on('submit', function(event) {
272        event.preventDefault();
273
274        var formData = new FormData(); 
275    formData.append("upload", $("#file-sign-ft_Vble")[0].files[0]);     
276       
277        $('#myJson_wrapper').hide();
278        FIRMA_VISIBLE = true;
279        SubirDocumentServer(formData);
280       
281});
Note: See TracBrowser for help on using the repository browser.