public String intercept(ActionInvocation invocation) throws Exception {

    int userId;
    Object action = invocation.getAction();

    if (action instanceof ExceptionHandler) {
      // actually print the message for debugging purposes
      String trace = getStackTrace(((ExceptionHandler) action).getException());
      return "";
    }

    // TODO FINNUCKS: this logs out a current user on one of
    // these actions and sets it to the read only user.
    // Need to check ID and ... ?
    if (action instanceof ROIterationAction
        || (isUnderReadOnlyAction
            && (action instanceof ChartAction
                || action instanceof IterationAction
                || action instanceof IterationHistoryAction
                || action instanceof StoryAction))) {

      isUnderReadOnlyAction = true;

      // log in read only user if we got to here
      UserDAOHibernate userDao = new UserDAOHibernate();

      SessionFactory sessionFactory = null;
      try {
        sessionFactory = (SessionFactory) new InitialContext().lookup("hibernateSessionFactory");
        userDao.setSessionFactory(sessionFactory);
      } catch (NamingException e) {
        e.printStackTrace();
      }
      Session session = sessionFactory.openSession();

      User user = userDao.getByLoginName("readonly");

      SecurityUtil.setLoggedUser(user);

      // push current user to the value stack
      invocation.getStack().set("currentUser", user);
      invocation.getStack().set("currentUserJson", new JSONSerializer().serialize(user));

      session.disconnect();
      session.close();

      // perform request
      String result = invocation.invoke();

      // after the request:
      // reset the logged user
      SecurityUtil.setLoggedUser(null);

      return result;
    }

    try {
      // get the current user id
      userId = SecurityUtil.getLoggedUserId();
    } catch (IllegalStateException e) {
      // no logged user

      log.warn("no user found to be assigned");

      SecurityUtil.setLoggedUser(null);

      return invocation.invoke();
    }

    // get the user object corresponding to the id
    User user = userBusiness.retrieve(userId);

    // check that user hasn't been removed during the session
    if (user == null) {
      SecurityUtil.logoutCurrentUser();
    }
    // check that user hasn't been disabled during the session
    if (!user.isEnabled()) {
      SecurityUtil.logoutCurrentUser();
    }

    // before the request:
    // set this user as the logged user
    SecurityUtil.setLoggedUser(user);

    // push current user to the value stack
    invocation.getStack().set("currentUser", user);
    invocation.getStack().set("currentUserJson", new JSONSerializer().serialize(user));

    // perform request
    String result = invocation.invoke();

    // after the request:
    // reset the logged user
    SecurityUtil.setLoggedUser(null);

    return result;
  }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    // System.out.println("URL: " + ServletActionContext.getRequest().getRequestURL().toString());
    HttpServletRequest req = ServletActionContext.getRequest();
    String actionName = ServletActionContext.getActionMapping().getName();

    User loggedUser =
        SecurityUtil
            .getLoggedUser(); // SecurityUtil.getLoggedUser() can't get all needed information of
                              // user -> should retrieve by making new user.
    User user = userBusiness.retrieve(loggedUser.getId());

    boolean admin = user.isAdmin();
    boolean readOnly = user.getName().equals("readonly");
    boolean access = false;

    if (admin) {
      // if admin, everything is fine
      access = true;
    } else if (readOnly) {
      // check read only operations
      if (actionName.equals("ROIterationHistoryByToken")
          || actionName.equals("ROIterationMetricsByToken")
          || actionName.equals(("ROIterationData"))) {
        access = true;
      }
    } else {
      if (actionName.equals("createTeam")
          || actionName.equals("deleteTeam")
          || actionName.equals("deleteTeamForm")
          || actionName.equals("storeTeam")
          || actionName.equals("storeNewTeam")) {

        // these are admin-only operations
        access = false;

      } else if (actionName.equals("storeUserAndRedirect")) {
        Map params = req.getParameterMap();
        boolean attemptAdmin = params.containsKey("user.admin");
        int id = Integer.parseInt(((String[]) params.get("userId"))[0]);
        if (id == user.getId() && !attemptAdmin) {
          access = true;
        }
      } else if (actionName.equals("storeUser")) {

        // check if ID is of current user, and what is being stored
        // can't set user.admin or team
        Map params = req.getParameterMap();
        boolean attemptAdmin = params.containsKey("user.admin");
        boolean attemptTeam = params.containsKey("teamsChanged") || params.containsKey("teamIds");
        int id = Integer.parseInt(((String[]) params.get("userId"))[0]);

        if (id == user.getId() && !attemptAdmin && !attemptTeam) {
          // check not setting user.admin
          access = true;
        }
      } else if (actionName.equals("storeNewUser")) {
        Map params = req.getParameterMap();
        boolean attemptToCreateNonAdmin =
            params.containsKey("user.admin")
                && ((String[]) params.get("user.admin"))[0].equals("false");
        // Non admins can create only other non admin users
        if (attemptToCreateNonAdmin) {
          // Non admins can only add new users to their teams
          if (params.containsKey("teamIds")) {
            Set<String> myTeamIds = new HashSet<String>();
            for (Team team : user.getTeams()) {
              myTeamIds.add("" + team.getId());
            }
            String[] teamIds = (String[]) params.get("teamIds");
            Set<String> newUserTeamIds = new HashSet<String>();
            for (String teamId : teamIds) {
              newUserTeamIds.add(teamId);
            }
            if (myTeamIds.containsAll(newUserTeamIds)) {
              access = true;
            }
          } else {
            access = true;
          }
        }
      } else if (actionName.equals("retrieveAllProducts")
          || actionName.equals("retrieveAllSAIterations")) {
        // access matrix operations
        access = false;
      } else if (actionName.equals("storeNewIteration") || actionName.equals("storeNewProduct")) {
        // these are operations available to everyone
        access = true;
      } else if ((actionName.equals("retrieveBranchMetrics")
              || actionName.equals("getStoryHierarchy"))
          && req.getParameterMap().containsKey("storyId")) {
        Map params = req.getParameterMap();
        int storyId = Integer.parseInt(((String[]) params.get("storyId"))[0]);
        Story story = storyBusiness.retrieve(storyId);
        if (story.getIteration() != null) {
          access =
              this.authorizationBusiness.isBacklogAccessible(story.getIteration().getId(), user);
        }
        if (!access && story.getBacklog() != null) {
          access = this.authorizationBusiness.isBacklogAccessible(story.getBacklog().getId(), user);
        }
      } else {
        // Default case: Try to find a backlog id of some kind to check.

        Map params = req.getParameterMap();
        int id = -1;
        if (params.containsKey("iterationId"))
          id = Integer.parseInt(((String[]) params.get("iterationId"))[0]);
        else if (params.containsKey("backlogId"))
          id = Integer.parseInt(((String[]) params.get("backlogId"))[0]);
        else if (params.containsKey("productId"))
          id = Integer.parseInt(((String[]) params.get("productId"))[0]);
        else if (params.containsKey("projectId"))
          id = Integer.parseInt(((String[]) params.get("projectId"))[0]);
        else if (params.containsKey("taskId")) {
          int taskId = Integer.parseInt(((String[]) params.get("taskId"))[0]);
          Task task = taskBusiness.retrieve(taskId);
          if (task.getIteration() != null) id = task.getIteration().getId();
          else if (task.getStory().getIteration() != null)
            id = task.getStory().getIteration().getId();
          else id = task.getStory().getBacklog().getId(); // story in project/product w/a iteration
        } else if (params.containsKey("storyId")) {
          int storyId = Integer.parseInt(((String[]) params.get("storyId"))[0]);
          Story story = storyBusiness.retrieve(storyId);
          if (story.getIteration() != null) {
            id = story.getIteration().getId();
          } else {
            id = story.getBacklog().getId();
          }
        }

        boolean attemptTeam = params.containsKey("teamsChanged");
        if (!attemptTeam) {
          if (id != -1
              && !(id == 0 && actionName.equals("retrieveSubBacklogs") && params.size() == 1))
            access = this.authorizationBusiness.isBacklogAccessible(id, user);
          else
            // Operations without ids must be allowed
            access = true;
        }
      }
    }

    if (access) return invocation.invoke();
    else return "noauth";
  }