Subversion Repositories Integrator Subversion

Rev

Rev 356 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
106 espaco 1
package br.com.ec.controller.seguranca;
2
 
356 espaco 3
import java.io.BufferedInputStream;
106 espaco 4
import java.io.IOException;
356 espaco 5
import java.io.InputStream;
106 espaco 6
import java.io.Serializable;
356 espaco 7
import java.net.InetAddress;
8
import java.net.NetworkInterface;
9
import java.net.SocketException;
10
import java.net.UnknownHostException;
11
import java.text.ParseException;
12
import java.util.Enumeration;
13
import java.util.StringTokenizer;
106 espaco 14
 
15
import javax.faces.context.FacesContext;
16
import javax.inject.Inject;
17
import javax.inject.Named;
356 espaco 18
import javax.servlet.http.HttpServletRequest;
19
import javax.servlet.http.HttpServletResponse;
106 espaco 20
 
21
import org.springframework.context.annotation.Scope;
22
 
195 espaco 23
import br.com.ec.core.util.VerificadorUtil;
106 espaco 24
import br.com.ec.domain.model.Loja;
25
import br.com.ec.domain.model.Parametro;
26
import br.com.ec.domain.model.Usuario;
27
import br.com.ec.domain.model.UsuarioLoja;
28
import br.com.ec.domain.model.tipos.TipoAno;
29
import br.com.ec.domain.model.tipos.TipoMes;
30
import br.com.ec.domain.service.perfil.PerfilService;
31
import br.com.ec.domain.service.seguranca.ContextoSeguranca;
32
import br.com.ec.domain.service.usuario.UsuarioService;
33
import br.com.ec.domain.shared.ConstantesSEC;
195 espaco 34
import br.com.ec.web.exception.VerificadorLancamentoException;
35
import br.com.ec.web.exception.VerificadorLancamentoException.CommandBean;
36
import br.com.ec.web.message.LancadorMensagem;
106 espaco 37
 
