Skip to content

Instantly share code, notes, and snippets.

@tomasmano
Last active December 12, 2015 01:28
Show Gist options
  • Save tomasmano/4690699 to your computer and use it in GitHub Desktop.
Save tomasmano/4690699 to your computer and use it in GitHub Desktop.
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* Backing bean for JSF 2.0 Framework. Collects login form values, provides
* login and logout, and checks for access to specific functions.
*
* @author Tomas Mano <tomasmano@gmail.com>
*/
@Component
@Transactional
@Scope(value="session", proxyMode= ScopedProxyMode.TARGET_CLASS)
public class AuthenticationBean implements Serializable{
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserServiceFacade userService;
private String username;
private String password;
private boolean loggedIn;
private boolean isAdmin = false;
private UserDTO user = new UserDTO();
/**
* Attempts to authenticate an user with provided user's credentials.
*
* @return if successful returns succes string keyword for configured
* navigation in faces-config.xml
* @throws IOException
* @throws ServletException
*/
public String doLogin() throws IOException, ServletException{
try {
// first create the authentication request object, processed by Authentification manager afterwards
Authentication request = new UsernamePasswordAuthenticationToken(
this.username, this.password);
// now authenticate the passed Authentication object
Authentication result = authenticationManager.authenticate(request);
//if excption wasn't thrown, set authenticated principal to spring security context(explicit authentication)
SecurityContextHolder.getContext().setAuthentication(result);
// determine user authority (is user admin?)
Collection<String> roles = AuthorityUtils.authorityListToSet(result.getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
isAdmin = true;
}
} catch (AuthenticationException e) {
FacesUtils.reportError(e.getMessage());
return "";
}
user = userService.findByUsername(username);
loggedIn = true;
if (isAdmin) {
lastLogin=user.getLastLogin();
ip=user.getIp();
markLoginEvent(user);
return Outcomes.successAdmin.go();
}
// check user current page to disable access to admin pages
String uri = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRequestURI();
if (uri.endsWith("/admin/admin-login.xhtml")) {
FacesUtils.getExternalContext().getFlash().setKeepMessages(true);
FacesUtils.reportMessage(FacesMessage.SEVERITY_ERROR, "Invalid credetnials");
((HttpSession) FacesUtils.getExternalContext().getSession(false)).invalidate();
}
// required by primefaces login popup window component
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("loggedIn", loggedIn);
return Outcomes.success.go();
}
/**
* Invalidates user's session.
*
* @return null
* @throws IOException
*/
public String doLogout() throws IOException {
this.username = "";
this.password = "";
this.loggedIn = false;
this.isAdmin = false;
this.projectRole = null;
((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).invalidate();
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
context.redirect(context.getRequestContextPath());
FacesContext.getCurrentInstance().responseComplete();
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment