package br.com.ec.controller.seguranca;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.StringTokenizer;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import br.com.ec.core.util.VerificadorUtil;
import br.com.ec.domain.model.Loja;
import br.com.ec.domain.model.Parametro;
import br.com.ec.domain.model.Usuario;
import br.com.ec.domain.model.UsuarioLoja;
import br.com.ec.domain.model.tipos.TipoAno;
import br.com.ec.domain.model.tipos.TipoMes;
import br.com.ec.domain.service.perfil.PerfilService;
import br.com.ec.domain.service.seguranca.ContextoSeguranca;
import br.com.ec.domain.service.usuario.UsuarioService;
import br.com.ec.domain.shared.ConstantesSEC;
import br.com.ec.web.exception.VerificadorLancamentoException;
import br.com.ec.web.exception.VerificadorLancamentoException.CommandBean;
import br.com.ec.web.message.LancadorMensagem;
@Named
@Scope
("view")
public class SegurancaBean
implements Serializable{
private static final long serialVersionUID = 1L
;
private ContextoSeguranca contextoSeguranca
;
private Usuario usuario
;
private String novaSenha
;
private UsuarioService usuarioService
;
private PerfilService perfilService
;
@Inject
public SegurancaBean
(ContextoSeguranca contextoSeguranca, UsuarioService usuarioService, PerfilService perfilService
) {
this.
contextoSeguranca = contextoSeguranca
;
this.
usuarioService = usuarioService
;
this.
perfilService = perfilService
;
}
public ContextoSeguranca getContextoSeguranca
() {
return contextoSeguranca
;
}
public void setContextoSeguranca
(ContextoSeguranca contextoSeguranca
) {
this.
contextoSeguranca = contextoSeguranca
;
}
public Usuario getUsuario
() {
if (usuario ==
null) {
setUsuario
(contextoSeguranca.
obterUsuario());
}
return usuario
;
}
public void setUsuario
(Usuario usuario
) {
this.
usuario = usuario
;
}
public String getNovaSenha
() {
return novaSenha
;
}
public void setNovaSenha
(String novaSenha
) {
this.
novaSenha = novaSenha
;
}
/************************************************************************/
public Boolean temPerfilAdministrador
() {
return perfilService.
temPerfilAdministrador(getUsuario
());
}
public Boolean temPerfilGerenteAdministrativo
() {
return perfilService.
temPerfilGerenteAdministrativo(getUsuario
());
}
/************************************************************************/
public Boolean temPerfilFinanceiro
() {
return perfilService.
temPerfilFinanceiro(getUsuario
());
}
public Boolean temPerfilComercial
() {
return perfilService.
temPerfilComercial(getUsuario
());
}
public Boolean temPerfilLojistica
() {
return perfilService.
temPerfilLojistica(getUsuario
());
}
public Boolean temPerfilVendedor
() {
return perfilService.
temPerfilVendedor(getUsuario
());
}
public Boolean temPerfilCompras
() {
return perfilService.
temPerfilCompras(getUsuario
());
}
public Boolean temPerfilGerenteVivo
() {
return perfilService.
temPerfilGerenteVivo(getUsuario
());
}
public Boolean temPerfilTecnico
() {
return perfilService.
temPerfilTecnico(getUsuario
());
}
public Boolean temPerfilRecursosHumanos
() {
return perfilService.
temPerfilRecursosHumanos(getUsuario
());
}
public Boolean temPerfilOperacoes
() {
return perfilService.
temPerfilOperacoes(getUsuario
());
}
public Boolean temPerfilProducao
() {
return perfilService.
temPerfilProducao(getUsuario
());
}
public Boolean temPerfilSupervisor
() {
return perfilService.
temPerfilSupervisor(getUsuario
());
}
public Boolean temPerfilTreinamento
() {
return perfilService.
temPerfilTreinamento(getUsuario
());
}
public Boolean temPerfilLoja
() {
return perfilService.
temPerfilLoja(getUsuario
());
}
public Boolean temAcessoLoja
(Long sequencialLoja
) {
return temPerfilGerenteAdministrativo
() || verificarAcessoLoja
(getUsuario
(), sequencialLoja
);
}
public Boolean temAcessoLojaVivo
() {
return temPerfilGerenteAdministrativo
() || verificarAcessoLoja
(getUsuario
(), ConstantesSEC.
SEQUENCIAL_LOJA_VIVO_4);
}
public Boolean temAcessoLojaCasaDasCapas
() {
return temPerfilCompras
() || temPerfilComercial
() ||
(verificarAcessoLoja
(getUsuario
(), ConstantesSEC.
SEQUENCIAL_CASA_DAS_CAPAS_17) && temPerfilVendedor
());
}
public Boolean naoTemAcessoLojaCasaDasCapas
() {
return temPerfilCompras
() || temPerfilComercial
() ||
!(verificarAcessoLoja
(getUsuario
(), ConstantesSEC.
SEQUENCIAL_CASA_DAS_CAPAS_17) && temPerfilVendedor
());
}
private Boolean verificarAcessoLoja
(Usuario usuario,
Long sequencialLoja
) {
for (UsuarioLoja usuarioLoja : usuario.
getLojas()) {
if (usuarioLoja.
getLoja().
getSequencial().
equals(sequencialLoja
)) {
return true;
}
}
return false;
}
public void restaurarTelaPDV
(Loja loja
) throws IOException {
FacesContext.
getCurrentInstance().
getExternalContext().
redirect(FacesContext.
getCurrentInstance().
getExternalContext().
getRequestContextPath() +
"/sistema/pdv.xhtml?sequencialLoja=" + loja.
getSequencial());
}
public void restaurarTelaPDVVivo
(Loja loja
) throws IOException {
FacesContext.
getCurrentInstance().
getExternalContext().
redirect(FacesContext.
getCurrentInstance().
getExternalContext().
getRequestContextPath() +
"/sistema/pdv_vivo.xhtml?sequencialLoja=" + loja.
getSequencial());
}
public void restaurarTelaPDVFarma
(Loja loja
) throws IOException {
FacesContext.
getCurrentInstance().
getExternalContext().
redirect(FacesContext.
getCurrentInstance().
getExternalContext().
getRequestContextPath() +
"/sistema/pdv.xhtml?sequencialLoja=" + loja.
getSequencial());
}
public void invalidarSessao
() {
FacesContext.
getCurrentInstance().
getExternalContext().
invalidateSession();
}
public void alterarSenhaUsuario
() {
new VerificadorLancamentoException
().
tratarIhRelancarExcecaoSemLimparEntidade(new CommandBean
() {
public void execute
() {
getUsuario
().
setSenha(getNovaSenha
());
usuarioService.
alterarSenhaUsuario(getUsuario
());
setNovaSenha
("");
LancadorMensagem.
lancarSucesso("SENHA ALTERADA COM SUCESSO");
}
});
}
public Integer getTempoEstoqueMinimoParaComprasEmDias
() {
Parametro parametro =
new Parametro
();
parametro.
setCodigo(ConstantesSEC.
Parametro.
CODIGO_PARAMETRO_TEMPO_ESTOQUE_MINIMO_PARA_COMPRAS);
parametro = getUsuario
().
getParametros().
get(getUsuario
().
getParametros().
indexOf(parametro
));
return VerificadorUtil.
naoEstaNulo(parametro
)? new Integer(parametro.
getValor()) :
15;
}
public Integer getTempoEstoqueParaReporEmDias
() {
Parametro parametro =
new Parametro
();
parametro.
setCodigo(ConstantesSEC.
Parametro.
CODIGO_PARAMETRO_TEMPO_ESTOQUE_REPOSICAO_PARA_COMPRAS);
parametro = getUsuario
().
getParametros().
get(getUsuario
().
getParametros().
indexOf(parametro
));
return VerificadorUtil.
naoEstaNulo(parametro
)? new Integer(parametro.
getValor()) :
60;
}
public TipoAno
[] getTiposAno
() {
return TipoAno.
values();
}
public TipoMes
[] getTiposMes
() {
return TipoMes.
values();
}
public String textoSobreCorMargem
() {
return ConstantesSEC.
Textos.
TEXTO_COR_MARGEM;
}
/*
public FacesContext getContext() {
return FacesContext.getCurrentInstance();
}
private boolean verificarContexto() {
FacesContext context = getContext();
return VerificadorUtil.naoEstaNulo(context) && VerificadorUtil.naoEstaNulo(context.getExternalContext());
}
public HttpServletRequest getRequest() {
return verificarContexto() ? (HttpServletRequest) getContext().getExternalContext().getRequest() : null;
}
public HttpServletResponse getResponse() {
return verificarContexto() ? (HttpServletResponse) getContext().getExternalContext().getResponse() : null;
}
public String nomeMaquina() {
String nomeMaquina = "";
try {
nomeMaquina = InetAddress.getLocalHost().getHostName();
nomeMaquina = getRequest().getLocalName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return nomeMaquina;
}
public String ipMaquina() {
String ipMaquina = "";
try {
ipMaquina = InetAddress.getLocalHost().getHostAddress();
ipMaquina = getRequest().getLocalAddr();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ipMaquina;
}
public String ipMaquina2() {
String ipMaquina = "";
try {
ipMaquina = InetAddress.getLocalHost().getHostAddress();
// ipMaquina = getRequest().getRemoteAddr();
ipMaquina = getRequest().getHeader("X-FORWARDED-FOR");
if (ipMaquina == null) {
return getRequest().getRemoteAddr();
} else {
// As of https://en.wikipedia.org/wiki/X-Forwarded-For
// The general format of the field is: X-Forwarded-For: client, prox y1, proxy2 ...
// we only want the client
return new StringTokenizer(ipMaquina, ",").nextToken().trim();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ipMaquina;
}
public String ipMaquina3() {
String ipMaquina = "";
try {
ipMaquina = InetAddress.getLocalHost().getHostAddress();
// ipMaquina = getRequest().getRemoteHost();
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
StringBuilder macs = new StringBuilder("");
while (networks.hasMoreElements()) {
NetworkInterface network = networks.nextElement();
byte[] mac = network.getHardwareAddress();
if (mac != null) {
// System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format(
"%02X%s", mac[i],
(i < mac.length - 1) ? "-" : ""));
}
// MAC Address
// System.out.println(sb.toString());
macs.append(sb.toString());
macs.append("\n");
}
}
ipMaquina = macs.toString();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ipMaquina;
}
public String ipMaquina4() {
StringBuilder ipMaquina = new StringBuilder("");
try {
// ipMaquina = InetAddress.getLocalHost().getHostAddress();
ipMaquina.append("Informacoes");
ipMaquina.append("Sistema operacional: " + System.getProperty("os.name"));
ipMaquina.append("IP/Localhost: " + InetAddress.getLocalHost().getHostAddress());
ipMaquina.append("Nome da maquina: " + InetAddress.getLocalHost().getHostName());
ipMaquina.append("Nome completo da maquina: " + InetAddress.getLocalHost().getCanonicalHostName());
ipMaquina.append("Nome da maquina2: " + InetAddress.getLoopbackAddress().getHostName());
ipMaquina.append("Nome completo da maquina2: " + InetAddress.getLoopbackAddress().getCanonicalHostName());
ipMaquina.append("MAC Address: " + getMacAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ipMaquina.toString();
}
private final static String windowsParseMacAddress(String ipConfigResponse) throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
} catch(java.net.UnknownHostException ex) {
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
StringBuilder infor = new StringBuilder("");
while(tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken().trim();
infor.append(line);
infor.append("\n");
//IP
if(line.endsWith(localHost) && lastMacAddress != null) {
return lastMacAddress;
}
//MAC address
int macAddressPosition = line.indexOf(":");
if(macAddressPosition <= 0) continue;
String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
if(windowsIsMacAddress(macAddressCandidate)) {
lastMacAddress = macAddressCandidate;
continue;
}
}
return infor.toString();
// ParseException ex = new ParseException("Nao foi possÃvel ler o MAC address de [" + ipConfigResponse + "]", 0);
// ex.printStackTrace();
// throw ex;
}
private final static boolean windowsIsMacAddress(String macAddressCandidate) {
if(macAddressCandidate.length() != 17) return false;
return true;
}
private final static String windowsRunIpConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ipconfig /all");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer= new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1) break;
buffer.append((char)c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
private final static String getMacAddress() throws IOException {
try {
return windowsParseMacAddress(windowsRunIpConfigCommand());
} catch(ParseException ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
public final static void main(String[] args) {
try {
System.out.println("Informacoes");
System.out.println("Sistema operacional: " + System.getProperty("os.name"));
System.out.println("IP/Localhost: " + InetAddress.getLocalHost().getHostAddress());
System.out.println("Nome da maquina: " + InetAddress.getLocalHost().getHostName());
System.out.println("Nome completo da maquina: " + InetAddress.getLocalHost().getCanonicalHostName());
System.out.println("Nome da maquina2: " + InetAddress.getLoopbackAddress().getHostName());
System.out.println("Nome completo da maquina2: " + InetAddress.getLoopbackAddress().getCanonicalHostName());
System.out.println("MAC Address: " + getMacAddress());
// create an Enumeration of type
// NetworkInterface and store the values
// returned by
// NetworkInterface.getNetworkInterfaces()
// method
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
// for every network in the networks Enumeration
while (networks.hasMoreElements()) {
NetworkInterface network
= networks.nextElement();
// call getHardwareAddress() method on each
// network and store the returned value in a
// byte array
byte[] mac = network.getHardwareAddress();
if (mac != null) {
System.out.print(
"Current MAC address : ");
// convert the obtained byte array into
// a printable String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format(
"%02X%s", mac[i],
(i < mac.length - 1) ? "-"
: ""));
}
// print the final String containing the
// MAC Address
System.out.println(sb.toString());
}
}
} catch(Throwable t) {
t.printStackTrace();
}
}
*/
}