AuthUtil.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cz.hsrs.rest.util;
  2. import javax.naming.AuthenticationException;
  3. import javax.servlet.http.HttpServletRequest;
  4. import cz.hsrs.db.util.UserUtil;
  5. import cz.hsrs.servlet.security.JSPHelper;
  6. import cz.hsrs.servlet.security.LoginUser;
  7. /**
  8. * Utility class for authentication
  9. * @author mkepka
  10. *
  11. */
  12. public class AuthUtil {
  13. /**
  14. * Method provides info about logged user by SessionId in HTTPRequest
  15. * @param request - HTTP request containing SESSIONID
  16. *
  17. */
  18. public static LoginUser getAuthenticatedLoginUser(HttpServletRequest request) throws AuthenticationException {
  19. LoginUser user = ((LoginUser) request.getSession().getAttribute(JSPHelper.USERATTRIBUTE));
  20. if(user != null){
  21. if (user.isAuthenticated()) {
  22. return user;
  23. } else {
  24. throw new AuthenticationException("Authentication failure for request " + request.getQueryString());
  25. }
  26. }
  27. else{
  28. String remoteHost = request.getRemoteHost();
  29. if ((remoteHost.equals("127.0.0.1") || remoteHost.equals("localhost")) && request.getParameter("user") != null) {
  30. try {
  31. UserUtil uUtil = new UserUtil();
  32. String userName = request.getParameter(JSPHelper.USERATTRIBUTE);
  33. String pass = uUtil.getUserPassword(userName);
  34. LoginUser userLocal = new LoginUser(request);
  35. if(userLocal.athenticate(userName, pass)){
  36. return userLocal;
  37. } else{
  38. throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
  39. }
  40. } catch (Exception e) {
  41. throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
  42. }
  43. } else{
  44. throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
  45. }
  46. }
  47. }
  48. }