38
@Named
39
@Scope("view")
40
public class SegurancaBean implements Serializable{
41
 
42
        private static final long serialVersionUID = 1L;
43
 
44
        private ContextoSeguranca contextoSeguranca;
45
        private Usuario usuario;
46
        private String novaSenha;
47
 
48
        private UsuarioService usuarioService;
49
        private PerfilService perfilService;
50
 
51
        @Inject
52
        public SegurancaBean(ContextoSeguranca contextoSeguranca, UsuarioService usuarioService, PerfilService perfilService) {
53
                this.contextoSeguranca = contextoSeguranca;
54
                this.usuarioService = usuarioService;
55
                this.perfilService = perfilService;
56
        }
57
 
58
        public ContextoSeguranca getContextoSeguranca() {
59
                return contextoSeguranca;
60
        }
61
        public void setContextoSeguranca(ContextoSeguranca contextoSeguranca) {
62
                this.contextoSeguranca = contextoSeguranca;
63
        }
64
 
65
        public Usuario getUsuario() {
66
                if (usuario == null) {
67
                        setUsuario(contextoSeguranca.obterUsuario());
68
                }
69
                return usuario;
70
        }
71
        public void setUsuario(Usuario usuario) {
72
                this.usuario = usuario;
73
        }
74
 
75
        public String getNovaSenha() {
76
                return novaSenha;
77
        }
78
        public void setNovaSenha(String novaSenha) {
79
                this.novaSenha = novaSenha;
80
        }
81
 
82
        /************************************************************************/
83
 
84
        public Boolean temPerfilAdministrador() {
85
                return perfilService.temPerfilAdministrador(getUsuario());
86
        }
87
 
88
        public Boolean temPerfilGerenteAdministrativo() {
89
                return perfilService.temPerfilGerenteAdministrativo(getUsuario());
90
        }
91
 
550 blopes 92
        public Boolean temPerfilGerenteComercial() {
93
                return perfilService.temPerfilGerenteComercial(getUsuario());
94
        }
95
 
106 espaco 96
        /************************************************************************/
97
 
305 espaco 98
        public Boolean temPerfilFinanceiro() {
99
                return perfilService.temPerfilFinanceiro(getUsuario());
106 espaco 100
        }
101
 
305 espaco 102
        public Boolean temPerfilComercial() {
103
                return perfilService.temPerfilComercial(getUsuario());
106 espaco 104
        }
105
 
305 espaco 106
        public Boolean temPerfilLojistica() {
107
                return perfilService.temPerfilLojistica(getUsuario());
106 espaco 108
        }
109
 
110
        public Boolean temPerfilVendedor() {
111
                return perfilService.temPerfilVendedor(getUsuario());
112
        }
113
 
305 espaco 114
        public Boolean temPerfilCompras() {
115
                return perfilService.temPerfilCompras(getUsuario());
106 espaco 116
        }
117
 
118
        public Boolean temPerfilGerenteVivo() {
119
                return perfilService.temPerfilGerenteVivo(getUsuario());
120
        }
121
 
122
        public Boolean temPerfilTecnico() {
123
                return perfilService.temPerfilTecnico(getUsuario());
124
        }
125
 
126
        public Boolean temPerfilRecursosHumanos() {
127
                return perfilService.temPerfilRecursosHumanos(getUsuario());
128
        }
129
 
305 espaco 130
        public Boolean temPerfilOperacoes() {
131
                return perfilService.temPerfilOperacoes(getUsuario());
106 espaco 132
        }
133
 
305 espaco 134
        public Boolean temPerfilProducao() {
135
                return perfilService.temPerfilProducao(getUsuario());
136
        }
137
 
106 espaco 138
        public Boolean temPerfilSupervisor() {
139
                return perfilService.temPerfilSupervisor(getUsuario());
140
        }
141
 
142
        public Boolean temPerfilTreinamento() {
143
                return perfilService.temPerfilTreinamento(getUsuario());
144
        }
145
 
146
        public Boolean temPerfilLoja() {
147
                return perfilService.temPerfilLoja(getUsuario());
148
        }
149
 
150
        public Boolean temAcessoLoja(Long sequencialLoja) {
151
                return temPerfilGerenteAdministrativo() || verificarAcessoLoja(getUsuario(), sequencialLoja);
152
        }
153
 
154
        public Boolean temAcessoLojaVivo() {
155
                return temPerfilGerenteAdministrativo() || verificarAcessoLoja(getUsuario(), ConstantesSEC.SEQUENCIAL_LOJA_VIVO_4);
156
        }
157
 
158
        public Boolean temAcessoLojaCasaDasCapas() {
305 espaco 159
                return temPerfilCompras() || temPerfilComercial() || (verificarAcessoLoja(getUsuario(), ConstantesSEC.SEQUENCIAL_CASA_DAS_CAPAS_17) && temPerfilVendedor());
106 espaco 160
        }
161
 
162
        public Boolean naoTemAcessoLojaCasaDasCapas() {
305 espaco 163
                return temPerfilCompras() || temPerfilComercial() || !(verificarAcessoLoja(getUsuario(), ConstantesSEC.SEQUENCIAL_CASA_DAS_CAPAS_17) && temPerfilVendedor());
106 espaco 164
        }
165
 
166
        private Boolean verificarAcessoLoja(Usuario usuario, Long sequencialLoja) {
167
                for (UsuarioLoja usuarioLoja : usuario.getLojas()) {
168
                        if (usuarioLoja.getLoja().getSequencial().equals(sequencialLoja)) {
169
                                return true;
170
                        }
171
                }
172
                return false;
173
        }
174
 
175
        public void restaurarTelaPDV(Loja loja) throws IOException {
176
            FacesContext.getCurrentInstance().getExternalContext().redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath() + "/sistema/pdv.xhtml?sequencialLoja=" + loja.getSequencial());
177
        }
178
 
179
        public void restaurarTelaPDVVivo(Loja loja) throws IOException {
180
            FacesContext.getCurrentInstance().getExternalContext().redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath() + "/sistema/pdv_vivo.xhtml?sequencialLoja=" + loja.getSequencial());
