Merge pull request 'security' (!311) from security into master

Reviewed-on: adm/VentaBoletosAdm#311
Reviewed-by: Valdir Cordeiro <valdir.cordeiro@totvs.com.br>
master
Valdir Cordeiro 2023-11-16 13:44:09 +00:00
commit 3cca5d76d9
8 changed files with 250 additions and 15 deletions

15
pom.xml
View File

@ -4,12 +4,12 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>br.com.rjconsultores</groupId> <groupId>br.com.rjconsultores</groupId>
<artifactId>ventaboletosadm</artifactId> <artifactId>ventaboletosadm</artifactId>
<version>1.30.1</version> <version>1.31.0</version>
<packaging>war</packaging> <packaging>war</packaging>
<properties> <properties>
<modelWeb.version>1.21.0</modelWeb.version> <modelWeb.version>1.22.0</modelWeb.version>
<flyway.version>1.18.0</flyway.version> <flyway.version>1.19.0</flyway.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties> </properties>
@ -32,6 +32,15 @@
</excludes> </excludes>
</resource> </resource>
</resources> </resources>
<testSourceDirectory>tests</testSourceDirectory>
<testResources>
<testResource>
<directory>tests</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>

View File

@ -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.RenderEmpresaContaBancaria;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderEmpresaImposto; import com.rjconsultores.ventaboletos.web.utilerias.render.RenderEmpresaImposto;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderEmpresaInscricaoEstadual; 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 txtLatitudeLongitude;
private Textbox txtLatitude; private Textbox txtLatitude;
private Textbox txtLongitude; 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-]+)*@" 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,})$"; + "[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) { if (empresa.getEmpresaId() == null) {
btnAdicionarEstadoImposto.setVisible(false); btnAdicionarEstadoImposto.setVisible(false);
btnAdicionarInscEstadual.setVisible(false); btnAdicionarInscEstadual.setVisible(false);
cadastroEmpresaNova = true;
} else { } else {
btnAdicionarEstadoImposto.setVisible(true); btnAdicionarEstadoImposto.setVisible(true);
@ -825,6 +834,28 @@ public class EditarEmpresaController extends MyGenericForwardComposer {
ajustarRadioAbaRateioComissao(); 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) { public void onClick$chkAutenticacao(Event ev) {
if(chkAutenticacao.isChecked()){ if(chkAutenticacao.isChecked()){
textEmail.setDisabled(false); textEmail.setDisabled(false);
@ -899,7 +930,11 @@ public class EditarEmpresaController extends MyGenericForwardComposer {
openWindow("/gui/catalogos/editarContaBancariaEmpresa.zul", openWindow("/gui/catalogos/editarContaBancariaEmpresa.zul",
Labels.getLabel("editarEmpresaController.contaBancaria.window.title"), args, MyGenericForwardComposer.MODAL); 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 { public void onClick$btnSalvar(Event ev) throws InterruptedException {
txtNome.getValue(); txtNome.getValue();
cmbIndTipo.getValue(); cmbIndTipo.getValue();
@ -1266,6 +1301,25 @@ public class EditarEmpresaController extends MyGenericForwardComposer {
Messagebox.show(Labels.getLabel("editarEmpresaController.MSG.suscribirOK"), Messagebox.show(Labels.getLabel("editarEmpresaController.MSG.suscribirOK"),
Labels.getLabel("editarEmpresaController.window.title"), Labels.getLabel("editarEmpresaController.window.title"),
Messagebox.OK, Messagebox.INFORMATION); 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<Empresa> 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(); closeWindow();
@ -2854,4 +2908,9 @@ public void onClick$btnTestEmailFlexBus(Event ev) throws InterruptedException {
public void setHoraFimEmbarque(Timebox horaFimEmbarque) { public void setHoraFimEmbarque(Timebox horaFimEmbarque) {
this.horaFimEmbarque = horaFimEmbarque; this.horaFimEmbarque = horaFimEmbarque;
} }
public boolean isExibeDadosTokenLicenca() {
return !cadastroEmpresaNova;
}
} }

View File

@ -29,6 +29,7 @@ import org.zkoss.zk.ui.WebApp;
import com.rjconsultores.ventaboletos.FlyWay; import com.rjconsultores.ventaboletos.FlyWay;
import com.rjconsultores.ventaboletos.entidad.Constante; import com.rjconsultores.ventaboletos.entidad.Constante;
import com.rjconsultores.ventaboletos.service.ConstanteService; import com.rjconsultores.ventaboletos.service.ConstanteService;
import com.rjconsultores.ventaboletos.service.EmpresaService;
import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties; import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties;
import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionConferenciaMovimentoJob; import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionConferenciaMovimentoJob;
import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionCorridaJob; import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionCorridaJob;
@ -105,6 +106,8 @@ public class MyAppInit implements org.zkoss.zk.ui.util.WebAppInit {
customToDatabase(); customToDatabase();
imageToDatabase(); imageToDatabase();
} }
this.atualizarLicencaPrimeiraVez();
} }
@ -434,4 +437,14 @@ public class MyAppInit implements org.zkoss.zk.ui.util.WebAppInit {
ConstanteService cs = (ConstanteService) factory.getBean("constanteService"); ConstanteService cs = (ConstanteService) factory.getBean("constanteService");
return cs; 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));
}
} }

View File

@ -0,0 +1,13 @@
package com.rjconsultores.ventaboletos.web.utilerias.security.exception;
public class SecurityException extends Exception {
private static final long serialVersionUID = 1801174850577435303L;
public SecurityException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public SecurityException(String arg0) {
super(arg0);
}
}

View File

@ -0,0 +1,117 @@
package com.rjconsultores.tests;
import static org.junit.Assert.fail;
import java.time.Duration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.rjconsultores.ventaboletos.web.utilerias.security.SecurityEmpresaToken;
public class SecurityEmpresaTokenTest {
private static final Logger log = LoggerFactory.getLogger(SecurityEmpresaTokenTest.class);
@Before
public void initApplicationContext() {
log.info("[ BEGIN ]");
}
@After
public void closeApplicationContext() {
log.info("[ END ]");
}
@Test
public void test_Token() throws Exception {
// license request -> token request -> token response -> license
Integer empresaId = 1313;
String cnpj = "00073778000120";
SecurityEmpresaToken security = new SecurityEmpresaToken();
final String bodyRequest = security.bodyRequestGenerate(empresaId, cnpj);
final String request = security.requestGenerate(bodyRequest);
final String reponse = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI4ZTY2MGVmOTQwMGRlNjU2MmQ1MjljZTVkZDMyZDU0NmM2OGU5YTk0NTUwYjUyNzc4MDhjNWIxMjgzNzkwNjVlNzI0NWU2ZTMxNzBjMTQ2ZGVlOWUyNGQwZjc1YzMwYTVmM2JlYmY5NjY0YzZiNWNiYjU3NTk1NzVmOGYzMTk4OTljNmVmODNkZDc3NmI4YjM2MGM1NDE3N2RhMzFkMDAzNTA5ZDFlIiwiZXhwIjoxNjk5NjQ5OTQ1LCJ1c2VySWQiOiJhZG0iLCJyb2xlIjoiUk9MRV9UT0tFTiJ9.0WFPKf6RcpPYle4Rgq_D-GScwhkw_Q4pmCvNCL_INfg";
final String license = security.tokenValidate(reponse);
final boolean valid = security.licenseValidate(license, empresaId, cnpj);
log.info("Body Request: " + bodyRequest);
log.info("Request: " + request);
log.info("License: " + license);
log.info("Valid: " + Boolean.toString(valid));
if (!valid) fail("Licença inválida");
}
@Test
public void test_EmpresaNova() throws Exception {
// license request -> token request -> token response -> license
Integer empresaId = 1313;
String cnpj = "00073778000120";
SecurityEmpresaToken security = new SecurityEmpresaToken();
final String bodyRequest = security.bodyRequestGenerate(empresaId, cnpj);
final String request = security.requestGenerate(bodyRequest);
final String license = security.tokenValidate(request);
final boolean valid = security.licenseValidate(license, empresaId, cnpj);
log.info("Body Request: " + bodyRequest);
log.info("Request: " + request);
log.info("License: " + license);
log.info("Valid: " + Boolean.toString(valid));
if (valid) fail("Licença válida");
}
@Test
public void test_Licenca() throws Exception {
Integer empresaId = 1313;
String cnpj = "00073778000120";
SecurityEmpresaToken security = new SecurityEmpresaToken();
final String license = security.licenseDefaultGenerate(empresaId, cnpj);
final boolean valid = security.licenseValidate(license, empresaId, cnpj);
log.info("License: " + license);
log.info("Valid: " + Boolean.toString(valid));
if (!valid) fail("Licença inválida");
}
@Test(expected = SecurityException.class)
public void test_TTL_expired() throws Exception {
Duration ttl = Duration.ofSeconds(5);
Integer empresaId = 1313;
String cnpj = "00073778000120";
SecurityEmpresaToken security = new SecurityEmpresaToken();
final String bodyRequest = security.bodyRequestGenerate(empresaId, cnpj);
final String request = security.requestGenerate(bodyRequest, ttl);
log.info("Body Request: " + bodyRequest);
log.info("Request: " + request);
Thread.sleep(Duration.ofSeconds(10).toMillis());
final String license = security.tokenValidate(request);
final boolean valid = security.licenseValidate(license, empresaId, cnpj);
log.info("License: " + license);
log.info("Valid: " + Boolean.toString(valid));
if (valid) fail("Licença válida");
}
}

View File

@ -1740,6 +1740,9 @@ editarEmpresaController.lbNome.value = Descrição
editarEmpresaController.lbConfiguraciones.value = Configurações editarEmpresaController.lbConfiguraciones.value = Configurações
editarEmpresaController.lbActivo.value = Ativo editarEmpresaController.lbActivo.value = Ativo
editarEmpresaController.MSG.suscribirOK = Empresa Registrada com Sucesso. 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.borrarPergunta = Deseja Eliminar esta empresa?
editarEmpresaController.MSG.borrarOK = Empresa Excluida com Sucesso. editarEmpresaController.MSG.borrarOK = Empresa Excluida com Sucesso.
editarEmpresaController.MSG.insEstadualCadastrada = Já existe uma inscrição estadual para este estado. 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.cst40.label = CST=40 (Isento)
editarEmpresaController.cst41.label = CST=41 (Não Tributado) editarEmpresaController.cst41.label = CST=41 (Não Tributado)
editarEmpresaController.codContPrevidencia.label = Código Indicador de Contribuição Previdenciária 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.lbInscricaoMunicipal.value =Inscrição Municipal
editarEmpresaController.label.isento = ISENTO editarEmpresaController.label.isento = ISENTO
editarEmpresaController.lbInscricaoMunicipal.label =Insc.Municipal editarEmpresaController.lbInscricaoMunicipal.label =Insc.Municipal

View File

@ -166,24 +166,43 @@
</row> </row>
<row> <row>
<hlayout> <hlayout>
<label <label
value="${c:l('editarEmpresaController.cpfCnpjAutorizadoDownload.label')}" /> value="${c:l('editarEmpresaController.cpfCnpjAutorizadoDownload.label')}" />
<image src="/gui/img/Question_mark_1.png" tooltiptext="${c:l('editarEmpresaController.cpfCnpjAutorizadoDownload.ajuda')}" <image src="/gui/img/Question_mark_1.png" tooltiptext="${c:l('editarEmpresaController.cpfCnpjAutorizadoDownload.ajuda')}"
style="cursor: help" /> style="cursor: help" />
</hlayout> </hlayout>
<textbox id="txtCpfCnpj_AutorizadoDowload" width="150px" type="text" <textbox id="txtCpfCnpj_AutorizadoDowload" width="150px" type="text"
value="@{winEditarEmpresa$composer.empresa.cpfCnpjAutDownload}" value="@{winEditarEmpresa$composer.empresa.cpfCnpjAutDownload}"
use="com.rjconsultores.ventaboletos.web.utilerias.MyTextbox" /> use="com.rjconsultores.ventaboletos.web.utilerias.MyTextbox" />
</row> </row>
<row> <row visible="@{winEditarEmpresa$composer.exibeDadosTokenLicenca}">
<label <label
value="${c:l('editarEmpresaController.codContPrevidencia.label')}" /> value="${c:l('editarEmpresaController.tokenEmpresa.label')}" />
<textbox id="txtCodContPrevidencia" width="150px" type="text"
maxlength="8" <textbox id="txtTokenRJ" width="650px" type="text" readonly="true"
value="@{winEditarEmpresa$composer.empresa.codContPrevidencia}"/> value="@{winEditarEmpresa$composer.empresa.token}"/>
</row>
<row visible="@{winEditarEmpresa$composer.exibeDadosTokenLicenca}">
<label value="${c:l('editarEmpresaController.tokenLicenca.label')}" />
<hlayout>
<textbox id="txtLicenca" width="550px" type="text" value="@{winEditarEmpresa$composer.empresa.licenca}" disabled="true" />
<button
id="btnDigitarLicenca" height="20"
width="55px"
label="Digitar Licença"/>
<button
id="btnValidarLicenca" height="20"
width="55px"
label="Validar Licença"/>
</hlayout>
</row> </row>
</rows> </rows>
</grid> </grid>