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

Last change on this file since a210970 was a210970, checked in by José Sulbarán <jsulbaran@…>, 7 years ago

Se agrego la funcionalidad de la firma bdoc y se modifico el datatable

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