use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.
the class ProcessoValidarGet method verify.
public static Map<String, Object> verify(String jwt) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, SignatureException, IOException, JWTVerifyException {
final JWTVerifier verifier = new JWTVerifier(Utils.getApiPassword());
Map<String, Object> map;
map = verifier.verify(jwt);
return map;
}
use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.
the class CertidaoObterTokenGet method verify.
public static Map<String, Object> verify(String jwt) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, SignatureException, IOException, JWTVerifyException {
final JWTVerifier verifier = new JWTVerifier(Utils.getApiPassword());
Map<String, Object> map;
map = verifier.verify(jwt);
return map;
}
use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.
the class CertidaoObterTokenGet method jwt.
public static String jwt(String certidao, String requisitante, String cpfcnpj) throws Exception {
final String issuer = Utils.getJwtIssuer();
// issued at claim
final long iat = System.currentTimeMillis() / 1000L;
// token expires in 12h
final long exp = iat + 12 * 60 * 60L;
final JWTSigner signer = new JWTSigner(Utils.getApiPassword());
final HashMap<String, Object> claims = new HashMap<String, Object>();
if (issuer != null)
claims.put("iss", issuer);
claims.put("exp", exp);
claims.put("iat", iat);
claims.put("certidao", certidao);
claims.put("requisitante", requisitante);
claims.put("cpfcnpj", cpfcnpj);
claims.put("typ", "consulta-certidao");
final String jwt = signer.sign(claims);
return jwt;
}
use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.
the class DownloadJwtFilenameGet method run.
@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
Map<String, Object> map = verify(req.jwt);
String username = (String) map.get("username");
String origin = (String) map.get("origin");
String password;
if (username != null && !"pub".equals(origin))
password = AutenticarPost.Usuario.getSenha(username);
else {
username = BalcaojusServlet.INSTANCE.getProperty("public.username");
password = BalcaojusServlet.INSTANCE.getProperty("public.password");
}
String name = (String) map.get("name");
String file = (String) map.get("file");
String numProc = (String) map.get("proc");
String numDoc = (String) map.get("doc");
String orgao = (String) map.get("orgao");
String type = (String) map.get("typ");
String text = (String) map.get("text");
String cargo = (String) map.get("cargo");
String empresa = (String) map.get("empresa");
String unidade = (String) map.get("unidade");
String uuid = (String) map.get("uuid");
String disposition = "attachment".equals(req.disposition) ? "attachment" : "inline";
if (!"download".equals(type))
throw new Exception("Tipo de token JWT inválido");
if (text != null) {
byte[] pdf = ProcessoNumeroCotaPrevisaoPdfPost.criarPDF(name, numProc, text, cargo, empresa, unidade);
resp.contentdisposition = "inline";
resp.contentlength = (long) pdf.length;
resp.contenttype = "application/pdf";
resp.inputstream = new ByteArrayInputStream(pdf);
} else if (file != null && file.equals("avisos-pendentes.xml")) {
// TODO: IMPLEMENTAR
// // Processo completo
// Future<SwaggerAsyncResponse<UsuarioWebUsernameAvisoPendenteExportarGetResponse>>
// future = SwaggerCall
// .callAsync("obter XML de avisos", "Bearer " + req.jwt, "GET",
// Utils.getWsProcessualUrl() + "/usuario-web/" +
// map.get("username")
// + "/aviso-pendente/exportar",
// null, UsuarioWebUsernameAvisoPendenteExportarGetResponse.class);
// SwaggerAsyncResponse<UsuarioWebUsernameAvisoPendenteExportarGetResponse>
// sar = future.get();
// if (sar.getException() != null)
// throw sar.getException();
// UsuarioWebUsernameAvisoPendenteExportarGetResponse r =
// (UsuarioWebUsernameAvisoPendenteExportarGetResponse) sar
// .getResp();
// resp.contentdisposition = "attachment;filename=" +
// map.get("username") + "-avisos-pendentes.xml";
// resp.contentlength = r.contentlength;
// resp.contenttype = r.contenttype;
// resp.inputstream = r.inputstream;
} else if (file != null && file.equals("avisos-confirmados.xml")) {
// TODO: IMPLEMENTAR
// Future<SwaggerAsyncResponse<UsuarioWebUsernameAvisoConfirmadoExportarGetResponse>>
// future = SwaggerCall
// .callAsync("obter XML de avisos confirmados", "Bearer " +
// req.jwt, "GET",
// Utils.getWsProcessualUrl() + "/usuario-web/" +
// map.get("username")
// + "/aviso-confirmado/exportar",
// null,
// UsuarioWebUsernameAvisoConfirmadoExportarGetResponse.class);
// SwaggerAsyncResponse<UsuarioWebUsernameAvisoConfirmadoExportarGetResponse>
// sar = future.get();
// if (sar.getException() != null)
// throw sar.getException();
// UsuarioWebUsernameAvisoConfirmadoExportarGetResponse r =
// (UsuarioWebUsernameAvisoConfirmadoExportarGetResponse) sar
// .getResp();
// resp.contentdisposition = "attachment;filename=" +
// map.get("username") + "-avisos-confirmados.xml";
// resp.contentlength = r.contentlength;
// resp.contenttype = r.contenttype;
// resp.inputstream = r.inputstream;
} else {
ContentInfoUtil contentInfoUtil = new ContentInfoUtil();
if (numDoc != null) {
byte[] ab = null;
// Peça Processual
username = Utils.preprocessarId(username, password, orgao, origin);
password = Utils.preprocessarSenha(username, password, orgao, origin);
ab = SoapMNI.obterPecaProcessual(username, password, orgao, numProc, numDoc);
ContentInfo info = contentInfoUtil.findMatch(ab);
resp.contenttype = info.getMimeType();
if (info.getMimeType().startsWith("application/xml")) {
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
String fileEncoding = xmlStreamReader.getEncoding();
boolean fHtml = false;
while (xmlStreamReader.hasNext()) {
int eventType = xmlStreamReader.next();
if (eventType == XMLStreamConstants.START_ELEMENT) {
if (xmlStreamReader.getLocalName().equals("html"))
fHtml = true;
break;
}
}
xmlStreamReader.close();
if (fHtml) {
info = contentInfoUtil.findMimeTypeMatch("text/html");
resp.contenttype = info.getMimeType() + "; charset=" + fileEncoding;
}
}
resp.contentdisposition = disposition + ";filename=" + numProc + "-peca-" + numDoc + "." + info.getFileExtensions()[0];
resp.contentlength = (long) ab.length;
resp.inputstream = new ByteArrayInputStream(ab);
} else if (uuid != null) {
String dirTemp = Utils.getDirTemp();
String bufName = dirTemp + "/" + numProc + "-completo-" + uuid + ".pdf";
resp.contentdisposition = disposition + ";filename=" + numProc + "-completo.pdf";
resp.contentlength = (long) new File(bufName).length();
resp.contenttype = "application/pdf";
resp.inputstream = new FileInputStream(bufName);
} else {
// Processo completo
// Consulta o processo para saber quais são os documentos a serem
// concatenados
String json = SoapMNI.consultarProcesso(username, password, orgao, numProc, false, false, true);
JSONObject proc = new JSONObject(json).getJSONObject("value");
JSONArray docs = proc.getJSONArray("documento");
// Cria um documento em diretório temporário para agregar os
// diversos PDFs
String dirTemp = Utils.getDirTemp();
String bufName = dirTemp + "/" + numProc + "-completo-" + UUID.randomUUID().toString() + ".pdf";
FileOutputStream buf = new FileOutputStream(bufName);
Document document = new Document();
PdfCopy copy = new PdfSmartCopy(document, buf);
document.open();
PdfReader reader;
for (int i = 0; i < docs.length(); i++) {
String idDocumento = docs.getJSONObject(i).getString("idDocumento");
byte[] ab = SoapMNI.obterPecaProcessual(username, password, orgao, numProc, idDocumento);
ContentInfo info = contentInfoUtil.findMatch(ab);
if (info.getMimeType().startsWith("application/xml")) {
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
String fileEncoding = xmlStreamReader.getEncoding();
boolean fHtml = false;
while (xmlStreamReader.hasNext()) {
int eventType = xmlStreamReader.next();
if (eventType == XMLStreamConstants.START_ELEMENT) {
if (xmlStreamReader.getLocalName().equals("html"))
fHtml = true;
break;
}
}
xmlStreamReader.close();
if (fHtml) {
String html = new String(ab, fileEncoding);
// System.out.println(html);
ab = new Html2Pdf().converter(html, false);
info = contentInfoUtil.findMimeTypeMatch("application/pdf");
}
}
if (info.getMimeType().startsWith("text/html")) {
String html = new String(ab, StandardCharsets.UTF_8);
if (html.toLowerCase().contains("charset=windows-1252") || html.toLowerCase().contains("iso-8859-1"))
html = new String(ab, StandardCharsets.ISO_8859_1);
// System.out.println(html);
ab = new Html2Pdf().converter(html, false);
info = contentInfoUtil.findMimeTypeMatch("application/pdf");
}
if (!"application/pdf".equals(info.getMimeType()))
throw new PresentableException("Não foi possível obter um PDF. (" + info.getMimeType() + ")");
reader = new PdfReader(ab);
copy.addDocument(reader);
reader.close();
}
document.close();
resp.contentdisposition = disposition + ";filename=" + numProc + "-completo.pdf";
resp.contentlength = (long) new File(bufName).length();
resp.contenttype = "application/pdf";
resp.inputstream = new FileInputStream(bufName);
}
}
}
use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.
the class BalcaojusServlet method invoke.
@Override
public void invoke(SwaggerContext context) throws Exception {
try {
if (!context.getAction().getClass().isAnnotationPresent(AcessoPublico.class)) {
try {
principal.set(AutenticarPost.assertUsuario());
} catch (Exception e) {
if (!context.getAction().getClass().isAnnotationPresent(AcessoPublicoEPrivado.class))
throw e;
}
if (principal.get() != null) {
Map<String, Object> decodedToken = AutenticarPost.assertUsuarioAutorizado();
final long now = System.currentTimeMillis() / 1000L;
if ((Integer) decodedToken.get("exp") < now + JWT_AUTH_COOKIE_TIME_TO_RENEW_IN_S) {
// Seria bom incluir o attributo HttpOnly
String tokenNew = AutenticarPost.renew();
Cookie cookie = AutenticarPost.buildCookie(tokenNew);
context.getResponse().addCookie(cookie);
}
}
}
super.invoke(context);
} catch (AcessoProibidoException e) {
AutenticarPost.informarProibido(context.getResponse(), e);
return;
} catch (JWTVerifyException e) {
if ("jwt expired".equals(e.getMessage()))
AutenticarPost.informarNaoAutenticado(context.getResponse(), e);
else
throw new RuntimeException(e);
} catch (AcessoInvalidoException e) {
AutenticarPost.informarNaoAutenticado(context.getResponse(), e);
return;
} finally {
principal.remove();
}
}
Aggregations