diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml index c6a0fb80..be03a8f6 100644 --- a/WebContent/WEB-INF/web.xml +++ b/WebContent/WEB-INF/web.xml @@ -318,18 +318,6 @@ /api/* --> - - - - - - NoUserInSessionTrustedTokenFilter - prerna.web.conf.NoUserInSessionTrustedTokenFilter - - trustedTokenPrefix - sencha - - - trustedTokenDomain - * - - - - NoUserInSessionTrustedTokenFilter - /api/* - NoUserInSessionFilter @@ -707,14 +678,6 @@ admin-set-publisher false - - anonymous-users-allowed - false - - - anonymous-users-upload-data - false - use-logout-page false @@ -746,9 +709,6 @@ prerna.web.conf.UserDBLoader - - prerna.web.conf.NoUserInSessionTrustedTokenListener - prerna.semoss.web.github.GitHubLifecycleListener diff --git a/docs/catalog-image-uploads.md b/docs/catalog-image-uploads.md index 7ad1b012..d0b88da4 100644 --- a/docs/catalog-image-uploads.md +++ b/docs/catalog-image-uploads.md @@ -64,7 +64,7 @@ and other formats are not accepted by these routes. | Status | Meaning | | --- | --- | | 400 | Invalid ID, empty/corrupt image, invalid dimensions, missing `file`, or malformed multipart body | -| 401 | Missing session or anonymous user | +| 401 | Missing session | | 403 | Resource is missing or the caller cannot edit it | | 413 | File/request size limit exceeded, or multiple multipart parts supplied | | 415 | Request is not multipart, or image format is unsupported | diff --git a/docs/endpoints.md b/docs/endpoints.md index 713d81ea..fdc24aa5 100644 --- a/docs/endpoints.md +++ b/docs/endpoints.md @@ -167,7 +167,7 @@ A model usage limit is JSON: Unlimited, or rules that must all have usage left. Only a model's owners, and admins in admin mode, set usage limits on it: a person's, a team's, public use and the model's total. Editors still add people and change the level of Read-Only and Editor people; their adds give no limit and their changes keep the current one. A change by an editor that leaves any other limit is refused with "Only owners can set usage limits". -These endpoints read and set limits that are not part of a grant. Anonymous sessions get `401` from each. +These endpoints read and set limits that are not part of a grant. Requests without a signed in user get `401` from each. | Method and endpoint | Inputs / purpose | Who may call | | --- | --- | --- | diff --git a/src/prerna/semoss/web/ms/MicrosoftGraphSubscriptionService.java b/src/prerna/semoss/web/ms/MicrosoftGraphSubscriptionService.java index a2b8487b..f36e87fb 100644 --- a/src/prerna/semoss/web/ms/MicrosoftGraphSubscriptionService.java +++ b/src/prerna/semoss/web/ms/MicrosoftGraphSubscriptionService.java @@ -128,7 +128,7 @@ public Response available(@Context HttpServletRequest req) { } catch (IllegalAccessException e) { classLogger.debug("Microsoft Graph availability was asked for without a session.", e); } - if (user == null || !user.isLoggedIn() || user.isAnonymous()) { + if (user == null || !user.isLoggedIn()) { return WebUtility.getResponse(Map.of(STATUS, ERROR, REASON, "user session is invalid"), 401); } diff --git a/src/prerna/semoss/web/services/config/ServerConfigurationResource.java b/src/prerna/semoss/web/services/config/ServerConfigurationResource.java index a243ab34..dcc2dec7 100644 --- a/src/prerna/semoss/web/services/config/ServerConfigurationResource.java +++ b/src/prerna/semoss/web/services/config/ServerConfigurationResource.java @@ -130,8 +130,6 @@ private static void loadConfig() { // security is always enabled... loadConfig.put("security", true); - loadConfig.put("anonymousUsers", AbstractSecurityUtils.anonymousUsersEnabled()); - loadConfig.put("anonymousUserUploadData", AbstractSecurityUtils.anonymousUserUploadData()); // admin only for project actions loadConfig.put("adminOnlyProjectAdd", AbstractSecurityUtils.adminOnlyProjectAdd()); loadConfig.put("adminOnlyProjectDelete", AbstractSecurityUtils.adminOnlyProjectDelete()); @@ -311,7 +309,7 @@ private static Map getConfiguration(@Context HttpServletRequest // from the scopes it asks for, so a client can tell which apps can work before // it calls them. only whether each app can work is sent, never the scopes, and // only to a user signed in to the platform - if (user != null && user.isLoggedIn() && !user.isAnonymous()) { + if (user != null && user.isLoggedIn()) { myConfiguration.put("connectorAccess", ConnectorScopeAccess.getConnectorAccess()); } // themes @@ -375,8 +373,8 @@ public Response fetchCsrf(@Context HttpServletRequest request, @Context HttpServ * {@code @Consumes}/{@code @Produces} content types. *

* Resources whose simple class name starts with {@code "Admin"} are only - * included when the calling user is logged in and an admin. Anonymous and - * non-admin users get the rest of the catalog without those entries. + * included when the calling user is logged in and an admin. Other callers get + * the rest of the catalog without those entries. * * @param request the incoming HTTP request (used only to prefix the * application context path on each path so callers see real @@ -388,8 +386,8 @@ public Response fetchCsrf(@Context HttpServletRequest request, @Context HttpServ @Path("/endpoints") @Produces("application/json") public Response listEndpoints(@Context HttpServletRequest request, @Context Application application) { - // admin gating: anonymous users and non-admin logged-in users do not - // see endpoints from resources whose simple class name starts with + // admin gating: callers who are not a logged-in admin do not see + // endpoints from resources whose simple class name starts with // "Admin" (e.g. AdminUserAuthorizationResource). boolean includeAdminResources = false; try { diff --git a/src/prerna/semoss/web/services/local/NameServer.java b/src/prerna/semoss/web/services/local/NameServer.java index 1ebcfee0..ebe8a281 100644 --- a/src/prerna/semoss/web/services/local/NameServer.java +++ b/src/prerna/semoss/web/services/local/NameServer.java @@ -1289,7 +1289,7 @@ public Response agentRunStreaming(MultivaluedMap form, @Context } HttpSession session = request.getSession(false); User user = session == null ? null : (User) session.getAttribute(Constants.SESSION_USER); - if (user == null || user.isAnonymous()) { + if (user == null) { Map errorRet = new HashMap<>(); errorRet.put("errorMessage", "Agent run streaming requires an authenticated user"); return WebUtility.getResponseNoCache(errorRet, 401); diff --git a/src/prerna/semoss/web/services/local/ResourceUtility.java b/src/prerna/semoss/web/services/local/ResourceUtility.java index 5b962b86..234dc9a7 100644 --- a/src/prerna/semoss/web/services/local/ResourceUtility.java +++ b/src/prerna/semoss/web/services/local/ResourceUtility.java @@ -170,8 +170,8 @@ public interface AdminCall { /** * Runs a call for the signed in user and turns its outcome into the response: - * 200 with its result, 401 for a missing or anonymous session, 403 for a user who - * may not do it, 400 for a bad request and 500 for anything else. Errors carry + * 200 with its result, 401 for a missing session, 403 for a user who may not do + * it, 400 for a bad request and 500 for anything else. Errors carry * {@link Constants#ERROR_MESSAGE}, and unexpected ones * {@link Constants#TECH_ERROR_MESSAGE} too. Every outcome is logged with the * endpoint, such as {@code POST /Monolith/api/auth/group/addGroupMember}, the @@ -185,25 +185,6 @@ public interface AdminCall { * @return the response */ public static Response respond(HttpServletRequest request, String action, UserCall call) { - return respond(request, action, false, call); - } - - /** - * {@link #respond} for a call that only reads, which an anonymous session, such - * as a visitor to a public app, may make too. A call that changes anything uses - * {@link #respond}, which answers anonymous sessions with 401. - * - * @param request the request, whose session holds the user - * @param action what the call does, for the logs, such as - * {@code "read their permission on project 123"} - * @param call the call - * @return the response - */ - public static Response respondAllowingAnonymous(HttpServletRequest request, String action, UserCall call) { - return respond(request, action, true, call); - } - - private static Response respond(HttpServletRequest request, String action, boolean allowAnonymous, UserCall call) { String endpoint = request.getMethod() + " " + request.getRequestURI(); User user; try { @@ -212,10 +193,6 @@ private static Response respond(HttpServletRequest request, String action, boole classLogger.warn("[{}] A request without a signed in user tried to {}", endpoint, action); return errorResponse("User session is invalid", 401); } - if (user.isAnonymous() && !allowAnonymous) { - classLogger.warn("[{}] An anonymous user tried to {}", endpoint, action); - return errorResponse("User session is invalid", 401); - } String userName = User.getSingleLogginName(user); try { diff --git a/src/prerna/semoss/web/services/local/UserResource.java b/src/prerna/semoss/web/services/local/UserResource.java index 68cbea5b..3ddae2b9 100644 --- a/src/prerna/semoss/web/services/local/UserResource.java +++ b/src/prerna/semoss/web/services/local/UserResource.java @@ -72,7 +72,6 @@ import prerna.auth.SyncUserAssetsThread; import prerna.auth.User; import prerna.auth.external.ExternalAuthorizationHelper; -import prerna.auth.utils.AbstractSecurityUtils; import prerna.auth.utils.SecurityAPIUserUtils; import prerna.auth.utils.SecurityAdminUtils; import prerna.auth.utils.SecurityExternalConnectorsUtils; @@ -328,7 +327,6 @@ public static void addAccessToken(AccessToken token, HttpServletRequest request, SecurityUserUtils.loadUserMetadata(token); semossUser.setAccessToken(token); - semossUser.setAnonymous(false); session.setAttribute(Constants.SESSION_USER, semossUser); WebUtility.loggingContextLoginEvent(session); @@ -1379,7 +1377,7 @@ public Response loginNative(@Context HttpServletRequest request, @Context HttpSe User user = null; if (session != null) { user = (User) session.getAttribute(Constants.SESSION_USER); - if (!AbstractSecurityUtils.anonymousUsersEnabled() && user != null && user.getLogins().isEmpty()) { + if (user != null && user.getLogins().isEmpty()) { session.invalidate(); } } @@ -1395,7 +1393,7 @@ public Response loginNative(@Context HttpServletRequest request, @Context HttpSe HttpSession session = request.getSession(false); if (session != null) { User user = (User) session.getAttribute(Constants.SESSION_USER); - if (!AbstractSecurityUtils.anonymousUsersEnabled() && user != null && user.getLogins().isEmpty()) { + if (user != null && user.getLogins().isEmpty()) { session.invalidate(); } } @@ -1460,7 +1458,7 @@ public Response loginLDAP(@Context HttpServletRequest request, @Context HttpServ HttpSession session = request.getSession(false); if (session != null) { User user = (User) session.getAttribute(Constants.SESSION_USER); - if (!AbstractSecurityUtils.anonymousUsersEnabled() && user != null && user.getLogins().isEmpty()) { + if (user != null && user.getLogins().isEmpty()) { session.invalidate(); } } @@ -1475,7 +1473,7 @@ public Response loginLDAP(@Context HttpServletRequest request, @Context HttpServ HttpSession session = request.getSession(false); if (session != null) { User user = (User) session.getAttribute(Constants.SESSION_USER); - if (!AbstractSecurityUtils.anonymousUsersEnabled() && user != null && user.getLogins().isEmpty()) { + if (user != null && user.getLogins().isEmpty()) { session.invalidate(); } } @@ -1535,7 +1533,7 @@ public Response changeADPassword(@Context HttpServletRequest request, @Context H HttpSession session = request.getSession(false); if (session != null) { User user = (User) session.getAttribute(Constants.SESSION_USER); - if (!AbstractSecurityUtils.anonymousUsersEnabled() && user != null && user.getLogins().isEmpty()) { + if (user != null && user.getLogins().isEmpty()) { session.invalidate(); } } diff --git a/src/prerna/semoss/web/services/local/auth/EngineAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/EngineAuthorizationResource.java index b7d23208..c2dfd899 100644 --- a/src/prerna/semoss/web/services/local/auth/EngineAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/EngineAuthorizationResource.java @@ -92,7 +92,7 @@ public Response getEngines(@Context HttpServletRequest request, @QueryParam("eng List engines = WebUtility.inputSanitizer(engineFilter); List types = WebUtility.inputSanitizer(engineTypes); List keys = WebUtility.inputSanitizer(metaKeys); - return ResourceUtility.respondAllowingAnonymous(request, "list the engines they can access", user -> { + return ResourceUtility.respond(request, "list the engines they can access", user -> { MyEnginesReactor reactor = new MyEnginesReactor(); reactor.In(); Insight temp = new Insight(); @@ -164,7 +164,7 @@ public Response getEngines(@Context HttpServletRequest request, @QueryParam("eng @Produces("application/json") @Path("getEngines") public Response getEnginesPOST(@Context HttpServletRequest request) { - return ResourceUtility.respondAllowingAnonymous(request, "list the engines they can access", user -> { + return ResourceUtility.respond(request, "list the engines they can access", user -> { MyEnginesReactor reactor = new MyEnginesReactor(); reactor.In(); Insight temp = new Insight(); @@ -257,7 +257,7 @@ public Response getUserEnginePermission(@Context HttpServletRequest request, @QueryParam("engineId") String engineId) { String engine = WebUtility.inputSanitizer(engineId); String action = "read their permission on engine " + engine; - return ResourceUtility.respondAllowingAnonymous(request, action, user -> { + return ResourceUtility.respond(request, action, user -> { String permission = SecurityEngineUtils.getActualUserEnginePermission(user, engine); if (permission == null) { // are you discoverable? @@ -294,7 +294,7 @@ public Response getEngineUsers(@Context HttpServletRequest request, @QueryParam( String term = WebUtility.inputSQLSanitizer(searchTerm); String level = WebUtility.inputSanitizer(permission); String searchParam = term != null ? term : member; - return ResourceUtility.respondAllowingAnonymous(request, "list the users of engine " + engine, user -> { + return ResourceUtility.respond(request, "list the users of engine " + engine, user -> { List> members = SecurityEngineUtils.getEngineUsers(user, engine, searchParam, level, limit, offset); long totalMembers = SecurityEngineUtils.getEngineUsersCount(user, engine, searchParam, level); @@ -595,7 +595,7 @@ public Response getEngineUsersNoCredentials(@Context HttpServletRequest request, @QueryParam(MicrosoftGraphUserLookup.LOOKUP_PARAM) String msGraphLookup) { String engine = WebUtility.inputSanitizer(engineId); String term = WebUtility.inputSQLSanitizer(searchTerm); - return ResourceUtility.respondAllowingAnonymous(request, "find people to add to engine " + engine, user -> { + return ResourceUtility.respond(request, "find people to add to engine " + engine, user -> { // when the directory is not used // then we will look at our security db if (!MicrosoftGraphUserLookup.useDirectory(msGraphLookup)) { diff --git a/src/prerna/semoss/web/services/local/auth/GroupAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/GroupAuthorizationResource.java index 8cf8685d..21c5d880 100644 --- a/src/prerna/semoss/web/services/local/auth/GroupAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/GroupAuthorizationResource.java @@ -52,8 +52,7 @@ * act as an ordinary user; admins manage every custom group under * {@code /auth/admin/group}. The owner of a project or engine can see who * manages a custom group before they give it access. - * {@link SecurityGroupManagerUtils} checks who may do what; anonymous sessions - * can do nothing here. + * {@link SecurityGroupManagerUtils} checks who may do what. */ @Path("/auth/group") @PermitAll diff --git a/src/prerna/semoss/web/services/local/auth/GroupEngineAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/GroupEngineAuthorizationResource.java index 77d36312..d6e172b3 100644 --- a/src/prerna/semoss/web/services/local/auth/GroupEngineAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/GroupEngineAuthorizationResource.java @@ -79,8 +79,8 @@ public Response getGroupAppPermission(@Context HttpServletRequest request, @Quer String groupType = AuthProvider.getProviderLabel(WebUtility.inputSanitizer(type)); String engine = WebUtility.inputSanitizer(appId); String group = WebUtility.inputSQLSanitizer(groupId); - return ResourceUtility.respondAllowingAnonymous(request, - "read the permission of group " + group + " on engine " + engine, user -> { + return ResourceUtility.respond(request, "read the permission of group " + group + " on engine " + engine, + user -> { Integer permissionCode = SecurityGroupEngineUtils.getGroupDatabasePermission( ValueUtils.requireNonBlank(group, GROUP_ID_REQUIRED), ValueUtils.requireNonBlank(groupType, GROUP_TYPE_REQUIRED), @@ -194,19 +194,18 @@ public Response getAllGroupsWithAccessToEngine(@Context HttpServletRequest reque @QueryParam("engineId") String engineId, @QueryParam("limit") long limit, @QueryParam("offset") long offset) { String engine = WebUtility.inputSanitizer(engineId); - return ResourceUtility.respondAllowingAnonymous(request, "list the groups with access to engine " + engine, - user -> { - if (engine == null || engine.isEmpty()) { - throw new IllegalArgumentException("Must define the engineId"); - } - List> groups = SecurityGroupEngineUtils.getGroupsWithAccessToEngine(user, - engine, limit, offset); - long totalGroups = SecurityGroupEngineUtils.getNumGroupsWithAccessToEngine(user, engine); - Map ret = new HashMap<>(); - ret.put("totalGroups", totalGroups); - ret.put("groups", groups); - return ret; - }); + return ResourceUtility.respond(request, "list the groups with access to engine " + engine, user -> { + if (engine == null || engine.isEmpty()) { + throw new IllegalArgumentException("Must define the engineId"); + } + List> groups = SecurityGroupEngineUtils.getGroupsWithAccessToEngine(user, engine, limit, + offset); + long totalGroups = SecurityGroupEngineUtils.getNumGroupsWithAccessToEngine(user, engine); + Map ret = new HashMap<>(); + ret.put("totalGroups", totalGroups); + ret.put("groups", groups); + return ret; + }); } /** @@ -228,8 +227,8 @@ public Response getAvailableGroupsForEngine(@Context HttpServletRequest request, @QueryParam("limit") long limit, @QueryParam("offset") long offset) { String engine = WebUtility.inputSanitizer(engineId); String term = WebUtility.inputSQLSanitizer(searchTerm); - return ResourceUtility.respondAllowingAnonymous(request, - "list the groups that can be given access to engine " + engine, user -> { + return ResourceUtility.respond(request, "list the groups that can be given access to engine " + engine, + user -> { if (engine == null || engine.isEmpty()) { throw new IllegalArgumentException("Must define the engineId"); } diff --git a/src/prerna/semoss/web/services/local/auth/GroupInsightAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/GroupInsightAuthorizationResource.java index 42833d18..c7e0b951 100644 --- a/src/prerna/semoss/web/services/local/auth/GroupInsightAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/GroupInsightAuthorizationResource.java @@ -78,7 +78,7 @@ public Response getGroupInsightPermission(@Context HttpServletRequest request, String groupType = AuthProvider.getProviderLabel(WebUtility.inputSQLSanitizer(type)); String insight = WebUtility.inputSQLSanitizer(insightId); String group = WebUtility.inputSQLSanitizer(groupId); - return ResourceUtility.respondAllowingAnonymous(request, + return ResourceUtility.respond(request, "read the permission of group " + group + " on insight " + insight + " of project " + project, user -> { Integer permissionCode = SecurityGroupInsightsUtils.getGroupInsightPermission( ValueUtils.requireNonBlank(group, GROUP_ID_REQUIRED), diff --git a/src/prerna/semoss/web/services/local/auth/GroupProjectAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/GroupProjectAuthorizationResource.java index 001d89f3..0027f680 100644 --- a/src/prerna/semoss/web/services/local/auth/GroupProjectAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/GroupProjectAuthorizationResource.java @@ -77,8 +77,8 @@ public Response getGroupProjectPermission(@Context HttpServletRequest request, String project = WebUtility.inputSanitizer(projectId); String groupType = AuthProvider.getProviderLabel(WebUtility.inputSanitizer(type)); String group = WebUtility.inputSQLSanitizer(groupId); - return ResourceUtility.respondAllowingAnonymous(request, - "read the permission of group " + group + " on project " + project, user -> { + return ResourceUtility.respond(request, "read the permission of group " + group + " on project " + project, + user -> { Integer permissionCode = SecurityGroupProjectUtils.getGroupProjectPermission( ValueUtils.requireNonBlank(group, GROUP_ID_REQUIRED), ValueUtils.requireNonBlank(groupType, GROUP_TYPE_REQUIRED), @@ -187,19 +187,18 @@ public Response getAllGroupsWithAccessToProject(@Context HttpServletRequest requ @QueryParam("projectId") String projectId, @QueryParam("limit") long limit, @QueryParam("offset") long offset) { String project = WebUtility.inputSanitizer(projectId); - return ResourceUtility.respondAllowingAnonymous(request, "list the groups with access to project " + project, - user -> { - if (project == null || project.isEmpty()) { - throw new IllegalArgumentException("Must define the projectId"); - } - List> groups = SecurityGroupProjectUtils.getGroupsWithAccessToProject(user, - project, limit, offset); - long totalGroups = SecurityGroupProjectUtils.getNumGroupsWithAccessToProject(user, project); - Map ret = new HashMap<>(); - ret.put("totalGroups", totalGroups); - ret.put("groups", groups); - return ret; - }); + return ResourceUtility.respond(request, "list the groups with access to project " + project, user -> { + if (project == null || project.isEmpty()) { + throw new IllegalArgumentException("Must define the projectId"); + } + List> groups = SecurityGroupProjectUtils.getGroupsWithAccessToProject(user, project, + limit, offset); + long totalGroups = SecurityGroupProjectUtils.getNumGroupsWithAccessToProject(user, project); + Map ret = new HashMap<>(); + ret.put("totalGroups", totalGroups); + ret.put("groups", groups); + return ret; + }); } /** @@ -221,8 +220,8 @@ public Response getAvailableGroupsForProject(@Context HttpServletRequest request @QueryParam("limit") long limit, @QueryParam("offset") long offset) { String project = WebUtility.inputSanitizer(projectId); String term = WebUtility.inputSQLSanitizer(searchTerm); - return ResourceUtility.respondAllowingAnonymous(request, - "list the groups that can be given access to project " + project, user -> { + return ResourceUtility.respond(request, "list the groups that can be given access to project " + project, + user -> { if (project == null || project.isEmpty()) { throw new IllegalArgumentException("Must define the projectId"); } diff --git a/src/prerna/semoss/web/services/local/auth/InsightAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/InsightAuthorizationResource.java index 3062206e..1c2a1b05 100644 --- a/src/prerna/semoss/web/services/local/auth/InsightAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/InsightAuthorizationResource.java @@ -73,7 +73,7 @@ public Response getInsights(@Context HttpServletRequest request, @QueryParam("pr String term = WebUtility.inputSQLSanitizer(searchTerm); String offsetValue = WebUtility.inputSanitizer(offset); String limitValue = WebUtility.inputSanitizer(limit); - return ResourceUtility.respondAllowingAnonymous(request, "search their insights", user -> { + return ResourceUtility.respond(request, "search their insights", user -> { List projectFilter = null; if (project != null && !project.trim().isEmpty()) { projectFilter = new ArrayList<>(); @@ -97,8 +97,7 @@ public Response getInsights(@Context HttpServletRequest request, @QueryParam("pr public Response getProjectInsights(@Context HttpServletRequest request, @QueryParam("projectId") String projectId, @QueryParam("searchTerm") String searchTerm) { String project = WebUtility.inputSanitizer(projectId); - return ResourceUtility.respondAllowingAnonymous(request, - "list the insights they can edit in project " + project, + return ResourceUtility.respond(request, "list the insights they can edit in project " + project, user -> SecurityInsightUtils.getUserEditableInsights(user, project)); } @@ -116,7 +115,7 @@ public Response getUserInsightPermission(@Context HttpServletRequest request, @QueryParam("projectId") String projectId, @QueryParam("insightId") String insightId) { String project = WebUtility.inputSanitizer(projectId); String insight = WebUtility.inputSanitizer(insightId); - return ResourceUtility.respondAllowingAnonymous(request, + return ResourceUtility.respond(request, "read their permission on insight " + insight + " of project " + project, user -> { String permission = SecurityInsightUtils.getActualUserInsightPermission(user, project, insight); if (permission == null) { @@ -147,8 +146,8 @@ public Response getInsightUsers(@Context HttpServletRequest request, @QueryParam String memberId = WebUtility.inputSQLSanitizer(userId); String insight = WebUtility.inputSanitizer(insightId); String memberPermission = WebUtility.inputSanitizer(permission); - return ResourceUtility.respondAllowingAnonymous(request, - "list the users of insight " + insight + " of project " + project, user -> { + return ResourceUtility.respond(request, "list the users of insight " + insight + " of project " + project, + user -> { List> members = SecurityInsightUtils.getInsightUsers(user, project, insight, memberId, memberPermission, limit, offset); long totalMembers = SecurityInsightUtils.getInsightUsersCount(user, project, insight, memberId, @@ -383,7 +382,7 @@ public Response getInsightUsersNoCredentials(@Context HttpServletRequest request String project = WebUtility.inputSanitizer(projectId); String insight = WebUtility.inputSanitizer(insightId); String term = WebUtility.inputSQLSanitizer(searchTerm); - return ResourceUtility.respondAllowingAnonymous(request, + return ResourceUtility.respond(request, "list the users without access to insight " + insight + " of project " + project, user -> SecurityInsightUtils.getInsightUsersNoCredentials(user, project, insight, term, limit, offset)); } diff --git a/src/prerna/semoss/web/services/local/auth/PermissionBatchResource.java b/src/prerna/semoss/web/services/local/auth/PermissionBatchResource.java index eb5dd4e0..2844e904 100644 --- a/src/prerna/semoss/web/services/local/auth/PermissionBatchResource.java +++ b/src/prerna/semoss/web/services/local/auth/PermissionBatchResource.java @@ -55,8 +55,7 @@ * {@link SecurityAccessPermissionBatchUtils} checks every change against the * same rules as the single permission endpoints, with the user's own * permissions: being an admin counts for nothing here, and - * {@link AdminPermissionBatchResource} is the admin mode. Anonymous sessions - * can do nothing here. + * {@link AdminPermissionBatchResource} is the admin mode. */ @Path("/auth/permissionBatch") @PermitAll diff --git a/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java index 730d0cab..c0f97aef 100644 --- a/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java @@ -98,7 +98,7 @@ public Response getProjectsGET(@Context HttpServletRequest request, String term = WebUtility.inputSQLSanitizer(searchTerm); List projects = WebUtility.inputSanitizer(projectFilter); List keys = WebUtility.inputSanitizer(metaKeys); - return ResourceUtility.respondAllowingAnonymous(request, "list the projects they can access", user -> { + return ResourceUtility.respond(request, "list the projects they can access", user -> { MyProjectsReactor reactor = new MyProjectsReactor(); reactor.In(); Insight temp = new Insight(); @@ -163,7 +163,7 @@ public Response getProjectsGET(@Context HttpServletRequest request, @Produces("application/json") @Path("getProjects") public Response getProjectsPOST(@Context HttpServletRequest request) { - return ResourceUtility.respondAllowingAnonymous(request, "list the projects they can access", user -> { + return ResourceUtility.respond(request, "list the projects they can access", user -> { MyProjectsReactor reactor = new MyProjectsReactor(); reactor.In(); Insight temp = new Insight(); @@ -247,7 +247,7 @@ public Response getUserProjectPermission(@Context HttpServletRequest request, @QueryParam("projectId") String projectId, @QueryParam("searchTerm") String searchTerm) { String project = WebUtility.inputSanitizer(projectId); String action = "read their permission on project " + project; - return ResourceUtility.respondAllowingAnonymous(request, action, user -> { + return ResourceUtility.respond(request, action, user -> { String permission = SecurityProjectUtils.getActualUserProjectPermission(user, project); if (permission == null) { // are you discoverable? @@ -283,7 +283,7 @@ public Response getProjectUsers(@Context HttpServletRequest request, @QueryParam String term = WebUtility.inputSQLSanitizer(searchTerm); String level = WebUtility.inputSanitizer(permission); String searchParam = term != null ? term : member; - return ResourceUtility.respondAllowingAnonymous(request, "list the users of project " + project, user -> { + return ResourceUtility.respond(request, "list the users of project " + project, user -> { List> members = SecurityProjectUtils.getProjectUsers(user, project, searchParam, level, limit, offset); long totalMembers = SecurityProjectUtils.getProjectUsersCount(user, project, searchParam, level); @@ -624,7 +624,7 @@ public Response getProjectUsersNoCredentials(@Context HttpServletRequest request @QueryParam(MicrosoftGraphUserLookup.LOOKUP_PARAM) String msGraphLookup) { String project = WebUtility.inputSanitizer(projectId); String term = WebUtility.inputSQLSanitizer(searchTerm); - return ResourceUtility.respondAllowingAnonymous(request, "find people to add to project " + project, user -> { + return ResourceUtility.respond(request, "find people to add to project " + project, user -> { // when the directory is not used // then we will look at our security db if (!MicrosoftGraphUserLookup.useDirectory(msGraphLookup)) { diff --git a/src/prerna/semoss/web/services/local/auth/UserAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/UserAuthorizationResource.java index a8cb0bce..bd2174a2 100644 --- a/src/prerna/semoss/web/services/local/auth/UserAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/UserAuthorizationResource.java @@ -296,7 +296,7 @@ public Response deleteUserAccessKey(@Context HttpServletRequest request) { @Path("/getUserAccessKeys") @Produces("application/json") public Response getUserAccessKeys(@Context HttpServletRequest request) { - return ResourceUtility.respondAllowingAnonymous(request, "list their access keys", + return ResourceUtility.respond(request, "list their access keys", user -> SecurityUserAccessKeyUtils.getUserAccessKeyInfo(user.getPrimaryLoginToken())); } diff --git a/src/prerna/upload/CatalogImageUploader.java b/src/prerna/upload/CatalogImageUploader.java index 25532076..7a342b88 100644 --- a/src/prerna/upload/CatalogImageUploader.java +++ b/src/prerna/upload/CatalogImageUploader.java @@ -98,9 +98,6 @@ public static Response upload(ServletContext context, HttpServletRequest request } catch (IllegalAccessException e) { return error("User session is invalid", 401); } - if (user.isAnonymous()) { - return error("Must be logged in to upload an image", 401); - } if (!WebUtility.isSafePathSegment(id)) { return error("Invalid " + (project ? "project" : "engine") + " id", 400); } diff --git a/src/prerna/upload/FileUploader.java b/src/prerna/upload/FileUploader.java index bbbf40e1..87deadab 100644 --- a/src/prerna/upload/FileUploader.java +++ b/src/prerna/upload/FileUploader.java @@ -311,12 +311,6 @@ public Response baseUpload(@Context ServletContext context, @Context HttpServlet return permResponse; } - if (user.isAnonymous() && in.isSavedInsight()) { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload files to a saved insight"); - return WebUtility.getResponse(errorMap, 400); - } - if (in.isSavedInsight() && !SecurityInsightUtils.userCanEditInsight(user, in.getProjectId(), in.getRdbmsId())) { Map errorMap = new HashMap<>(); errorMap.put(Constants.ERROR_MESSAGE, "User does not edit access for this insight"); @@ -489,12 +483,6 @@ public Response userAssetsUpload(@Context ServletContext context, @Context HttpS return permResponse; } - if (user.isAnonymous()) { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload files to user assets"); - return WebUtility.getResponse(errorMap, 400); - } - ThreadStore.setSessionId(request.getSession().getId()); try { List fileItems = processRequest(context, request, insightId); @@ -679,12 +667,6 @@ private Insight getValidInsight(String insightId) { * @return A Response object if permissions are denied, otherwise null. */ private Response checkGeneralUserPermissions(User user) { - if (user.isAnonymous() && !AbstractSecurityUtils.anonymousUserUploadData()) { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload files"); - return WebUtility.getResponse(errorMap, 400); - } - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(user)) { Map errorMap = new HashMap<>(); errorMap.put(Constants.ERROR_MESSAGE, diff --git a/src/prerna/upload/ImageUploader.java b/src/prerna/upload/ImageUploader.java index 80b853e4..577947dc 100644 --- a/src/prerna/upload/ImageUploader.java +++ b/src/prerna/upload/ImageUploader.java @@ -98,12 +98,6 @@ public Response uploadEngineImage(@Context ServletContext context, @Context Http "Session could not be validated in order to upload the engine image"); return WebUtility.getResponse(errorMap, 400); } - - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an engine image"); - return WebUtility.getResponse(errorMap, 400); - } } else { returnMap.put(Constants.ERROR_MESSAGE, "User session is invalid"); return WebUtility.getResponse(returnMap, 400); @@ -303,12 +297,6 @@ public Response deleteEngineImage(@Context HttpServletRequest request) throws SQ return WebUtility.getResponse(errorMap, 400); } - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an engine image"); - return WebUtility.getResponse(errorMap, 400); - } - if (!SecurityEngineUtils.userCanEditEngine(user, engineId)) { returnMap.put(Constants.ERROR_MESSAGE, "User does not have access to this engine or the engine id does not exist"); @@ -453,12 +441,6 @@ public Response uploadProjectImage(@Context ServletContext context, @Context Htt "Session could not be validated in order to upload the project image"); return WebUtility.getResponse(errorMap, 400); } - - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an project image"); - return WebUtility.getResponse(errorMap, 400); - } } else { returnMap.put(Constants.ERROR_MESSAGE, "User session is invalid"); return WebUtility.getResponse(returnMap, 400); @@ -603,12 +585,6 @@ public Response deleteProjectImage(@Context HttpServletRequest request) throws S return WebUtility.getResponse(errorMap, 400); } - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an project image"); - return WebUtility.getResponse(errorMap, 400); - } - try { projectId = SecurityProjectUtils.testUserProjectIdForAlias(user, projectId); } catch (Exception e) { @@ -708,12 +684,6 @@ public Response uploadInsightImage(@Context ServletContext context, @Context Htt "Session could not be validated in order to upload the insight image"); return WebUtility.getResponse(errorMap, 400); } - - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an insight image"); - return WebUtility.getResponse(errorMap, 400); - } } else { returnMap.put(Constants.ERROR_MESSAGE, "User session is invalid"); return WebUtility.getResponse(returnMap, 400); @@ -867,12 +837,6 @@ public Response deleteInsightImage(@Context HttpServletRequest request) throws S return WebUtility.getResponse(errorMap, 400); } - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an app image"); - return WebUtility.getResponse(errorMap, 400); - } - try { projectId = SecurityProjectUtils.testUserProjectIdForAlias(user, projectId); } catch (Exception e) { @@ -970,12 +934,6 @@ public Response uploadDatabaseImage(@Context ServletContext context, @Context Ht "Session could not be validated in order to upload the engine image"); return WebUtility.getResponse(errorMap, 400); } - - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an engine image"); - return WebUtility.getResponse(errorMap, 400); - } } else { returnMap.put(Constants.ERROR_MESSAGE, "User session is invalid"); return WebUtility.getResponse(returnMap, 400); @@ -1187,12 +1145,6 @@ public Response deleteDatabaseImage(@Context HttpServletRequest request) throws return WebUtility.getResponse(errorMap, 400); } - if (user.isAnonymous()) { - HashMap errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Must be logged in to upload an engine image"); - return WebUtility.getResponse(errorMap, 400); - } - if (!SecurityEngineUtils.userCanEditEngine(user, engineId)) { returnMap.put(Constants.ERROR_MESSAGE, "User does not have access to this engine or the engine id does not exist"); diff --git a/src/prerna/web/conf/AccountLockedFilter.java b/src/prerna/web/conf/AccountLockedFilter.java index 2fcdcf00..d32f7123 100644 --- a/src/prerna/web/conf/AccountLockedFilter.java +++ b/src/prerna/web/conf/AccountLockedFilter.java @@ -63,7 +63,7 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 user = (User) session.getAttribute(Constants.SESSION_USER); } - if (user != null && !user.isAnonymous()) { + if (user != null) { AccessToken token = user.getAccessToken(user.getPrimaryLogin()); boolean isLocked = token.isLocked(); if (isLocked) { diff --git a/src/prerna/web/conf/AnonymousUserFilter.java b/src/prerna/web/conf/AnonymousUserFilter.java deleted file mode 100644 index bb2bde45..00000000 --- a/src/prerna/web/conf/AnonymousUserFilter.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.web.conf; - -import java.io.IOException; -import java.util.UUID; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.FilterConfig; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpSession; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.util.Constants; -import prerna.web.services.util.WebUtility; - -public class AnonymousUserFilter implements Filter { - - private static final Logger classLogger = LogManager.getLogger(AnonymousUserFilter.class); - - @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) - throws IOException, ServletException { - if (AbstractSecurityUtils.anonymousUsersEnabled()) { - HttpSession session = ((HttpServletRequest) arg0).getSession(true); - - User user = (User) session.getAttribute(Constants.SESSION_USER); - if (user == null) { - user = new User(); - user.setAnonymous(true); - - String cookieToFind = DBLoader.getSessionIdKey() + "_unk"; - Cookie[] cookies = ((HttpServletRequest) arg0).getCookies(); - if (cookies != null) { - // loop through and see if we have a cookie for this user - for (Cookie c : cookies) { - if (c.getName().equals(cookieToFind)) { - String uId = WebUtility.cleanHttpResponse(c.getValue()); - user.setAnonymousId(uId); - // found the cookie - // no need to continue loop - break; - } - } - } - - boolean foundPrevoiusCookie = user.getAnonymousId() != null; - if (!foundPrevoiusCookie) { - // set a new id + add a cookie - String uId = "UNK_" + UUID.randomUUID().toString(); - user.setAnonymousId(uId); - - Cookie c = new Cookie(cookieToFind, uId); - c.setPath(((HttpServletRequest) arg0).getContextPath()); - c.setHttpOnly(true); - c.setSecure(arg0.isSecure()); - ((HttpServletResponse) arg1).addCookie(c); - } - // add to session - session.setAttribute(Constants.SESSION_USER, user); - session.setAttribute(Constants.SESSION_USER_ID_LOG, user.getAnonymousId()); - - // log the user login - if (foundPrevoiusCookie) { - classLogger.info("User is logging in anonymously"); - } else { - classLogger.info("User is logging in anonymously for first time"); - } - } - } - - arg2.doFilter(arg0, arg1); - } - - @Override - public void destroy() { - // destroy - - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - // initialize - - } - -} diff --git a/src/prerna/web/conf/DBLoader.java b/src/prerna/web/conf/DBLoader.java index 786213a1..6dd962b9 100644 --- a/src/prerna/web/conf/DBLoader.java +++ b/src/prerna/web/conf/DBLoader.java @@ -147,19 +147,6 @@ public void contextInitialized(ServletContextEvent arg0) { } context.setInitParameter(Constants.ADMIN_SET_EXPORTER, adminSetExporter); - // see if we allow anonymous users - String anonymousUsersEnabled = context.getInitParameter(Constants.ANONYMOUS_USER_ALLOWED); - if (anonymousUsersEnabled == null) { - anonymousUsersEnabled = "false"; - } - context.setInitParameter(Constants.ANONYMOUS_USER_ALLOWED, anonymousUsersEnabled); - // see if anonymous users can upload data - String anonymousUsersUploadData = context.getInitParameter(Constants.ANONYMOUS_USER_UPLOAD_DATA); - if (anonymousUsersUploadData == null) { - anonymousUsersUploadData = "false"; - } - context.setInitParameter(Constants.ANONYMOUS_USER_UPLOAD_DATA, anonymousUsersUploadData); - // see if we redirect to logout page or back to login screen String useLogoutPage = context.getInitParameter(Constants.USE_LOGOUT_PAGE); if (useLogoutPage == null) { @@ -209,8 +196,6 @@ public void contextInitialized(ServletContextEvent arg0) { // load it as a boolean instead of us searching within DIHelper DIHelper.getInstance().setLocalProperty(Constants.ADMIN_SET_PUBLISHER, adminSetPublisher); DIHelper.getInstance().setLocalProperty(Constants.ADMIN_SET_EXPORTER, adminSetExporter); - DIHelper.getInstance().setLocalProperty(Constants.ANONYMOUS_USER_ALLOWED, anonymousUsersEnabled); - DIHelper.getInstance().setLocalProperty(Constants.ANONYMOUS_USER_UPLOAD_DATA, anonymousUsersUploadData); DIHelper.getInstance().setLocalProperty(Constants.USE_LOGOUT_PAGE, useLogoutPage); DIHelper.getInstance().setLocalProperty(Constants.SESSION_ID_KEY, SESSION_ID_KEY); DIHelper.getInstance().setLocalProperty(Constants.CONTEXT_PATH_KEY, contextPath); diff --git a/src/prerna/web/conf/NoUserInSessionFilter.java b/src/prerna/web/conf/NoUserInSessionFilter.java index ce1880d2..9ef9137f 100644 --- a/src/prerna/web/conf/NoUserInSessionFilter.java +++ b/src/prerna/web/conf/NoUserInSessionFilter.java @@ -42,7 +42,6 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; import prerna.semoss.web.services.local.ResourceUtility; import prerna.util.Constants; import prerna.util.SocialPropertiesUtil; @@ -72,7 +71,7 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 user = (User) session.getAttribute(Constants.SESSION_USER); } - if (user == null || (!AbstractSecurityUtils.anonymousUsersEnabled() && user.getLogins().isEmpty())) { + if (user == null || user.getLogins().isEmpty()) { // don't know what i am redirecting // send back an error and have the client remake the request setInvalidEntryRedirect(context, arg0, arg1); diff --git a/src/prerna/web/conf/NoUserInSessionTrustedTokenFilter.java b/src/prerna/web/conf/NoUserInSessionTrustedTokenFilter.java deleted file mode 100644 index d7e4bed5..00000000 --- a/src/prerna/web/conf/NoUserInSessionTrustedTokenFilter.java +++ /dev/null @@ -1,269 +0,0 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.web.conf; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.catalina.session.StandardManager; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.FilterConfig; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpSession; -import prerna.auth.AccessToken; -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.semoss.web.services.local.SessionResource; -import prerna.util.Constants; -import prerna.web.services.util.WebUtility; - -public class NoUserInSessionTrustedTokenFilter implements Filter { - - private static final Logger classLogger = LogManager.getLogger(NoUserInSessionTrustedTokenFilter.class); - - private static String TRUSTED_TOKEN_PREFIX = "trustedTokenPrefix"; - private static String TRUSTED_TOKEN_DOMAIN = "trustedTokenDomain"; - - private static String tokenName = null; - private static List trustedDomains = null; - - // maps from the IP the user is coming in with the cookie - private static Map sessionMapper = new ConcurrentHashMap<>(); - - private FilterConfig filterConfig; - - @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) - throws IOException, ServletException { - setInitParams(arg0); - - // this will be the full path of the request - // like http://localhost:8080/Monolith_Dev/api/engine/runPixel - String fullUrl = WebUtility.cleanHttpResponse(((HttpServletRequest) arg0).getRequestURL().toString()); - String contextPath = ((HttpServletRequest) arg0).getContextPath(); - HttpSession session = ((HttpServletRequest) arg0).getSession(false); - - User user = null; - if (session != null) { - user = (User) session.getAttribute(Constants.SESSION_USER); - } - - // if we have a user, there is nothing to do - if (user == null) { - - // the front end comes with - // fullUrl?prefix_token=userId - // check if the ip address is allowed - // check if the userId actually exists - // if first time, add the user - // if not, redirect the GET/POST call - - HttpServletRequest req = (HttpServletRequest) arg0; - // grab the token id - // if the token exists - String userId = WebUtility.cleanHttpResponse(req.getParameter(tokenName)); - if (userId != null) { - boolean redirectToExistingSession = false; - String redirectSessionId = sessionMapper.get(userId); - if (redirectSessionId != null) { - // validate that the session exists within tomcats session manager - session = ((HttpServletRequest) arg0).getSession(); - StandardManager manager = SessionResource.getManager(session); - if (manager.getSession(redirectSessionId) != null) { - redirectToExistingSession = true; - // we are going to try to redirect - // so invalidate this new session - if (((HttpServletRequest) arg0).isRequestedSessionIdValid()) { - session.invalidate(); - } - } else { - // remove from the session mapper - sessionMapper.remove(userId); - } - } - if (!redirectToExistingSession) { - // grab the ip address - String ipAddress = req.getHeader("X-FORWARDED-FOR"); - if (ipAddress == null) { - ipAddress = req.getRemoteAddr(); - } - // check if the ip address is allowed - boolean allow = trustedDomains.contains("*"); - if (!allow) { - for (String domain : trustedDomains) { - if (ipAddress.matches(domain)) { - allow = true; - break; - } - } - } - if (allow && SecurityQueryUtils.checkUserExist(userId)) { - // you are allowed - // i just have to check if the token id exists - // and id you do, i make the user object - user = new User(); - AccessToken token = new AccessToken(); - token.setProvider(AuthProvider.WINDOWS_USER); - token.setId(userId); - token.setName(userId); - user.setAccessToken(token); - // if the session hasn't been instantiated yet - // start one - if (session == null) { - session = ((HttpServletRequest) arg0).getSession(); - } - session.setAttribute(Constants.SESSION_USER, user); - - String sessionId = session.getId(); - sessionMapper.put(userId, sessionId); - - // add the session id cookie - // use addHeader to allow for SameSite option - // SameSite only works if Secure tag also there - String setCookieString = DBLoader.getSessionIdKey() + "=" + sessionId + "; Path=" + contextPath - + "; HttpOnly" - + ((ClusterUtil.IS_CLUSTER || req.isSecure()) ? "; Secure; SameSite=None" : ""); - ((HttpServletResponse) arg1).addHeader("Set-Cookie", setCookieString); - } else { - // invalidate the session - if (((HttpServletRequest) arg0).isRequestedSessionIdValid()) { - session.invalidate(); - } - } - } else { - // this is the case where you redirect - // we have also validated that the session id is active - - // add the session id cookie -// Cookie k = new Cookie(DBLoader.getSessionIdKey(), redirectSessionId); -// k.setHttpOnly(true); -// k.setSecure(req.isSecure()); -// k.setPath(contextPath); -// ((HttpServletResponse)arg1).addCookie(k); - // replace any other session id cookies - Cookie[] cookies = req.getCookies(); - if (cookies != null) { - classLogger.info("Forcing session value !"); - for (Cookie c : cookies) { - if (c.getName().equals(DBLoader.getSessionIdKey())) { - if (c.getName().equalsIgnoreCase(DBLoader.getSessionIdKey())) { - c.setValue(redirectSessionId); - } - } - } - } - - // add the session id cookie - // use addHeader to allow for SameSite option - // SameSite only works if Secure tag also there - String setCookieString = DBLoader.getSessionIdKey() + "=" + redirectSessionId + "; Path=" - + contextPath + "; HttpOnly" - + ((ClusterUtil.IS_CLUSTER || req.isSecure()) ? "; Secure; SameSite=None" : ""); - - String method = req.getMethod(); - if (method.equalsIgnoreCase("GET")) { - ((HttpServletResponse) arg1).addHeader("Set-Cookie", setCookieString); - ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - ((HttpServletResponse) arg1).sendRedirect(fullUrl + "?" + req.getQueryString()); - return; - } else if (method.equalsIgnoreCase("POST")) { - ((HttpServletResponse) arg1).addHeader("Set-Cookie", setCookieString); - ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); - ((HttpServletResponse) arg1).setHeader("Location", fullUrl); - return; - } - } - } - } -// else { -// System.out.println("Have user = " + user.getAccessToken(user.getPrimaryLogin()).getId()); -// } - arg2.doFilter(arg0, arg1); - } - - @Override - public void destroy() { - // TODO Auto-generated method stub - - } - - /** - * Remove the session from the mapper - * - * @param sessionId - */ - public static void removeSession(String sessionId) { - Iterator iterator = NoUserInSessionTrustedTokenFilter.sessionMapper.keySet().iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - if (NoUserInSessionTrustedTokenFilter.sessionMapper.get(key).equals(sessionId)) { - // remove this - iterator.remove(); - } - } - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - this.filterConfig = arg0; - } - - private void setInitParams(ServletRequest arg0) { - // the token name - if (NoUserInSessionTrustedTokenFilter.tokenName == null) { - NoUserInSessionTrustedTokenFilter.tokenName = this.filterConfig - .getInitParameter(NoUserInSessionTrustedTokenFilter.TRUSTED_TOKEN_PREFIX); - } - - // the token domains - if (NoUserInSessionTrustedTokenFilter.trustedDomains == null) { - String[] trustedIPs = this.filterConfig - .getInitParameter(NoUserInSessionTrustedTokenFilter.TRUSTED_TOKEN_DOMAIN).split(","); - NoUserInSessionTrustedTokenFilter.trustedDomains = new Vector<>(); - for (String trustedIP : trustedIPs) { - NoUserInSessionTrustedTokenFilter.trustedDomains.add(trustedIP.toLowerCase()); - } - } - } - -} diff --git a/src/prerna/web/conf/NoUserInSessionTrustedTokenListener.java b/src/prerna/web/conf/NoUserInSessionTrustedTokenListener.java deleted file mode 100644 index b9bb9dc0..00000000 --- a/src/prerna/web/conf/NoUserInSessionTrustedTokenListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.web.conf; - -import jakarta.servlet.http.HttpSessionEvent; -import jakarta.servlet.http.HttpSessionListener; - -public class NoUserInSessionTrustedTokenListener implements HttpSessionListener { - - @Override - public void sessionCreated(HttpSessionEvent se) { - // do nothing - - } - - @Override - public void sessionDestroyed(HttpSessionEvent se) { - // clean up the session map - String sessionId = se.getSession().getId(); - NoUserInSessionTrustedTokenFilter.removeSession(sessionId); - } - -}