Created
May 17, 2013 12:40
-
-
Save andreluizf/5598777 to your computer and use it in GitHub Desktop.
custom spring security
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<beans:beans xmlns="http://www.springframework.org/schema/security" | |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xmlns:beans="http://www.springframework.org/schema/beans" | |
xsi:schemaLocation="http://www.springframework.org/schema/beans | |
http://www.springframework.org/schema/beans/spring-beans.xsd | |
http://www.springframework.org/schema/security | |
http://www.springframework.org/schema/security/spring-security-3.0.xsd" > | |
<http > | |
<session-management session-fixation-protection="newSession" /> | |
<intercept-url pattern="/home.xhtml" access="ROLE_ADMIN" /> | |
<intercept-url pattern="/pages/**" access="ROLE_ADMIN" /> | |
<form-login | |
login-processing-url="/j_spring_security_check" | |
always-use-default-target="true" | |
login-page="/index.xhtml" | |
default-target-url="/home.xhtml" | |
authentication-failure-url="/index.xhtml?login_error=1" /> | |
<logout/> | |
</http> | |
<authentication-manager> | |
<authentication-provider ref="customAuthenticationProvider" > | |
</authentication-provider> | |
</authentication-manager> | |
<beans:bean id="customAuthenticationProvider" class="com.xkey.principal.CustomAuthenticationProvider"/> | |
</beans:beans> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.xkey.principal.bean; | |
import java.io.IOException; | |
import java.io.Serializable; | |
import javax.annotation.PostConstruct; | |
import javax.faces.bean.ManagedBean; | |
import javax.faces.bean.SessionScoped; | |
import javax.faces.context.ExternalContext; | |
import javax.faces.context.FacesContext; | |
import javax.servlet.RequestDispatcher; | |
import javax.servlet.ServletException; | |
import javax.servlet.ServletRequest; | |
import javax.servlet.ServletResponse; | |
@ManagedBean(name = "login") | |
@SessionScoped | |
public class Login implements Serializable { | |
public static String cnpj; | |
public static String empresa; | |
private String username; | |
private String password; | |
@PostConstruct | |
public void login() { | |
Login.empresa = ""; | |
Login.cnpj = ""; | |
} | |
public String getEmpresa() { | |
return empresa; | |
} | |
public void setEmpresa(String empresa) { | |
Login.empresa = empresa; | |
} | |
public void setPassword(String password) { | |
this.password = password; | |
} | |
public String getPassword() { | |
return password; | |
} | |
public void setUsername(String username) { | |
this.username = username; | |
} | |
public String getUsername() { | |
return username; | |
} | |
public String getCnpj() { | |
return cnpj; | |
} | |
public void setCnpj(String cnpj) { | |
Login.cnpj = cnpj; | |
} | |
public String doLogin() throws IOException, ServletException { | |
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); | |
RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check?j_username=" + username + "&j_password=" + password); | |
dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse()); | |
FacesContext.getCurrentInstance().responseComplete(); | |
return ""; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.xkey.principal; | |
import com.xkey.principal.helpers.LoginHelper; | |
import com.google.common.collect.Lists; | |
import com.xkey.principal.bean.Login; | |
import com.xkey.saxgeral.helpers.SessionHelper; | |
import java.util.List; | |
import org.apache.logging.log4j.LogManager; | |
import org.apache.logging.log4j.Logger; | |
import org.springframework.security.authentication.AuthenticationProvider; | |
import org.springframework.security.authentication.BadCredentialsException; | |
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
import org.springframework.security.core.Authentication; | |
import org.springframework.security.core.AuthenticationException; | |
import org.springframework.security.core.GrantedAuthority; | |
public class CustomAuthenticationProvider implements AuthenticationProvider { | |
LoginHelper login = new LoginHelper(); | |
public final static Logger log = LogManager.getLogger(CustomAuthenticationProvider.class.getName()); | |
@Override | |
public Authentication authenticate(Authentication authentication) | |
throws AuthenticationException { | |
List<GrantedAuthority> AUTHORITIES = Lists.newArrayList(); | |
AUTHORITIES.add(new GrantedAuthority() { | |
@Override | |
public String getAuthority() { | |
return "ROLE_ADMIN"; | |
} | |
}); | |
String msg = ""; | |
if (SessionHelper.getQuantidadeEmpresas() > 0) { | |
msg = login.logar(authentication.getName(), authentication.getCredentials().toString(), Login.empresa); | |
} else { | |
log.fatal("Nenhuma empresa encontrada. Iniciando ativação do CNPJ: " + Login.cnpj); | |
msg = login.ativar(authentication.getName(), authentication.getCredentials().toString(), Login.cnpj); | |
} | |
if (msg.isEmpty()) { | |
return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), AUTHORITIES); | |
} else { | |
log.error("Erro ao logar. Usuário: " + authentication.getName() + " MSG: " + msg); | |
throw new BadCredentialsException(msg); | |
} | |
} | |
@Override | |
public boolean supports(Class<? extends Object> authentication) { | |
return authentication.equals(UsernamePasswordAuthenticationToken.class); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h:form id="login" prependId="false" > | |
<p:panelGrid columns="4" styleClass="semBorda"> | |
<h:outputLabel value="Usuário" for="j_username" style="font-weight: bold"/> | |
<p:inputText id="j_username" value="#{login.username}" styleClass="j_username" style="font-weight: bold; width: 231px!important; height: 25px;; margin-bottom: 10px; background-color: #fff!important " required="true" requiredMessage="Preencha o nome do Usuário"/> | |
<p:watermark for="j_username" value="Usuário"/> | |
<p:message for="j_username" /> | |
<h:outputLabel value="Senha" for="j_password" style="font-weight: bold"/> | |
<p:password id="j_password" value="#{login.password}" size="30" styleClass="j_password" style="font-weight: bold; width: 231px!important;height: 25px;" required="true" requiredMessage="Digite a Senha" /> | |
<p:watermark for="j_password" value="Senha" /> | |
<p:message for="j_password" /> | |
<h:outputLabel value="Empresa" for="selectEmpresa" style="font-weight: bold" rendered="#{acessoController.quantidade != 0}"/> | |
<p:selectOneMenu id="selectEmpresa" value="#{login.empresa}" styleClass="selectEmpresa" style="font-weight: bold; width: 239px!important;height: 32px; margin-top: 8px;" editable="false" required="true" requiredMessage="Selecione uma empresa" rendered="#{acessoController.quantidade != 0}"> | |
<f:selectItem itemLabel="SELECIONE UMA EMPRESA" itemDisabled="true" itemValue=""/> | |
<f:selectItems value="#{empresaController.listEmpresas}" var="list" itemLabel="#{list.nomeFantasiaMaiusculo}" itemValue="#{list.codEmpresa}"/> | |
<f:ajax event="change" execute="@this" /> | |
</p:selectOneMenu> | |
<h:outputText value=""/> | |
<p:message for="selectEmpresa" /> | |
<p:outputLabel value="" rendered="#{acessoController.quantidade == 0}"/> | |
<!-- CASO A QUANTIDADE DE EMPRESAS NO BANDO SEJA == 0 MOSTRA-SE O CAMPO CNPJ CASO CONTRÁRIO MOSTRA-SE O COMBOBOX DE EMPRESAS--> | |
<h:outputLabel value="CNPJ" for="j_cnpj" style="font-weight: bold;" rendered="#{acessoController.quantidade == 0}"/> | |
<p:inputMask id="j_cnpj" value="#{login.cnpj}" styleClass="j_username" style="font-weight: bold; width: 231px!important; height: 25px; margin-bottom: 10px; background-color: #fff!important;" required="true" requiredMessage="Preencha o CNPJ" rendered="#{acessoController.quantidade == 0}" mask="99.999.999/9999-99"/> | |
<p:watermark for="j_cnpj" value="CNPJ"/> | |
<p:message for="j_cnpj" /> | |
</p:panelGrid> | |
<p:panel styleClass="panelBotaoLogin" > | |
<h:commandButton id="saveButton" action="#{login.doLogin()}" value=" Entrar" styleClass="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only botaoEntrar" style="#{acessoController.quantidade == 0 ? 'left:-6px' : ''}" /> | |
</p:panel> | |
</h:form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.xkey.principal.helpers; | |
import com.xkey.saxgeral.helpers.NumberHelper; | |
import com.xkey.caxgeral.model.cliente.Cliente; | |
import com.xkey.caxgeral.model.cliente.ClienteRepository; | |
import com.xkey.caxgeral.model.consultor.Consultor; | |
import com.xkey.caxgeral.model.consultor.ConsultorRepository; | |
import com.xkey.saxgeral.helpers.SessionHelper; | |
import com.xkey.saxgeral.model.empresa.Empresa; | |
import com.xkey.saxgeral.model.empresa.EmpresaRepository; | |
import com.xkey.saxgeral.model.funcionario.Funcionario; | |
import com.xkey.saxfuncionario.model.funcionario.FuncionarioRepository; | |
import java.util.Date; | |
import javax.ejb.EJB; | |
import javax.naming.InitialContext; | |
import javax.naming.NamingException; | |
import org.apache.logging.log4j.LogManager; | |
import org.apache.logging.log4j.Logger; | |
public class LoginHelper { | |
public final static Logger log = LogManager.getLogger(LoginHelper.class.getName()); | |
@EJB | |
FuncionarioRepository funcionarioService; | |
@EJB | |
EmpresaRepository empresaService; | |
@EJB | |
ClienteRepository clienteService; | |
@EJB | |
ConsultorRepository consultorService; | |
public String logar(String login, String senha, String empresa) { | |
String msg = ""; | |
try { | |
InitialContext ini = new InitialContext(); | |
funcionarioService = (FuncionarioRepository) ini.lookup("ejb/FuncionarioRepositoryImp"); | |
empresaService = (EmpresaRepository) ini.lookup("ejb/EmpresaRepositoryImp"); | |
} catch (NamingException ex) { | |
log.error("Erro ao carregar repositórios.", ex); | |
} | |
Funcionario funcionario = funcionarioService.findLoginSenha(login, senha); | |
Empresa emp = null; | |
if (empresa == null || empresa.isEmpty()) { | |
msg = "Atenção, selecione uma empresa."; | |
} else if (funcionario != null) { | |
emp = empresaService.findById(Long.parseLong(empresa)); | |
if (!funcionario.getSistemaPermitirAcesso()) { | |
msg = "Atenção, o usuário informado não tem permissão de acesso ao sistema. Verifique!"; | |
} else if (funcionario.getSistemaDataExpira().before(new Date())) { | |
msg = "Atenção, sua permissão de acesso expirou. Verifique!"; | |
} else if (((!funcionario.getSistemaAcessoMultiempresa() || funcionario.getEmpresaList().isEmpty()) && !funcionario.getLigCodEmpresa().equals(emp)) && (!funcionario.getEmpresaList().contains(emp))) { | |
msg = "Ateção, o usuário informado não tem permissâo de acesso para a empresa selecionada. Verifique!"; | |
} | |
} else { | |
msg = "Atenção, o usuário informado e/ou senha estão incorretos. Verifique!"; | |
} | |
if (funcionario != null && empresa != null && msg.isEmpty()) { | |
new SessionHelper(emp, funcionario); | |
log.fatal("Usuário " + funcionario.getDescricao() + " logado na empresa " + emp.getRazaoSocial() + "."); | |
} | |
return msg; | |
} | |
public String ativar(String login, String senha, String cnpj) { | |
try { | |
InitialContext ini = new InitialContext(); | |
clienteService = (ClienteRepository) ini.lookup("ejb/ClienteRepositoryImp"); | |
consultorService = (ConsultorRepository) ini.lookup("ejb/ConsultorRepositoryImpl"); | |
} catch (NamingException ex) { | |
log.error("Erro ao carregar repositórios.", ex); | |
} | |
Consultor consultor = consultorService.findLoginSenha(login, senha); | |
Cliente cliente = clienteService.findByCnpj(NumberHelper.getNumbers(cnpj)); | |
String msg = ""; | |
AtivacaoHelper.setEmpresa(cliente); | |
if (consultor == null) { | |
msg = "Atenção, usuário e/ou senha para ativação inválidos. Verifique!"; | |
} else if (cliente == null) { | |
msg = "Atenção, o CNPJ informado não foi encontrado. Verifique!"; | |
} else if (cliente.getSistemaImplantacao() != null) { | |
msg = "Atenção, o CNPJ informado já está ativado. Verifique !"; | |
} else { | |
msg = "ATIVACAO"; | |
} | |
return msg; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment