/**
   * Get the list of authorized apps for the user based on the user's LEA.
   *
   * <p>No additional filtering is done on the results. E.g. if a user is a non-admin, the admin
   * apps will still show up in the list, or if an app is disabled it will still show up.
   *
   * @param principal
   * @return list of app IDs, or null if it couldn't be determined
   */
  @SuppressWarnings("unchecked")
  public boolean isAuthorizedForApp(Entity app, SLIPrincipal principal) {

    if (principal.isAdminRealmAuthenticated()) {
      return isAdminVisible(app);
    } else {
      if (isAutoAuthorized(app)) {
        return true;
      } else if (!isOperatorApproved(app)) {
        return false;
      } else {
        Set<String> edOrgs = helper.locateDirectEdorgs(principal.getEntity());
        NeutralQuery appAuthCollQuery = new NeutralQuery();
        appAuthCollQuery.addCriteria(new NeutralCriteria("applicationId", "=", app.getEntityId()));
        appAuthCollQuery.addCriteria(
            new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, edOrgs));
        Entity authorizedApps = repo.findOne("applicationAuthorization", appAuthCollQuery);
        if (authorizedApps != null) {
          if (isAutoApproved(app)) {
            return true;
          } else {
            // query approved edorgs
            List<String> approvedDistricts =
                new ArrayList<String>((List<String>) app.getBody().get("authorized_ed_orgs"));
            List<String> myDistricts = helper.getDistricts(edOrgs);
            approvedDistricts.retainAll(myDistricts);
            return !approvedDistricts.isEmpty();
          }
        }
      }
    }
    return false;
  }