181
        }
182
 
183
        public void restaurarTelaPDVFarma(Loja loja) throws IOException {
184
            FacesContext.getCurrentInstance().getExternalContext().redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath() + "/sistema/pdv.xhtml?sequencialLoja=" + loja.getSequencial());
185
        }
186
 
187
        public void invalidarSessao() {
188
                FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
189
        }
190
 
191
        public void alterarSenhaUsuario() {
192
                new VerificadorLancamentoException().tratarIhRelancarExcecaoSemLimparEntidade(new CommandBean() {
193
                        public void execute() {
194
                                getUsuario().setSenha(getNovaSenha());
195
                                usuarioService.alterarSenhaUsuario(getUsuario());
196
                                setNovaSenha("");
197
                                LancadorMensagem.lancarSucesso("SENHA ALTERADA COM SUCESSO");
198
                        }
199
                });
200
        }
201
 
202
        public Integer getTempoEstoqueMinimoParaComprasEmDias() {
203
                Parametro parametro = new Parametro();
204
                parametro.setCodigo(ConstantesSEC.Parametro.CODIGO_PARAMETRO_TEMPO_ESTOQUE_MINIMO_PARA_COMPRAS);
205
                parametro = getUsuario().getParametros().get(getUsuario().getParametros().indexOf(parametro));
206
                return VerificadorUtil.naoEstaNulo(parametro)? new Integer(parametro.getValor()) : 15;
207
        }
208
 
209
        public Integer getTempoEstoqueParaReporEmDias() {
210
                Parametro parametro = new Parametro();
211
                parametro.setCodigo(ConstantesSEC.Parametro.CODIGO_PARAMETRO_TEMPO_ESTOQUE_REPOSICAO_PARA_COMPRAS);
212
                parametro = getUsuario().getParametros().get(getUsuario().getParametros().indexOf(parametro));
213
                return VerificadorUtil.naoEstaNulo(parametro)? new Integer(parametro.getValor()) : 60;
214
        }
215
 
216
        public TipoAno[] getTiposAno() {
217
                return TipoAno.values();
218
        }
219
 
220
        public TipoMes[] getTiposMes() {
221
                return TipoMes.values();
222
        }
223
 
152 espaco 224
        public String textoSobreCorMargem() {
225
                return ConstantesSEC.Textos.TEXTO_COR_MARGEM;
226
        }
227
 
