From 216b878529b7b7f0b93244fa74a64d8e0c0c0725 Mon Sep 17 00:00:00 2001 From: Gleimar Botelho Baleeiro Date: Tue, 14 Nov 2023 17:16:28 -0300 Subject: [PATCH] =?UTF-8?q?Implementa=C3=A7=C3=A3o=20do=20fluxo=20de=20aut?= =?UTF-8?q?oriza=C3=A7=C3=A3o=20para=20novas=20empresas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 4 +- .../catalogos/EditarEmpresaController.java | 61 +++++++- .../ventaboletos/web/utilerias/MyAppInit.java | 13 ++ .../web/utilerias/security/AESGSMHelper.java | 106 ------------- .../security/SecurityEmpresaToken.java | 140 ------------------ web/WEB-INF/i3-label_pt_BR.label | 5 + web/gui/catalogos/editarEmpresa.zul | 41 +++-- 7 files changed, 110 insertions(+), 260 deletions(-) delete mode 100644 src/java/com/rjconsultores/ventaboletos/web/utilerias/security/AESGSMHelper.java delete mode 100644 src/java/com/rjconsultores/ventaboletos/web/utilerias/security/SecurityEmpresaToken.java diff --git a/pom.xml b/pom.xml index 5220d9f91..28a4d96a2 100644 --- a/pom.xml +++ b/pom.xml @@ -8,8 +8,8 @@ war - 1.18.0 - 1.16.0 + 1.19.1 + 1.17.0 UTF-8 UTF-8 diff --git a/src/java/com/rjconsultores/ventaboletos/web/gui/controladores/catalogos/EditarEmpresaController.java b/src/java/com/rjconsultores/ventaboletos/web/gui/controladores/catalogos/EditarEmpresaController.java index c83b8508f..687a2fa48 100644 --- a/src/java/com/rjconsultores/ventaboletos/web/gui/controladores/catalogos/EditarEmpresaController.java +++ b/src/java/com/rjconsultores/ventaboletos/web/gui/controladores/catalogos/EditarEmpresaController.java @@ -134,6 +134,7 @@ import com.rjconsultores.ventaboletos.web.utilerias.render.RenderComEmpTipoEvent import com.rjconsultores.ventaboletos.web.utilerias.render.RenderEmpresaContaBancaria; import com.rjconsultores.ventaboletos.web.utilerias.render.RenderEmpresaImposto; import com.rjconsultores.ventaboletos.web.utilerias.render.RenderEmpresaInscricaoEstadual; +import com.rjconsultores.ventaboletos.web.utilerias.security.SecurityEmpresaToken; /** * @@ -465,6 +466,12 @@ public class EditarEmpresaController extends MyGenericForwardComposer { private Textbox txtLatitudeLongitude; private Textbox txtLatitude; private Textbox txtLongitude; + + private Textbox txtTokenRJ; + private Textbox txtLicenca; + private Button btnDigitarLicenca; + private Button btnValidarLicenca; + private boolean cadastroEmpresaNova = false; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; @@ -517,6 +524,8 @@ public class EditarEmpresaController extends MyGenericForwardComposer { if (empresa.getEmpresaId() == null) { btnAdicionarEstadoImposto.setVisible(false); btnAdicionarInscEstadual.setVisible(false); + + cadastroEmpresaNova = true; } else { btnAdicionarEstadoImposto.setVisible(true); @@ -825,6 +834,28 @@ public class EditarEmpresaController extends MyGenericForwardComposer { ajustarRadioAbaRateioComissao(); } + public void onClick$btnDigitarLicenca(Event ev) { + txtLicenca.setDisabled(false); + } + public void onClick$btnValidarLicenca(Event ev) throws InterruptedException { + + String tokenLicensa = empresaService.validarTokenLicensa(empresa,txtLicenca.getText()); + + if (StringUtils.isNotBlank(tokenLicensa)){ + txtLicenca.setText(tokenLicensa); + txtLicenca.setDisabled(true); + btnValidarLicenca.setDisabled(true); + btnDigitarLicenca.setDisabled(true); + empresa.setLicenca(tokenLicensa); + + Messagebox.show(Labels.getLabel("editarEmpresaController.MSG.licencaOK"), + Labels.getLabel("editarEmpresaController.window.title"), Messagebox.OK, Messagebox.INFORMATION); + }else{ + txtLicenca.setText(""); + Messagebox.show(Labels.getLabel("editarEmpresaController.MSG.licencaNOK"), + Labels.getLabel("editarEmpresaController.window.title"), Messagebox.OK, Messagebox.ERROR); + } + } public void onClick$chkAutenticacao(Event ev) { if(chkAutenticacao.isChecked()){ textEmail.setDisabled(false); @@ -899,7 +930,11 @@ public class EditarEmpresaController extends MyGenericForwardComposer { openWindow("/gui/catalogos/editarContaBancariaEmpresa.zul", Labels.getLabel("editarEmpresaController.contaBancaria.window.title"), args, MyGenericForwardComposer.MODAL); } - + + public void onClick$btnGerarToken(Event ev) throws InterruptedException { + txtTokenRJ.setText(empresaService.token(empresa)); + } + public void onClick$btnSalvar(Event ev) throws InterruptedException { txtNome.getValue(); cmbIndTipo.getValue(); @@ -1266,6 +1301,25 @@ public class EditarEmpresaController extends MyGenericForwardComposer { Messagebox.show(Labels.getLabel("editarEmpresaController.MSG.suscribirOK"), Labels.getLabel("editarEmpresaController.window.title"), Messagebox.OK, Messagebox.INFORMATION); + + + + if (cadastroEmpresaNova){ + Messagebox.show( + Labels.getLabel("editarEmpresaController.MSG.tokenNovaEmpresaOK", new String[] {empresa.getToken()}), + Labels.getLabel("editarEmpresaController.window.title"), + Messagebox.OK, Messagebox.EXCLAMATION); + }else{ + + List lsEmpresa = Arrays.asList(new Empresa[]{empresa}); + if (empresaService.filtrarApenasEmpresasLicencaValida(lsEmpresa).isEmpty()){ + Messagebox.show( + Labels.getLabel("editarEmpresaController.MSG.licencaNOK"), + Labels.getLabel("editarEmpresaController.window.title"), + Messagebox.OK, Messagebox.EXCLAMATION); + } + + } closeWindow(); @@ -2854,4 +2908,9 @@ public void onClick$btnTestEmailFlexBus(Event ev) throws InterruptedException { public void setHoraFimEmbarque(Timebox horaFimEmbarque) { this.horaFimEmbarque = horaFimEmbarque; } + + public boolean isExibeDadosTokenLicenca() { + return !cadastroEmpresaNova; + } + } diff --git a/src/java/com/rjconsultores/ventaboletos/web/utilerias/MyAppInit.java b/src/java/com/rjconsultores/ventaboletos/web/utilerias/MyAppInit.java index 7b878bf9e..8b206425e 100644 --- a/src/java/com/rjconsultores/ventaboletos/web/utilerias/MyAppInit.java +++ b/src/java/com/rjconsultores/ventaboletos/web/utilerias/MyAppInit.java @@ -29,6 +29,7 @@ import org.zkoss.zk.ui.WebApp; import com.rjconsultores.ventaboletos.FlyWay; import com.rjconsultores.ventaboletos.entidad.Constante; import com.rjconsultores.ventaboletos.service.ConstanteService; +import com.rjconsultores.ventaboletos.service.EmpresaService; import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties; import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionConferenciaMovimentoJob; import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionCorridaJob; @@ -105,6 +106,8 @@ public class MyAppInit implements org.zkoss.zk.ui.util.WebAppInit { customToDatabase(); imageToDatabase(); } + + this.atualizarLicencaPrimeiraVez(); } @@ -434,4 +437,14 @@ public class MyAppInit implements org.zkoss.zk.ui.util.WebAppInit { ConstanteService cs = (ConstanteService) factory.getBean("constanteService"); return cs; } + + private void atualizarLicencaPrimeiraVez(){ + ApplicationContext appContext = AppContext.getApplicationContext(); + BeanFactory factory = (BeanFactory) appContext; + EmpresaService es = (EmpresaService) factory.getBean("empresaService"); + + Integer cantLicencaEmpresasPrimeiraVez = es.atualizarLicencaEmpresasPrimeiraVez(); + + log.info(String.format("cantLicencaEmpresasPrimeiraVez: %s", cantLicencaEmpresasPrimeiraVez)); + } } diff --git a/src/java/com/rjconsultores/ventaboletos/web/utilerias/security/AESGSMHelper.java b/src/java/com/rjconsultores/ventaboletos/web/utilerias/security/AESGSMHelper.java deleted file mode 100644 index bc7f43653..000000000 --- a/src/java/com/rjconsultores/ventaboletos/web/utilerias/security/AESGSMHelper.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.rjconsultores.ventaboletos.web.utilerias.security; - -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; - -import javax.crypto.Cipher; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; - -public class AESGSMHelper { - private final String SECRET_KEY = "RJ@2019#c0n5ul10r35"; - private final String SALT = "HrqoFr44GtkAhhYN+jP8Ag=="; - private final String ENCRYPT_ALGO = "AES/GCM/NoPadding"; - private final int TAG_LENGTH_BIT = 128; - private final int IV_LENGTH_BYTE = 12; - - private final Charset UTF_8 = StandardCharsets.UTF_8; - - public String encrypt(String value) throws Exception { - SecretKey secret = getAESKeyFromPassword(SECRET_KEY.toCharArray()); - - byte[] pText = value.getBytes(StandardCharsets.UTF_8); - byte[] iv = getRandomNonce(12); - byte[] cipherText = encrypt(pText, secret, iv); - - byte[] cipherTextWithIv = ByteBuffer.allocate(iv.length + cipherText.length) - .put(iv) - .put(cipherText) - .array(); - - return hex(cipherTextWithIv); - } - - private byte[] encrypt(byte[] pText, SecretKey secret, byte[] iv) throws Exception { - Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO); - cipher.init(Cipher.ENCRYPT_MODE, secret, new GCMParameterSpec(TAG_LENGTH_BIT, iv)); - - byte[] encryptedText = cipher.doFinal(pText); - - return encryptedText; - - } - - public String decrypt(String value) throws Exception { - SecretKey secret = getAESKeyFromPassword(SECRET_KEY.toCharArray()); - - byte[] cText = unhex(value); - - ByteBuffer bb = ByteBuffer.wrap(cText); - - byte[] iv = new byte[IV_LENGTH_BYTE]; - bb.get(iv); - - byte[] cipherText = new byte[bb.remaining()]; - bb.get(cipherText); - - String plainText = decrypt(cipherText, secret, iv); - - return plainText; - } - - private String decrypt(byte[] cText, SecretKey secret, byte[] iv) throws Exception { - Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO); - cipher.init(Cipher.DECRYPT_MODE, secret, new GCMParameterSpec(TAG_LENGTH_BIT, iv)); - - byte[] plainText = cipher.doFinal(cText); - - return new String(plainText, UTF_8); - } - - private byte[] getRandomNonce(int numBytes) { - byte[] nonce = new byte[numBytes]; - new SecureRandom().nextBytes(nonce); - - return nonce; - } - - private SecretKey getAESKeyFromPassword(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { - SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); - - KeySpec spec = new PBEKeySpec(password, SALT.getBytes(), 65536, 256); - SecretKeySpec secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); - - return secret; - } - - private String hex(byte[] bytes) { - char[] result = Hex.encodeHex(bytes); - return new String(result); - } - - private byte[] unhex(String hex) throws DecoderException { - return Hex.decodeHex(hex.toCharArray()); - } -} diff --git a/src/java/com/rjconsultores/ventaboletos/web/utilerias/security/SecurityEmpresaToken.java b/src/java/com/rjconsultores/ventaboletos/web/utilerias/security/SecurityEmpresaToken.java deleted file mode 100644 index 3fe1f432c..000000000 --- a/src/java/com/rjconsultores/ventaboletos/web/utilerias/security/SecurityEmpresaToken.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.rjconsultores.ventaboletos.web.utilerias.security; - -import java.text.ParseException; -import java.time.Duration; -import java.util.Calendar; - -import javax.xml.bind.DatatypeConverter; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.crypto.MACSigner; -import com.nimbusds.jwt.JWTClaimsSet; - -import net.minidev.json.JSONObject; - -public class SecurityEmpresaToken { - private static Logger log = Logger.getLogger(SecurityEmpresaToken.class); - - private String secret = "#KO&Fm4_k.sU9M8`6Mx'F\\\"H:*Qxu]6F4r,)JmZ2Jwafd)I.2[RET'1:)VQ6mG9,"; - private static final Duration ttl = Duration.ofDays(7); - - private Gson gson = new Gson(); - - public String bodyRequestGenerate(final Integer empresaId, final String cnpj) throws SecurityException { - try { - AESGSMHelper crypto = new AESGSMHelper(); - - JsonObject json = new JsonObject(); - json.addProperty("empresaId", empresaId); - json.addProperty("CNPJ", cnpj); - - return crypto.encrypt(json.toString()); - - } catch (Exception e) { - log.error("Erro ao gerar o body usado no request da licença: " + e.getMessage(), e); - - throw new SecurityException(e); - } - } - - public String licenseDefaultGenerate(final Integer empresaId, final String cnpj) throws SecurityException { - try { - AESGSMHelper crypto = new AESGSMHelper(); - - JsonObject json = new JsonObject(); - json.addProperty("empresaId", empresaId); - json.addProperty("CNPJ", cnpj); - json.addProperty("aprovado", 1); - - return crypto.encrypt(json.toString()); - - } catch (Exception e) { - log.error("Erro ao gerar a licença padrão para as empresas existentes: " + e.getMessage(), e); - - throw new SecurityException(e); - } - } - - public boolean licenseValidate(final String license, final Integer empresaId, final String cnpj) { - try { - AESGSMHelper crypto = new AESGSMHelper(); - - final String value = crypto.decrypt(license); - final JsonObject json = gson.fromJson(value, JsonObject.class); - - if (json.has("empresaId") && json.get("empresaId").getAsInt() == empresaId.intValue() - && json.has("CNPJ") && json.get("CNPJ").getAsString().equals(cnpj) - && json.has("aprovado")) { - log.debug("[empresaId=" + json.get("empresaId").getAsString() + ", CNPJ=" + json.get("CNPJ").getAsString() + ", aprovado=" + json.get("aprovado").getAsString() + "]"); - - return json.get("aprovado").getAsString().equals("1"); - } - } catch (Exception e) { - log.error("Erro ao gerar o body usado no request da licença: " + e.getMessage(), e); - } - - return false; - } - - public String requestGenerate(String licenseRequest) throws SecurityException { - return requestGenerate(licenseRequest, ttl); - } - - public String requestGenerate(String licenseRequest, Duration ttl) throws SecurityException { - try { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.MILLISECOND, (int) ttl.toMillis()); - - JWTClaimsSet claims = new JWTClaimsSet.Builder() - .expirationTime(cal.getTime()) - .claim("sub", licenseRequest) - .claim("userId", "adm") - .claim("role", "ROLE_TOKEN") - .build(); - - JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload(claims.toJSONObject())); - - jwsObject.sign(new MACSigner(DatatypeConverter.parseBase64Binary(secret))); - - return jwsObject.serialize(); - } catch (Exception e) { - log.error("Erro ao gerar a request: " + e.getMessage(), e); - - throw new SecurityException(e); - } - } - - public String tokenValidate(final String token) throws SecurityException { - try { - JWSObject jwsObject = JWSObject.parse(token); - JSONObject jsonPayload = jwsObject.getPayload().toJSONObject(); - JWTClaimsSet claims = JWTClaimsSet.parse(jsonPayload); - - if (claims.getExpirationTime().compareTo(Calendar.getInstance().getTime()) < 0) { - throw new SecurityException("Token expirado"); - } - - return claims.getSubject(); - - } catch (SecurityException e) { - throw e; - - } catch (ParseException e) { - log.error("Erro no parser do token: " + e.getMessage(), e); - - throw new SecurityException(e); - - } catch (Exception e) { - log.error("Erro ao validar o token: " + e.getMessage(), e); - - throw new SecurityException(e); - } - } -} diff --git a/web/WEB-INF/i3-label_pt_BR.label b/web/WEB-INF/i3-label_pt_BR.label index 61b9e8025..1ffc9b013 100644 --- a/web/WEB-INF/i3-label_pt_BR.label +++ b/web/WEB-INF/i3-label_pt_BR.label @@ -1740,6 +1740,9 @@ editarEmpresaController.lbNome.value = Descrição editarEmpresaController.lbConfiguraciones.value = Configurações editarEmpresaController.lbActivo.value = Ativo editarEmpresaController.MSG.suscribirOK = Empresa Registrada com Sucesso. +editarEmpresaController.MSG.tokenNovaEmpresaOK = Para que a Empresa cadastrada possa ser utilizada no sistema, favor acionar o Suporte com o seguinte TOKEN: {0} +editarEmpresaController.MSG.licencaNOK = Licença Informada não é válida. A empresa não ficará disponível para utilização. Favor entrar em contato com o Suporte. +editarEmpresaController.MSG.licencaOK = Licença validada. editarEmpresaController.MSG.borrarPergunta = Deseja Eliminar esta empresa? editarEmpresaController.MSG.borrarOK = Empresa Excluida com Sucesso. editarEmpresaController.MSG.insEstadualCadastrada = Já existe uma inscrição estadual para este estado. @@ -1860,6 +1863,8 @@ editarEmpresaController.cst00.label = CST=00 (Tribuitação Normal) editarEmpresaController.cst40.label = CST=40 (Isento) editarEmpresaController.cst41.label = CST=41 (Não Tributado) editarEmpresaController.codContPrevidencia.label = Código Indicador de Contribuição Previdenciária +editarEmpresaController.tokenEmpresa.label = Token para Licença +editarEmpresaController.tokenLicenca.label = Licença editarEmpresaController.lbInscricaoMunicipal.value =Inscrição Municipal editarEmpresaController.label.isento = ISENTO editarEmpresaController.lbInscricaoMunicipal.label =Insc.Municipal diff --git a/web/gui/catalogos/editarEmpresa.zul b/web/gui/catalogos/editarEmpresa.zul index 8f844a78f..4c50e1b2e 100644 --- a/web/gui/catalogos/editarEmpresa.zul +++ b/web/gui/catalogos/editarEmpresa.zul @@ -166,24 +166,43 @@ - - + + - + + +