From 6c452b5433134d92145647416ecef75e8c1214c8 Mon Sep 17 00:00:00 2001 From: "konstantina.galouni" Date: Thu, 25 Feb 2021 11:57:22 +0000 Subject: [PATCH] [Trunk | Admin Tools]: 1. pom.xml: Added dependency for spring security. 2. UoaAdminToolsApplication.java: Import AuthorizationConfiguration.class | Remove SecurityConfig.class from @EnableConfigurationProperties. 3. UoaAdminToolsConfiguration.java: Comment "addInterceptors()" method calling AuthorizationHandler with SecurityConfig. 4. SecurityConfig.java & AuthorizationHandler.java & AuthorizationUtils.java & CommunityInfo.java & UserInfo.java: Commented all contents of these files (files will be deleted in coming commit). 5. PortalSubscribersController.java: Comment imports from commeted files. 6. Notifications.java: Added field "aaiId" get getters and setters. 7. NotificationsController.java: a. Method "getNotifications()" is replaced by "getNotificationsForUser()" (/community/{pid}/notifications) - returns notification settings only for user who made the request (uoa-authorization-li$ b. Path changed for method "getNotifications()": /community/{pid}/notifications/all c. Remove "@RequestBody String email" parameter from method "deleteNotification()" - get email from user who made the request (uoa-authorization-library). d. In method "saveNotification()" get aaiId and email from user who made the request (uoa-authorization-library). e. Added checks and throw Exceptions in all methods. f. Added @PreAuthorize Portal Admins: "getNotifications()" (/community/{pid}/notifications/all) Portal Admins - Curators - Managers: "getNotificationsForUser()" (/community/{pid}/notifications), "deleteNotification()" (/community/{pid}/notifications), "saveNotification()" (/communit$ 8. ExploreController.java: a. Added checks and throw Exceptions in all methods. b. Added @PreAuthorize Portal Admins: "updateExplore()" (/explore/update), "insertExplore()" (/explore/save), "deleteExplore()" (/explore/delete). 9. ConnectController.java: a. Added checks and throw Exceptions in all methods. b. Added @PreAuthorize Portal Admins: "updateConnect()" (/connect/update), "insertConnect()" (/connect/save), "deleteConnect()" (/connect/delete). c. Commented methods "getLayoutForConnect()" and "updateLayoutForConnect()" (/connect/{pid}/layout). 10. CommunityController.java: a. Added checks and throw Exceptions in all methods. b. Added @PreAuthorize Portal Admins: "updateCommunity()" (/community/update), "insertCommunity()" (/community/save), "deleteCommunity()" (/community/delete). Portal Admin - Curators - Managers: "updateLayoutForCommunity()" (/community/{pid}/layout). 11. CuratorController.java: a. In "insertCurator() (/curator) set _id field with aaiId from user who made the request (uoa-authorization-library). b. Added @PreAuthorize Authenticated users: "getCuratorById()" (/curator/{id}), "insertCurator()" (/curator). Portal Admins: "deleteCurators()" (/curator). --- pom.xml | 8 +- .../UoaAdminToolsApplication.java | 8 +- .../UoaAdminToolsConfiguration.java | 20 +- .../properties/SecurityConfig.java | 80 ++-- .../controllers/CommunityController.java | 65 ++- .../controllers/ConnectController.java | 56 ++- .../controllers/CuratorController.java | 9 + .../controllers/ExploreController.java | 25 +- .../controllers/NotificationsController.java | 89 +++- .../PortalSubscribersController.java | 4 +- .../uoaadmintools/entities/Notifications.java | 10 + .../handlers/AuthorizationHandler.java | 132 +++--- .../handlers/utils/AuthorizationUtils.java | 418 +++++++++--------- .../handlers/utils/CommunityInfo.java | 162 +++---- .../handlers/utils/UserInfo.java | 92 ++-- 15 files changed, 673 insertions(+), 505 deletions(-) diff --git a/pom.xml b/pom.xml index 9df441d..c6a1c6d 100644 --- a/pom.xml +++ b/pom.xml @@ -50,10 +50,10 @@ test - - - - + + org.springframework.boot + spring-boot-starter-security + log4j diff --git a/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsApplication.java b/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsApplication.java index 5067195..97d4f98 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsApplication.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsApplication.java @@ -1,8 +1,9 @@ package eu.dnetlib.uoaadmintools; import eu.dnetlib.uoaadmintools.configuration.properties.MongoConfig; -import eu.dnetlib.uoaadmintools.configuration.properties.SecurityConfig; +//import eu.dnetlib.uoaadmintools.configuration.properties.SecurityConfig; //import eu.dnetlib.uoaauthorizationlibrary.configuration.AuthorizationConfiguration; +import eu.dnetlib.uoaauthorizationlibrary.configuration.AuthorizationConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -15,8 +16,9 @@ import org.springframework.context.annotation.PropertySources; @PropertySource("classpath:admintools.properties"), @PropertySource(value = "classpath:dnet-override.properties", ignoreResourceNotFound = true) }) -@EnableConfigurationProperties({SecurityConfig.class, MongoConfig.class}) -//@Import(AuthorizationConfiguration.class) +//SecurityConfig.class, +@EnableConfigurationProperties({MongoConfig.class}) +@Import(AuthorizationConfiguration.class) public class UoaAdminToolsApplication { public static void main(String[] args) { diff --git a/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsConfiguration.java b/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsConfiguration.java index ba41672..88625ca 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsConfiguration.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/UoaAdminToolsConfiguration.java @@ -1,7 +1,7 @@ package eu.dnetlib.uoaadmintools; -import eu.dnetlib.uoaadmintools.configuration.properties.SecurityConfig; -import eu.dnetlib.uoaadmintools.handlers.AuthorizationHandler; +//import eu.dnetlib.uoaadmintools.configuration.properties.SecurityConfig; +//import eu.dnetlib.uoaadmintools.handlers.AuthorizationHandler; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -18,8 +18,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter public class UoaAdminToolsConfiguration extends WebMvcConfigurerAdapter { private final Logger log = Logger.getLogger(this.getClass()); - @Autowired - private SecurityConfig securityConfig; +// @Autowired +// private SecurityConfig securityConfig; @Bean @@ -27,11 +27,11 @@ public class UoaAdminToolsConfiguration extends WebMvcConfigurerAdapter { return new PropertySourcesPlaceholderConfigurer(); } - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new AuthorizationHandler(securityConfig.getUserInfoUrl(), securityConfig.getOriginServer(), securityConfig.getPostsAllowed())) - .addPathPatterns("/**"); - - } +// @Override +// public void addInterceptors(InterceptorRegistry registry) { +// registry.addInterceptor(new AuthorizationHandler(securityConfig.getUserInfoUrl(), securityConfig.getOriginServer(), securityConfig.getPostsAllowed())) +// .addPathPatterns("/**"); +// +// } } diff --git a/src/main/java/eu/dnetlib/uoaadmintools/configuration/properties/SecurityConfig.java b/src/main/java/eu/dnetlib/uoaadmintools/configuration/properties/SecurityConfig.java index 2723e8b..3a43183 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/configuration/properties/SecurityConfig.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/configuration/properties/SecurityConfig.java @@ -1,40 +1,40 @@ -package eu.dnetlib.uoaadmintools.configuration.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.ArrayList; -import java.util.List; - -@ConfigurationProperties("admintool.security") -public class SecurityConfig { - - private String userInfoUrl; - private String originServer; - private List postsAllowed = new ArrayList<>(); - - public void setUserInfoUrl(String userInfoUrl) { - this.userInfoUrl = userInfoUrl; - } - - public void setOriginServer(String originServer) { - this.originServer = originServer; - } - - - public void setPostsAllowed(List posts) { - this.postsAllowed = posts; - } - - public String getUserInfoUrl() { - return userInfoUrl; - } - - public String getOriginServer() { - return originServer; - } - - public List getPostsAllowed() { - return postsAllowed; - } - -} +//package eu.dnetlib.uoaadmintools.configuration.properties; +// +//import org.springframework.boot.context.properties.ConfigurationProperties; +// +//import java.util.ArrayList; +//import java.util.List; +// +//@ConfigurationProperties("admintool.security") +//public class SecurityConfig { +// +// private String userInfoUrl; +// private String originServer; +// private List postsAllowed = new ArrayList<>(); +// +// public void setUserInfoUrl(String userInfoUrl) { +// this.userInfoUrl = userInfoUrl; +// } +// +// public void setOriginServer(String originServer) { +// this.originServer = originServer; +// } +// +// +// public void setPostsAllowed(List posts) { +// this.postsAllowed = posts; +// } +// +// public String getUserInfoUrl() { +// return userInfoUrl; +// } +// +// public String getOriginServer() { +// return originServer; +// } +// +// public List getPostsAllowed() { +// return postsAllowed; +// } +// +//} diff --git a/src/main/java/eu/dnetlib/uoaadmintools/controllers/CommunityController.java b/src/main/java/eu/dnetlib/uoaadmintools/controllers/CommunityController.java index 0bcb8a8..7de2053 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/controllers/CommunityController.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/controllers/CommunityController.java @@ -7,12 +7,17 @@ import eu.dnetlib.uoaadmintools.services.StatisticsService; import eu.dnetlib.uoaadmintools.services.SubscriberService; import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.*; +import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException; +import eu.dnetlib.uoaadmintoolslibrary.handlers.ForbiddenException; +import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException; +import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils; import eu.dnetlib.uoaadmintoolslibrary.services.PortalService; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; +import org.springframework.security.access.prepost.PreAuthorize; @RestController @RequestMapping("/community") @@ -20,6 +25,9 @@ import java.util.*; public class CommunityController { private final Logger log = Logger.getLogger(this.getClass()); + @Autowired + private RolesUtils rolesUtils; + @Autowired private LayoutService layoutService; @@ -45,9 +53,14 @@ public class CommunityController { return portalService.getAllPortalsFullByType("community"); } -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") + @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/update", method = RequestMethod.POST) public PortalResponse updateCommunity(@RequestBody Portal portal) { + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Update Community: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community"); + } + String old_pid = portalService.getPortalById(portal.getId()).getPid(); String new_pid = portal.getPid(); @@ -64,9 +77,14 @@ public class CommunityController { return portalResponse; } -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") + @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/save", method = RequestMethod.POST) public PortalResponse insertCommunity(@RequestBody Portal portal) { + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Save Community: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community"); + } + PortalResponse portalResponse = portalService.insertPortal(portal); statisticsService.createPortalStatistics(portal.getPid()); @@ -75,11 +93,22 @@ public class CommunityController { return portalResponse; } - // cannot handle MismatchingContent -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") + @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/delete", method = RequestMethod.POST) public Boolean deleteCommunities(@RequestBody List portals) { + List roles = rolesUtils.getRoles(); + for (String id: portals) { + Portal portal = portalService.getPortalById(id); + if(portal == null) { + // EXCEPTION - Entity Not Found + throw new ContentNotFoundException("Delete community: Portal with id: " + id + " not found"); + } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Delete Community: Portal with id: "+id+" has type: "+portal.getType()+" instead of community"); + } + String pid = portalService.deletePortal(id); statisticsService.deleteByPid(pid); @@ -93,14 +122,36 @@ public class CommunityController { @RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET) public Layout getLayoutForCommunity(@PathVariable(value = "pid") String pid) { + Portal portal = portalService.getPortal(pid); + if(portal == null) { + // EXCEPTION - Entity Not Found + throw new ContentNotFoundException("CommunityController - Get layout: Portal with pid: " + pid + " not found"); + } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("CommunityController - Get layout: Portal with pid: "+pid+" has type: "+portal.getType()+" instead of community"); + } return layoutService.findByPid(pid); } -// @PreAuthorize("hasAnyAuthority(" + -// "@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN, " + -// "@AuthorizationService.curator(#portalType), @AuthorizationService.manager(#portalType, #pid))") + @PreAuthorize("hasAnyAuthority(" + + "@AuthorizationService.PORTAL_ADMIN, " + + "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))") @RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST) public Layout updateLayoutForCommunity(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) { + Portal portal = portalService.getPortal(pid); + if(portal == null) { + // EXCEPTION - Entity Not Found + throw new ContentNotFoundException("CommunityController - Update layout: Portal with pid: " + pid + " not found"); + } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("CommunityController - Update layout: Portal with pid: "+pid+" has type: "+portal.getType()+" instead of community"); + } + if(!pid.equals(layout.getPortalPid())) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("CommunityController - Update layout: Portal has pid: "+pid+" while layout has portalPid: "+layout.getPortalPid()); + } return layoutService.save(layout); } } diff --git a/src/main/java/eu/dnetlib/uoaadmintools/controllers/ConnectController.java b/src/main/java/eu/dnetlib/uoaadmintools/controllers/ConnectController.java index bf58292..e9909b7 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/controllers/ConnectController.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/controllers/ConnectController.java @@ -4,8 +4,11 @@ import eu.dnetlib.uoaadmintools.entities.Layout; import eu.dnetlib.uoaadmintools.services.LayoutService; import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.*; +import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException; +import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException; import eu.dnetlib.uoaadmintoolslibrary.services.PortalService; import org.apache.log4j.Logger; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; @@ -14,6 +17,7 @@ import java.util.*; @RestController @RequestMapping("/connect") @CrossOrigin(origins = "*") +@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") public class ConnectController { private final Logger log = Logger.getLogger(this.getClass()); @@ -23,9 +27,13 @@ public class ConnectController { @Autowired private PortalService portalService; -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/update", method = RequestMethod.POST) - public PortalResponse updateCommunity(@RequestBody Portal portal) { + public PortalResponse updateConnect(@RequestBody Portal portal) { + if(!portal.getType().equals("connect")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Update Connect: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of connect"); + } + PortalResponse portalResponse = portalService.updatePortal(portal); String old_pid = portalResponse.getPid(); @@ -37,18 +45,30 @@ public class ConnectController { return portalResponse; } -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/save", method = RequestMethod.POST) - public PortalResponse insertCommunity(@RequestBody Portal portal) { + public PortalResponse insertConnect(@RequestBody Portal portal) { + if(!portal.getType().equals("connect")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Save Connect: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of connect"); + } + PortalResponse portalResponse = portalService.insertPortal(portal); return portalResponse; } - // cannot handle MismatchingContent -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/delete", method = RequestMethod.POST) - public Boolean deleteCommunities(@RequestBody List portals) { + public Boolean deleteConnect(@RequestBody List portals) { for (String id: portals) { + Portal portal = portalService.getPortalById(id); + if(portal == null) { + // EXCEPTION - Entity Not Found + throw new ContentNotFoundException("Delete connect: Portal with id: " + id + " not found"); + } + if(!portal.getType().equals("connect")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Delete Connect: Portal with id: "+id+" has type: "+portal.getType()+" instead of connect"); + } + String pid = portalService.deletePortal(id); layoutService.deleteByPid(pid); } @@ -56,17 +76,15 @@ public class ConnectController { return true; } - @RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET) - public Layout getLayoutForCommunity(@PathVariable(value = "pid") String pid) { - return layoutService.findByPid(pid); - } - -// @PreAuthorize("hasAnyAuthority(" + -// "@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN, " + -// "@AuthorizationService.curator(#portalType), @AuthorizationService.manager(#portalType, #pid))") - @RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST) - public Layout updateLayoutForCommunity(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) { - return layoutService.save(layout); - } +// @RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET) +// public Layout getLayoutForConnect(@PathVariable(value = "pid") String pid) { +// return layoutService.findByPid(pid); +// } +// +// @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") +// @RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST) +// public Layout updateLayoutForConnect(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) { +// return layoutService.save(layout); +// } } diff --git a/src/main/java/eu/dnetlib/uoaadmintools/controllers/CuratorController.java b/src/main/java/eu/dnetlib/uoaadmintools/controllers/CuratorController.java index ce76eba..a1fb139 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/controllers/CuratorController.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/controllers/CuratorController.java @@ -3,8 +3,10 @@ package eu.dnetlib.uoaadmintools.controllers; import eu.dnetlib.uoaadmintools.dao.CuratorDAO; import eu.dnetlib.uoaadmintools.entities.curator.Curator; import eu.dnetlib.uoaadmintools.entities.curator.CuratorResponse; +import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; @@ -19,6 +21,8 @@ public class CuratorController { @Autowired private CuratorDAO curatorDAO; + @Autowired + private RolesUtils rolesUtils; /** * Return a list with curator. If list of emails does not existed return all curators, else return @@ -51,6 +55,7 @@ public class CuratorController { * @param id * @return */ + @PreAuthorize("isAuthenticated()") @RequestMapping(value = "/curator/{id}", method = RequestMethod.GET) public Curator getCuratorById(@PathVariable String id) { return curatorDAO.findById(id); @@ -62,8 +67,11 @@ public class CuratorController { * @param curator * @return */ + @PreAuthorize("isAuthenticated()") @RequestMapping(value = "/curator", method = RequestMethod.POST) public Curator insertCurator(@RequestBody Curator curator) { + String aaiId = rolesUtils.getAaiId(); + curator.setId(aaiId); return curatorDAO.save(curator); } @@ -73,6 +81,7 @@ public class CuratorController { * * @param emails */ + @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/curator", method = RequestMethod.DELETE) public void deleteCurators(@RequestBody(required = false) Optional> emails) { if(emails.isPresent()) { diff --git a/src/main/java/eu/dnetlib/uoaadmintools/controllers/ExploreController.java b/src/main/java/eu/dnetlib/uoaadmintools/controllers/ExploreController.java index ad513a3..fcec22f 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/controllers/ExploreController.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/controllers/ExploreController.java @@ -2,8 +2,11 @@ package eu.dnetlib.uoaadmintools.controllers; import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.*; +import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException; +import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException; import eu.dnetlib.uoaadmintoolslibrary.services.PortalService; import org.apache.log4j.Logger; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; @@ -12,32 +15,46 @@ import java.util.*; @RestController @RequestMapping("/explore") @CrossOrigin(origins = "*") -//@PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") +@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") public class ExploreController { private final Logger log = Logger.getLogger(this.getClass()); @Autowired private PortalService portalService; -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/update", method = RequestMethod.POST) public PortalResponse updateExplore(@RequestBody Portal portal) { + if(!portal.getType().equals("explore")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Update Explore: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of explore"); + } PortalResponse portalResponse = portalService.updatePortal(portal); return portalResponse; } -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/save", method = RequestMethod.POST) public PortalResponse insertExplore(@RequestBody Portal portal) { + if(!portal.getType().equals("explore")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Save Explore: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of explore"); + } PortalResponse portalResponse = portalService.insertPortal(portal); return portalResponse; } // cannot handle MismatchingContent -// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @RequestMapping(value = "/delete", method = RequestMethod.POST) public Boolean deleteExplore(@RequestBody List portals) throws Exception { for (String id : portals) { + Portal portal = portalService.getPortalById(id); + if(portal == null) { + // EXCEPTION - Entity Not Found + throw new ContentNotFoundException("Delete Explore: Portal with id: " + id + " not found"); + } + if(!portal.getType().equals("explore")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Delete Explore: Portal with id: "+id+" has type: "+portal.getType()+" instead of explore"); + } portalService.deletePortal(id); } diff --git a/src/main/java/eu/dnetlib/uoaadmintools/controllers/NotificationsController.java b/src/main/java/eu/dnetlib/uoaadmintools/controllers/NotificationsController.java index 3f33329..11966c7 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/controllers/NotificationsController.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/controllers/NotificationsController.java @@ -2,10 +2,15 @@ package eu.dnetlib.uoaadmintools.controllers; import eu.dnetlib.uoaadmintools.dao.NotificationsDAO; import eu.dnetlib.uoaadmintools.entities.Notifications; +import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; +import eu.dnetlib.uoaadmintoolslibrary.entities.PortalType; import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException; import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO; +import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException; +import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -22,36 +27,92 @@ public class NotificationsController { private NotificationsDAO notificationsDAO; @Autowired private PortalDAO portalDAO; + @Autowired + private RolesUtils rolesUtils; - @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.GET) + @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)") + @RequestMapping(value = "/community/{pid}/notifications/all", method = RequestMethod.GET) public List getNotifications(@PathVariable(value = "pid") String pid ) throws ContentNotFoundException { - if(portalDAO.findByPid(pid) == null){ - throw new ContentNotFoundException("Portal not found"); + Portal portal = portalDAO.findByPid(pid); + if(portal == null){ + throw new ContentNotFoundException("Portal with pid: "+pid+" not found"); } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Get Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community"); + } + List notifications = notificationsDAO.findByPortalPid(pid); if(notifications == null || notifications.size() == 0){ - throw new ContentNotFoundException("Notifications settings not found"); + throw new ContentNotFoundException("Notifications settings for community with pid: "+pid+" not found"); } return notifications; } + + @PreAuthorize("hasAnyAuthority(" + + "@AuthorizationService.PORTAL_ADMIN, " + + "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))") + @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.GET) + public Notifications getNotificationsForUser(@PathVariable(value = "pid") String pid) throws ContentNotFoundException { + Portal portal = portalDAO.findByPid(pid); + if(portal == null){ + throw new ContentNotFoundException("Portal with pid: "+pid+" not found"); + } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Get Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community"); + } + + String email = rolesUtils.getEmail(); + + Notifications notifications = notificationsDAO.findByManagerEmailAndPortalPid(email, pid); + if(notifications == null){ + throw new ContentNotFoundException("Notifications settings for community with pid: "+pid+" and user email: "+email+" not found"); + } + return notifications; + } + + @PreAuthorize("hasAnyAuthority(" + + "@AuthorizationService.PORTAL_ADMIN, " + + "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))") @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.DELETE) - public void deleteEntity(@PathVariable(value = "pid") String pid, @RequestBody String email) throws ContentNotFoundException { + public void deleteNotification(@PathVariable(value = "pid") String pid) throws ContentNotFoundException { + Portal portal = portalDAO.findByPid(pid); + if(portal == null){ + throw new ContentNotFoundException("Portal with pid: "+pid+" not found"); + } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Delete Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community"); + } + String email = rolesUtils.getEmail(); Notifications notifications = notificationsDAO.findByManagerEmailAndPortalPid(email,pid); if(notifications!= null){ notificationsDAO.delete(notifications.getId()); }else{ - throw new ContentNotFoundException("Notifications not found"); + throw new ContentNotFoundException("Notifications settings for community with pid: "+pid+" and user email: "+email+" not found"); } } + @PreAuthorize("hasAnyAuthority(" + + "@AuthorizationService.PORTAL_ADMIN, " + + "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))") @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.POST) - public Notifications saveEntity(@PathVariable(value = "pid") String pid, @RequestBody Notifications notifications) throws ContentNotFoundException { - if(portalDAO.findByPid(pid) == null){ - throw new ContentNotFoundException("Portal not found"); + public Notifications saveNotification(@PathVariable(value = "pid") String pid, @RequestBody Notifications notifications) throws ContentNotFoundException { + Portal portal = portalDAO.findByPid(pid); + if(portal == null){ + throw new ContentNotFoundException("Portal with pid: "+pid+" not found"); + } + if(!portal.getType().equals("community")) { + // EXCEPTION - MismatchingContent + throw new MismatchingContentException("Save Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community"); } - if(notifications.getManagerEmail() != null && !notifications.getManagerEmail().isEmpty()){ + notifications.setManagerEmail(rolesUtils.getEmail()); + notifications.setAaiId(rolesUtils.getAaiId()); + +// if(notifications.getManagerEmail() != null && !notifications.getManagerEmail().isEmpty()){ Notifications saved = notificationsDAO.findByManagerEmailAndPortalPid(notifications.getManagerEmail(),pid); log.debug(saved); if(saved!= null){ @@ -62,10 +123,10 @@ public class NotificationsController { log.debug(notifications); Notifications savedNotifications = notificationsDAO.save(notifications); return savedNotifications; - }else{ - log.error("No user e-mail specified"); - return null; - } +// } else{ +// log.error("Save notifications: No user e-mail specified"); +// return null; +// } } diff --git a/src/main/java/eu/dnetlib/uoaadmintools/controllers/PortalSubscribersController.java b/src/main/java/eu/dnetlib/uoaadmintools/controllers/PortalSubscribersController.java index 1089cf2..35f23d4 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/controllers/PortalSubscribersController.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/controllers/PortalSubscribersController.java @@ -6,8 +6,8 @@ import eu.dnetlib.uoaadmintools.dao.SubscriberDAO; import eu.dnetlib.uoaadmintools.entities.subscriber.PortalSubscribers; import eu.dnetlib.uoaadmintools.entities.subscriber.Subscriber; import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException; -import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils; -import eu.dnetlib.uoaadmintools.handlers.utils.UserInfo; +//import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils; +//import eu.dnetlib.uoaadmintools.handlers.utils.UserInfo; import eu.dnetlib.uoaadmintoolslibrary.responses.SingleValueWrapperResponse; import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO; import org.apache.log4j.Logger; diff --git a/src/main/java/eu/dnetlib/uoaadmintools/entities/Notifications.java b/src/main/java/eu/dnetlib/uoaadmintools/entities/Notifications.java index 43e33ff..9916f0d 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/entities/Notifications.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/entities/Notifications.java @@ -14,6 +14,8 @@ public class Notifications { Boolean notifyForNewSubscribers = true; String managerEmail; String portalPid; + String aaiId; + public Notifications(){ } @@ -62,6 +64,14 @@ public class Notifications { this.portalPid = portalPid; } + public String getAaiId() { + return aaiId; + } + + public void setAaiId(String aaiId) { + this.aaiId = aaiId; + } + @Override public String toString() { return "Notifications{" + diff --git a/src/main/java/eu/dnetlib/uoaadmintools/handlers/AuthorizationHandler.java b/src/main/java/eu/dnetlib/uoaadmintools/handlers/AuthorizationHandler.java index 0baa51f..2db32af 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/handlers/AuthorizationHandler.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/handlers/AuthorizationHandler.java @@ -1,71 +1,71 @@ -package eu.dnetlib.uoaadmintools.handlers; - -import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.List; - -/** - * Created by argirok on 23/2/2018. - */ -public class AuthorizationHandler extends HandlerInterceptorAdapter { - private final Logger log = Logger.getLogger(this.getClass()); - private AuthorizationUtils helper = new AuthorizationUtils(); - private List allowedPostRequests; - - public AuthorizationHandler(String userInfoUrl, String originServer, List allowedPostRequests){ - helper.setOriginServer(originServer); - helper.setUserInfoUrl(userInfoUrl); - this.allowedPostRequests = allowedPostRequests; - } - @Override - public boolean preHandle( - HttpServletRequest request, - HttpServletResponse response, - Object handler) throws Exception { -// log.debug("request method " + request.getRemoteHost()); -// log.debug("properties: " + helper.getOriginServer() + " "+ helper.getUserInfoUrl()); -// log.debug(allowedPostRequests); -// log.debug(allowedPostRequests.contains(request.getServletPath())); -// log.debug(request.getServletPath()); - if((request.getMethod().equals("POST") || request.getMethod().equals("DELETE")) && - !allowedPostRequests.contains(request.getServletPath())) { - //TODO check domain & check user info - if(!this.helper.checkCookies(request) || !helper.isAuthorized(helper.getToken(request))){ - - response.setHeader("Access-Control-Allow-Credentials","true"); - response.setHeader("Access-Control-Allow-Origin","*"); - response.setHeader("Vary","Origin"); - - response.setStatus(403); - response.sendError(403, "Forbidden: You don't have permission to access. Maybe you are not registered."); - return false; - } - - } - return true; - } - - +//package eu.dnetlib.uoaadmintools.handlers; +// +//import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils; +//import org.apache.log4j.Logger; +//import org.springframework.beans.factory.annotation.Value; +//import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +// +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.util.List; +// +///** +// * Created by argirok on 23/2/2018. +// */ +//public class AuthorizationHandler extends HandlerInterceptorAdapter { +// private final Logger log = Logger.getLogger(this.getClass()); +// private AuthorizationUtils helper = new AuthorizationUtils(); +// private List allowedPostRequests; +// +// public AuthorizationHandler(String userInfoUrl, String originServer, List allowedPostRequests){ +// helper.setOriginServer(originServer); +// helper.setUserInfoUrl(userInfoUrl); +// this.allowedPostRequests = allowedPostRequests; +// } // @Override -// public void postHandle( +// public boolean preHandle( // HttpServletRequest request, // HttpServletResponse response, -// Object handler, -// ModelAndView modelAndView) throws Exception { -// log.info("I am here - postHandle "); +// Object handler) throws Exception { +//// log.debug("request method " + request.getRemoteHost()); +//// log.debug("properties: " + helper.getOriginServer() + " "+ helper.getUserInfoUrl()); +//// log.debug(allowedPostRequests); +//// log.debug(allowedPostRequests.contains(request.getServletPath())); +//// log.debug(request.getServletPath()); +// if((request.getMethod().equals("POST") || request.getMethod().equals("DELETE")) && +// !allowedPostRequests.contains(request.getServletPath())) { +// //TODO check domain & check user info +// if(!this.helper.checkCookies(request) || !helper.isAuthorized(helper.getToken(request))){ +// +// response.setHeader("Access-Control-Allow-Credentials","true"); +// response.setHeader("Access-Control-Allow-Origin","*"); +// response.setHeader("Vary","Origin"); +// +// response.setStatus(403); +// response.sendError(403, "Forbidden: You don't have permission to access. Maybe you are not registered."); +// return false; +// } +// +// } +// return true; // } // -// @Override -// public void afterCompletion( -// HttpServletRequest request, -// HttpServletResponse response, -// Object handler, Exception ex) { -// log.info("I am here - afterCompletion "); -// } - -} +// +//// @Override +//// public void postHandle( +//// HttpServletRequest request, +//// HttpServletResponse response, +//// Object handler, +//// ModelAndView modelAndView) throws Exception { +//// log.info("I am here - postHandle "); +//// } +//// +//// @Override +//// public void afterCompletion( +//// HttpServletRequest request, +//// HttpServletResponse response, +//// Object handler, Exception ex) { +//// log.info("I am here - afterCompletion "); +//// } +// +//} diff --git a/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/AuthorizationUtils.java b/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/AuthorizationUtils.java index 7da34b3..6ff1444 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/AuthorizationUtils.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/AuthorizationUtils.java @@ -1,215 +1,97 @@ -package eu.dnetlib.uoaadmintools.handlers.utils; - -import org.apache.log4j.Logger; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Enumeration; - -import com.google.gson.Gson; - -/** - * Created by argirok on 27/2/2018. - */ -public class AuthorizationUtils { - private final Logger log = Logger.getLogger(this.getClass()); - private String userInfoUrl = null; -// private String communityAPI =""; -// List adminRoles = new ArrayList(Arrays.asList("Super Administrator", "Portal Administrator")); - private String originServer= null; - public Boolean checkCookies(HttpServletRequest request){ - Boolean valid = true; - String cookieValue = this.getCookie(request,"AccessToken"); - if(cookieValue == null || cookieValue.isEmpty()){ - log.info("no cookie available "); - valid = false; - }else { - String headerValue = this.getHeadersInfo(request, "x-xsrf-token"); - if(headerValue == null || headerValue.isEmpty()){ - log.info("no header available "); - valid = false; - }else{ - if(!cookieValue.equals(headerValue)){ - log.info("no proper header or cookie "); - valid = false; - }else if(!hasValidOrigin(this.getHeadersInfo(request, "origin"))){ - log.info("no proper origin "); - valid = false; - } - } - } - return valid; - } - public String getToken(HttpServletRequest request){ - return this.getHeadersInfo(request, "x-xsrf-token"); - } - private String getCookie(HttpServletRequest request, String cookieName){ - if(request.getCookies() == null){ - return null; - } - for(Cookie c: request.getCookies()){ -// log.debug("cookie "+ c.getName()+ " "+ c.getValue()); - if(c.getName().equals(cookieName)){ - return c.getValue(); - } - - } - return null; - } - private String getHeadersInfo(HttpServletRequest request, String name) { - - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String key = (String) headerNames.nextElement(); - String value = request.getHeader(key); -// log.debug(" key: "+ key+" value: "+ value); - if(name.equals(key)){ - return value; - } - } - return null; - } - public boolean hasValidOrigin(String origin) { - if (origin != null && origin.indexOf(originServer)!=-1) { - return true; - } - log.debug("Not valid origin. Origin server is \"" + origin + "\", but expected value is \"" + originServer + "\". If the expec cted value is not right, check properties file. "); - return false; - } - public UserInfo getUserInfo(String accessToken){ - String url=userInfoUrl+accessToken; - URL obj = null; - String responseStr=null; -// log.debug("User info url is "+url); - - try { - obj = new URL(url); - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - if (con.getResponseCode() != 200) { - log.debug("User info response code is: " + con.getResponseCode()); - return null; - } - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - StringBuffer response = new StringBuffer(); - String inputLine; - while ((inputLine = in.readLine()) != null) { - response.append(inputLine).append("\n"); - } - in.close(); - responseStr = response.toString(); - }catch(Exception e){ - log.error("An error occured while trying to fetch user info ",e); - return null; - } - return json2UserInfo(responseStr); - } - private UserInfo json2UserInfo(String json) { - -// log.debug("Try to create userInfo class from json: "+json); - if (json == null){ - return null; - } - - BufferedReader br = new BufferedReader(new StringReader(json)); - //convert the json string back to object - Gson gson = new Gson(); - UserInfo userInfo = null; - try { - userInfo = gson.fromJson(br, UserInfo.class); - }catch(Exception e){ - log.debug("Error in parsing json response. Given json is : "+json, e); - return null; - } - -// log.debug("Original response.........: "+userInfo.toString()); - try { - if(userInfo != null && userInfo.getEdu_person_entitlements() != null ) { - - for (int i = 0; i < userInfo.getEdu_person_entitlements().size(); i++) { - String role = userInfo.getEdu_person_entitlements().get(i); -// log.debug("AAI role: "+role); - role = role.split(":")[role.split(":").length-1]; - role = role.replace("+"," "); -// log.debug("Adding parsed role : "+role); - userInfo.getEdu_person_entitlements().set(i,role); - } - } - }catch(Exception e){ - log.debug("Error in parsing Edu_person_entitlements : ",e); - return null; - } -// log.debug("After handling roles : "+userInfo.toString()); - - - return userInfo; - } - public boolean isAuthorized(String token) { - UserInfo userInfo = getUserInfo(token); - if (userInfo != null ) { - return true; - } else { - log.debug(" User has no Valid UserInfo"); - return false; - } - - } - - public String getUserInfoUrl() { - return userInfoUrl; - } - - public String getOriginServer() { - return originServer; - } - - public void setUserInfoUrl(String userInfoUrl) { - this.userInfoUrl = userInfoUrl; - } - - public void setOriginServer(String originServer) { - this.originServer = originServer; - } - // private boolean hasRole(List givenRoles, List authorizedRoles) { -// log.debug("It's registered with role " + givenRoles); -// for (String gRole : givenRoles) { -// if (authorizedRoles.indexOf(gRole) != -1) { -// return true; +//package eu.dnetlib.uoaadmintools.handlers.utils; +// +//import org.apache.log4j.Logger; +// +//import javax.servlet.http.Cookie; +//import javax.servlet.http.HttpServletRequest; +//import java.io.BufferedReader; +//import java.io.InputStreamReader; +//import java.io.StringReader; +//import java.net.HttpURLConnection; +//import java.net.URL; +//import java.util.Enumeration; +// +//import com.google.gson.Gson; +// +///** +// * Created by argirok on 27/2/2018. +// */ +//public class AuthorizationUtils { +// private final Logger log = Logger.getLogger(this.getClass()); +// private String userInfoUrl = null; +//// private String communityAPI =""; +//// List adminRoles = new ArrayList(Arrays.asList("Super Administrator", "Portal Administrator")); +// private String originServer= null; +// public Boolean checkCookies(HttpServletRequest request){ +// Boolean valid = true; +// String cookieValue = this.getCookie(request,"AccessToken"); +// if(cookieValue == null || cookieValue.isEmpty()){ +// log.info("no cookie available "); +// valid = false; +// }else { +// String headerValue = this.getHeadersInfo(request, "x-xsrf-token"); +// if(headerValue == null || headerValue.isEmpty()){ +// log.info("no header available "); +// valid = false; +// }else{ +// if(!cookieValue.equals(headerValue)){ +// log.info("no proper header or cookie "); +// valid = false; +// }else if(!hasValidOrigin(this.getHeadersInfo(request, "origin"))){ +// log.info("no proper origin "); +// valid = false; +// } // } // } -// log.debug("Not Authorized. Authorized roles are" + authorizedRoles); -// return false; -// +// return valid; // } -// private boolean isCommunityManager(String community, String email) { +// public String getToken(HttpServletRequest request){ +// return this.getHeadersInfo(request, "x-xsrf-token"); +// } +// private String getCookie(HttpServletRequest request, String cookieName){ +// if(request.getCookies() == null){ +// return null; +// } +// for(Cookie c: request.getCookies()){ +//// log.debug("cookie "+ c.getName()+ " "+ c.getValue()); +// if(c.getName().equals(cookieName)){ +// return c.getValue(); +// } // -// CommunityInfo communityInfo = getCommunityInfo(community); -// if(communityInfo != null && communityInfo.getManagers() != null ) { -// -// for (int i = 0; i < communityInfo.getManagers().size(); i++) { -// String manager = communityInfo.getManagers().get(i); -// log.debug("Community manager: "+manager); +// } +// return null; +// } +// private String getHeadersInfo(HttpServletRequest request, String name) { // +// Enumeration headerNames = request.getHeaderNames(); +// while (headerNames.hasMoreElements()) { +// String key = (String) headerNames.nextElement(); +// String value = request.getHeader(key); +//// log.debug(" key: "+ key+" value: "+ value); +// if(name.equals(key)){ +// return value; // } // } -// return false; -// +// return null; // } -// private CommunityInfo getCommunityInfo(String community) { -// String url = userInfoUrl + community; +// public boolean hasValidOrigin(String origin) { +// if (origin != null && origin.indexOf(originServer)!=-1) { +// return true; +// } +// log.debug("Not valid origin. Origin server is \"" + origin + "\", but expected value is \"" + originServer + "\". If the expec cted value is not right, check properties file. "); +// return false; +// } +// public UserInfo getUserInfo(String accessToken){ +// String url=userInfoUrl+accessToken; // URL obj = null; -// String responseStr = null; -// log.debug("Community info url is " + url); +// String responseStr=null; +//// log.debug("User info url is "+url); // // try { // obj = new URL(url); // HttpURLConnection con = (HttpURLConnection) obj.openConnection(); -// log.debug("User info response code is: " + con.getResponseCode()); // if (con.getResponseCode() != 200) { +// log.debug("User info response code is: " + con.getResponseCode()); // return null; // } // BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); @@ -220,15 +102,15 @@ public class AuthorizationUtils { // } // in.close(); // responseStr = response.toString(); -// } catch (Exception e) { -// log.error("An error occured while trying to fetch user info ", e); +// }catch(Exception e){ +// log.error("An error occured while trying to fetch user info ",e); // return null; // } -// return json2CommunityInfo(community); +// return json2UserInfo(responseStr); // } -// private CommunityInfo json2CommunityInfo(String json){ +// private UserInfo json2UserInfo(String json) { // -// log.debug("Try to create CommunityInfo class from json: "+json); +//// log.debug("Try to create userInfo class from json: "+json); // if (json == null){ // return null; // } @@ -236,18 +118,136 @@ public class AuthorizationUtils { // BufferedReader br = new BufferedReader(new StringReader(json)); // //convert the json string back to object // Gson gson = new Gson(); -// CommunityInfo communityInfo = null; +// UserInfo userInfo = null; // try { -// communityInfo = gson.fromJson(br, CommunityInfo.class); +// userInfo = gson.fromJson(br, UserInfo.class); // }catch(Exception e){ // log.debug("Error in parsing json response. Given json is : "+json, e); // return null; // } // -// log.debug("Original response.........: "+communityInfo.toString()); +//// log.debug("Original response.........: "+userInfo.toString()); +// try { +// if(userInfo != null && userInfo.getEdu_person_entitlements() != null ) { +// +// for (int i = 0; i < userInfo.getEdu_person_entitlements().size(); i++) { +// String role = userInfo.getEdu_person_entitlements().get(i); +//// log.debug("AAI role: "+role); +// role = role.split(":")[role.split(":").length-1]; +// role = role.replace("+"," "); +//// log.debug("Adding parsed role : "+role); +// userInfo.getEdu_person_entitlements().set(i,role); +// } +// } +// }catch(Exception e){ +// log.debug("Error in parsing Edu_person_entitlements : ",e); +// return null; +// } +//// log.debug("After handling roles : "+userInfo.toString()); // // -// -// return communityInfo; +// return userInfo; // } -} +// public boolean isAuthorized(String token) { +// UserInfo userInfo = getUserInfo(token); +// if (userInfo != null ) { +// return true; +// } else { +// log.debug(" User has no Valid UserInfo"); +// return false; +// } +// +// } +// +// public String getUserInfoUrl() { +// return userInfoUrl; +// } +// +// public String getOriginServer() { +// return originServer; +// } +// +// public void setUserInfoUrl(String userInfoUrl) { +// this.userInfoUrl = userInfoUrl; +// } +// +// public void setOriginServer(String originServer) { +// this.originServer = originServer; +// } +// // private boolean hasRole(List givenRoles, List authorizedRoles) { +//// log.debug("It's registered with role " + givenRoles); +//// for (String gRole : givenRoles) { +//// if (authorizedRoles.indexOf(gRole) != -1) { +//// return true; +//// } +//// } +//// log.debug("Not Authorized. Authorized roles are" + authorizedRoles); +//// return false; +//// +//// } +//// private boolean isCommunityManager(String community, String email) { +//// +//// CommunityInfo communityInfo = getCommunityInfo(community); +//// if(communityInfo != null && communityInfo.getManagers() != null ) { +//// +//// for (int i = 0; i < communityInfo.getManagers().size(); i++) { +//// String manager = communityInfo.getManagers().get(i); +//// log.debug("Community manager: "+manager); +//// +//// } +//// } +//// return false; +//// +//// } +//// private CommunityInfo getCommunityInfo(String community) { +//// String url = userInfoUrl + community; +//// URL obj = null; +//// String responseStr = null; +//// log.debug("Community info url is " + url); +//// +//// try { +//// obj = new URL(url); +//// HttpURLConnection con = (HttpURLConnection) obj.openConnection(); +//// log.debug("User info response code is: " + con.getResponseCode()); +//// if (con.getResponseCode() != 200) { +//// return null; +//// } +//// BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); +//// StringBuffer response = new StringBuffer(); +//// String inputLine; +//// while ((inputLine = in.readLine()) != null) { +//// response.append(inputLine).append("\n"); +//// } +//// in.close(); +//// responseStr = response.toString(); +//// } catch (Exception e) { +//// log.error("An error occured while trying to fetch user info ", e); +//// return null; +//// } +//// return json2CommunityInfo(community); +//// } +//// private CommunityInfo json2CommunityInfo(String json){ +//// +//// log.debug("Try to create CommunityInfo class from json: "+json); +//// if (json == null){ +//// return null; +//// } +//// +//// BufferedReader br = new BufferedReader(new StringReader(json)); +//// //convert the json string back to object +//// Gson gson = new Gson(); +//// CommunityInfo communityInfo = null; +//// try { +//// communityInfo = gson.fromJson(br, CommunityInfo.class); +//// }catch(Exception e){ +//// log.debug("Error in parsing json response. Given json is : "+json, e); +//// return null; +//// } +//// +//// log.debug("Original response.........: "+communityInfo.toString()); +//// +//// +//// +//// return communityInfo; +//// } +//} diff --git a/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/CommunityInfo.java b/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/CommunityInfo.java index 91e3fdf..d95618d 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/CommunityInfo.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/CommunityInfo.java @@ -1,81 +1,81 @@ -package eu.dnetlib.uoaadmintools.handlers.utils; - -import com.google.gson.Gson; -import org.apache.log4j.Logger; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -/** - * Created by argirok on 27/2/2018. - */ -public class CommunityInfo { - - List managers = new ArrayList(); - private final Logger log = Logger.getLogger(this.getClass()); - - public List getManagers() { - return managers; - } - - public void setManagers(List managers) { - this.managers = managers; - } - - private CommunityInfo getCommunityInfo(String communityAPI, String community) { - String url = communityAPI + community; - URL obj = null; - String responseStr = null; - log.debug("Community info url is " + url); - - try { - obj = new URL(url); - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - log.debug("User info response code is: " + con.getResponseCode()); - if (con.getResponseCode() != 200) { - return null; - } - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - StringBuffer response = new StringBuffer(); - String inputLine; - while ((inputLine = in.readLine()) != null) { - response.append(inputLine).append("\n"); - } - in.close(); - responseStr = response.toString(); - } catch (Exception e) { - log.error("An error occured while trying to fetch user info ", e); - return null; - } - return json2CommunityInfo(community); - } - private CommunityInfo json2CommunityInfo(String json){ - - log.debug("Try to create CommunityInfo class from json: "+json); - if (json == null){ - return null; - } - - BufferedReader br = new BufferedReader(new StringReader(json)); - //convert the json string back to object - Gson gson = new Gson(); - CommunityInfo communityInfo = null; - try { - communityInfo = gson.fromJson(br, CommunityInfo.class); - }catch(Exception e){ - log.debug("Error in parsing json response. Given json is : "+json, e); - return null; - } - - log.debug("Original response.........: "+communityInfo.toString()); - - - - return communityInfo; - } -} +//package eu.dnetlib.uoaadmintools.handlers.utils; +// +//import com.google.gson.Gson; +//import org.apache.log4j.Logger; +// +//import java.io.BufferedReader; +//import java.io.InputStreamReader; +//import java.io.StringReader; +//import java.net.HttpURLConnection; +//import java.net.URL; +//import java.util.ArrayList; +//import java.util.List; +// +///** +// * Created by argirok on 27/2/2018. +// */ +//public class CommunityInfo { +// +// List managers = new ArrayList(); +// private final Logger log = Logger.getLogger(this.getClass()); +// +// public List getManagers() { +// return managers; +// } +// +// public void setManagers(List managers) { +// this.managers = managers; +// } +// +// private CommunityInfo getCommunityInfo(String communityAPI, String community) { +// String url = communityAPI + community; +// URL obj = null; +// String responseStr = null; +// log.debug("Community info url is " + url); +// +// try { +// obj = new URL(url); +// HttpURLConnection con = (HttpURLConnection) obj.openConnection(); +// log.debug("User info response code is: " + con.getResponseCode()); +// if (con.getResponseCode() != 200) { +// return null; +// } +// BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); +// StringBuffer response = new StringBuffer(); +// String inputLine; +// while ((inputLine = in.readLine()) != null) { +// response.append(inputLine).append("\n"); +// } +// in.close(); +// responseStr = response.toString(); +// } catch (Exception e) { +// log.error("An error occured while trying to fetch user info ", e); +// return null; +// } +// return json2CommunityInfo(community); +// } +// private CommunityInfo json2CommunityInfo(String json){ +// +// log.debug("Try to create CommunityInfo class from json: "+json); +// if (json == null){ +// return null; +// } +// +// BufferedReader br = new BufferedReader(new StringReader(json)); +// //convert the json string back to object +// Gson gson = new Gson(); +// CommunityInfo communityInfo = null; +// try { +// communityInfo = gson.fromJson(br, CommunityInfo.class); +// }catch(Exception e){ +// log.debug("Error in parsing json response. Given json is : "+json, e); +// return null; +// } +// +// log.debug("Original response.........: "+communityInfo.toString()); +// +// +// +// return communityInfo; +// } +//} diff --git a/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/UserInfo.java b/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/UserInfo.java index 2c57478..127f799 100644 --- a/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/UserInfo.java +++ b/src/main/java/eu/dnetlib/uoaadmintools/handlers/utils/UserInfo.java @@ -1,46 +1,46 @@ -package eu.dnetlib.uoaadmintools.handlers.utils; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by argirok on 23/6/2017. - */ -public class UserInfo { - String name; - String email; - List edu_person_entitlements = new ArrayList(); - - @Override - public String toString() { - return "UserInfo{" + - "name='" + name + '\'' + - ", email='" + email + '\'' + - ", edu_person_entitlements=" + edu_person_entitlements + - '}'; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public List getEdu_person_entitlements() { - return edu_person_entitlements; - } - - public void setEdu_person_entitlements(List edu_person_entitlements) { - this.edu_person_entitlements = edu_person_entitlements; - } -} +//package eu.dnetlib.uoaadmintools.handlers.utils; +// +//import java.util.ArrayList; +//import java.util.List; +// +///** +// * Created by argirok on 23/6/2017. +// */ +//public class UserInfo { +// String name; +// String email; +// List edu_person_entitlements = new ArrayList(); +// +// @Override +// public String toString() { +// return "UserInfo{" + +// "name='" + name + '\'' + +// ", email='" + email + '\'' + +// ", edu_person_entitlements=" + edu_person_entitlements + +// '}'; +// } +// +// public String getName() { +// return name; +// } +// +// public void setName(String name) { +// this.name = name; +// } +// +// public String getEmail() { +// return email; +// } +// +// public void setEmail(String email) { +// this.email = email; +// } +// +// public List getEdu_person_entitlements() { +// return edu_person_entitlements; +// } +// +// public void setEdu_person_entitlements(List edu_person_entitlements) { +// this.edu_person_entitlements = edu_person_entitlements; +// } +//}