356 espaco 228
        /*
229
 
230
        public FacesContext getContext() {
231
                return FacesContext.getCurrentInstance();
232
        }
233
 
234
        private boolean verificarContexto() {
235
                FacesContext context = getContext();
236
                return VerificadorUtil.naoEstaNulo(context) && VerificadorUtil.naoEstaNulo(context.getExternalContext());
237
        }
238
 
239
        public HttpServletRequest getRequest() {
240
                return verificarContexto() ? (HttpServletRequest) getContext().getExternalContext().getRequest() : null;
241
        }
242
 
243
        public HttpServletResponse getResponse() {
244
                return verificarContexto() ? (HttpServletResponse) getContext().getExternalContext().getResponse() : null;
245
        }
246
 
247
        public String nomeMaquina() {
248
                String nomeMaquina = "";
249
                try {
250
                        nomeMaquina = InetAddress.getLocalHost().getHostName();
251
                        nomeMaquina = getRequest().getLocalName();
252
                } catch (UnknownHostException e) {
253
                        e.printStackTrace();
254
                }
255
                return nomeMaquina;
256
        }
257
 
258
        public String ipMaquina() {
259
                String ipMaquina = "";
260
                try {
261
                        ipMaquina = InetAddress.getLocalHost().getHostAddress();
262
                        ipMaquina = getRequest().getLocalAddr();
263
                } catch (UnknownHostException e) {
264
                        e.printStackTrace();
265
                }
266
                return ipMaquina;
267
        }
268
 
269
        public String ipMaquina2() {
270
                String ipMaquina = "";
271
                try {
272
                        ipMaquina = InetAddress.getLocalHost().getHostAddress();
273
//                      ipMaquina = getRequest().getRemoteAddr();
274
                        ipMaquina = getRequest().getHeader("X-FORWARDED-FOR");
275
                    if (ipMaquina == null) {
276
                        return getRequest().getRemoteAddr();
277
                    } else {
278
                        // As of https://en.wikipedia.org/wiki/X-Forwarded-For
279
                        // The general format of the field is: X-Forwarded-For: client, prox y1, proxy2 ...
280
                        // we only want the client
281
                        return new StringTokenizer(ipMaquina, ",").nextToken().trim();
282
                    }
283
                } catch (UnknownHostException e) {
284
                        e.printStackTrace();
285
                }
286
                return ipMaquina;
287
        }
288
 
289
        public String ipMaquina3() {
290
                String ipMaquina = "";
291
                try {
292
                        ipMaquina = InetAddress.getLocalHost().getHostAddress();
293
//                      ipMaquina = getRequest().getRemoteHost();
294
 
295
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
296
            StringBuilder macs = new StringBuilder("");
297
            while (networks.hasMoreElements()) {
298
                NetworkInterface network = networks.nextElement();
299
                byte[] mac = network.getHardwareAddress();
300
                if (mac != null) {
301
//                    System.out.print("Current MAC address : ");
302
                    StringBuilder sb = new StringBuilder();
303
                    for (int i = 0; i < mac.length; i++) {
304
                        sb.append(String.format(
305
                            "%02X%s", mac[i],
306
                            (i < mac.length - 1) ? "-" : ""));
307
                    }
308
                    // MAC Address
309
//                    System.out.println(sb.toString());
310
                    macs.append(sb.toString());
311
                    macs.append("\n");
312
                }
313
            }
314
            ipMaquina = macs.toString();
315
                } catch (UnknownHostException e) {
316
                        e.printStackTrace();
317
                } catch (SocketException e) {
318
                        // TODO Auto-generated catch block
319
                        e.printStackTrace();
320
                }
321
                return ipMaquina;
322
        }
323
 
324
        public String ipMaquina4() {
325
                StringBuilder ipMaquina = new StringBuilder("");
326
                try {
327
//                      ipMaquina = InetAddress.getLocalHost().getHostAddress();
328
                        ipMaquina.append("Informacoes");
329
                        ipMaquina.append("Sistema operacional: " + System.getProperty("os.name"));
330
                        ipMaquina.append("IP/Localhost: " + InetAddress.getLocalHost().getHostAddress());
331
                        ipMaquina.append("Nome da maquina: " + InetAddress.getLocalHost().getHostName());
332
                        ipMaquina.append("Nome completo da maquina: " + InetAddress.getLocalHost().getCanonicalHostName());
333
                        ipMaquina.append("Nome da maquina2: " + InetAddress.getLoopbackAddress().getHostName());
334
                        ipMaquina.append("Nome completo da maquina2: " + InetAddress.getLoopbackAddress().getCanonicalHostName());
335
                        ipMaquina.append("MAC Address: " + getMacAddress());
336
                } catch (UnknownHostException e) {
337
                        e.printStackTrace();
338
                } catch (IOException e) {
339
                        // TODO Auto-generated catch block
340
                        e.printStackTrace();
341
                }
342
                return ipMaquina.toString();
343
        }
344
 
345
        private final static String windowsParseMacAddress(String ipConfigResponse) throws ParseException {
346
            String localHost = null;
347
            try {
348
                localHost = InetAddress.getLocalHost().getHostAddress();
349
            } catch(java.net.UnknownHostException ex) {
350
                ex.printStackTrace();
351
                throw new ParseException(ex.getMessage(), 0);
352
            }
353
 
354
            StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
355
            String lastMacAddress = null;
356
            StringBuilder infor = new StringBuilder("");
357
 
358
            while(tokenizer.hasMoreTokens()) {
359
                String line = tokenizer.nextToken().trim();
360
                infor.append(line);
361
                infor.append("\n");
362
 
363
                //IP
364
                if(line.endsWith(localHost) && lastMacAddress != null) {
365
                    return lastMacAddress;
366
                }
367
 
368
                //MAC address
369
                int macAddressPosition = line.indexOf(":");
370
                if(macAddressPosition <= 0) continue;
371
 
372
                String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
373
                if(windowsIsMacAddress(macAddressCandidate)) {
374
                    lastMacAddress = macAddressCandidate;
375
                    continue;
376
                }
377
            }
378
 
379
            return infor.toString();
380
//          ParseException ex = new ParseException("Nao foi possível ler o MAC address de [" + ipConfigResponse + "]", 0);
381
//          ex.printStackTrace();
382
//          throw ex;
383
        }
384
 
385
        private final static boolean windowsIsMacAddress(String macAddressCandidate) {
386
            if(macAddressCandidate.length() != 17) return false;
387
 
388
            return true;
389
        }
390
 
391
        private final static String windowsRunIpConfigCommand() throws IOException {
392
            Process p = Runtime.getRuntime().exec("ipconfig /all");
393
            InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
394
 
395
            StringBuffer buffer= new StringBuffer();
396
            for (;;) {
397
                int c = stdoutStream.read();
398
                if (c == -1) break;
399
                buffer.append((char)c);
400
            }
401
            String outputText = buffer.toString();
402
 
403
            stdoutStream.close();
404
 
405
            return outputText;
406
        }
407
 
408
 
409
        private final static String getMacAddress() throws IOException {
410
            try {
411
            return windowsParseMacAddress(windowsRunIpConfigCommand());
412
            } catch(ParseException ex) {
413
                ex.printStackTrace();
414
                throw new IOException(ex.getMessage());
415
            }
416
        }
417
 
418
        public final static void main(String[] args) {
419
                try {
420
                        System.out.println("Informacoes");
421
                        System.out.println("Sistema operacional: " + System.getProperty("os.name"));
422
                        System.out.println("IP/Localhost: " + InetAddress.getLocalHost().getHostAddress());
423
                        System.out.println("Nome da maquina: " + InetAddress.getLocalHost().getHostName());
424
                        System.out.println("Nome completo da maquina: " + InetAddress.getLocalHost().getCanonicalHostName());
425
                        System.out.println("Nome da maquina2: " + InetAddress.getLoopbackAddress().getHostName());
426
                        System.out.println("Nome completo da maquina2: " + InetAddress.getLoopbackAddress().getCanonicalHostName());
427
                        System.out.println("MAC Address: " + getMacAddress());
428
 
429
 
430
            // create an Enumeration of type
431
            // NetworkInterface and store the values
432
            // returned by
433
            // NetworkInterface.getNetworkInterfaces()
434
            // method
435
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
436
 
437
            // for every network in the networks Enumeration
438
            while (networks.hasMoreElements()) {
439
                NetworkInterface network
440
                    = networks.nextElement();
441
 
442
                // call getHardwareAddress() method on each
443
                // network and store the returned value in a
444
                // byte array
445
                byte[] mac = network.getHardwareAddress();
446
 
447
                if (mac != null) {
448
                    System.out.print(
449
                        "Current MAC address : ");
450
 
451
                    // convert the obtained byte array into
452
                    // a printable String
453
                    StringBuilder sb = new StringBuilder();
454
                    for (int i = 0; i < mac.length; i++) {
455
                        sb.append(String.format(
456
                            "%02X%s", mac[i],
457
                            (i < mac.length - 1) ? "-"
458
                                                 : ""));
459
                    }
460
 
461
                    // print the final String containing the
462
                    // MAC Address
463
                    System.out.println(sb.toString());
464
                }
465
            }
466
 
467
                } catch(Throwable t) {
468
                        t.printStackTrace();
469
                }
470
        }
471
 
472
        */
473
 
106 espaco 474
}