[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).
This commit is contained in:
Konstantina Galouni 2021-02-25 11:57:22 +00:00
parent 40b7fa40cd
commit 6c452b5433
15 changed files with 673 additions and 505 deletions

View File

@ -50,10 +50,10 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- <dependency>--> <dependency>
<!-- <groupId>org.springframework.boot</groupId>--> <groupId>org.springframework.boot</groupId>
<!-- <artifactId>spring-boot-starter-security</artifactId>--> <artifactId>spring-boot-starter-security</artifactId>
<!-- </dependency>--> </dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>

View File

@ -1,8 +1,9 @@
package eu.dnetlib.uoaadmintools; package eu.dnetlib.uoaadmintools;
import eu.dnetlib.uoaadmintools.configuration.properties.MongoConfig; 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 eu.dnetlib.uoaauthorizationlibrary.configuration.AuthorizationConfiguration;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@ -15,8 +16,9 @@ import org.springframework.context.annotation.PropertySources;
@PropertySource("classpath:admintools.properties"), @PropertySource("classpath:admintools.properties"),
@PropertySource(value = "classpath:dnet-override.properties", ignoreResourceNotFound = true) @PropertySource(value = "classpath:dnet-override.properties", ignoreResourceNotFound = true)
}) })
@EnableConfigurationProperties({SecurityConfig.class, MongoConfig.class}) //SecurityConfig.class,
//@Import(AuthorizationConfiguration.class) @EnableConfigurationProperties({MongoConfig.class})
@Import(AuthorizationConfiguration.class)
public class UoaAdminToolsApplication { public class UoaAdminToolsApplication {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -1,7 +1,7 @@
package eu.dnetlib.uoaadmintools; package eu.dnetlib.uoaadmintools;
import eu.dnetlib.uoaadmintools.configuration.properties.SecurityConfig; //import eu.dnetlib.uoaadmintools.configuration.properties.SecurityConfig;
import eu.dnetlib.uoaadmintools.handlers.AuthorizationHandler; //import eu.dnetlib.uoaadmintools.handlers.AuthorizationHandler;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -18,8 +18,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
public class UoaAdminToolsConfiguration extends WebMvcConfigurerAdapter { public class UoaAdminToolsConfiguration extends WebMvcConfigurerAdapter {
private final Logger log = Logger.getLogger(this.getClass()); private final Logger log = Logger.getLogger(this.getClass());
@Autowired // @Autowired
private SecurityConfig securityConfig; // private SecurityConfig securityConfig;
@Bean @Bean
@ -27,11 +27,11 @@ public class UoaAdminToolsConfiguration extends WebMvcConfigurerAdapter {
return new PropertySourcesPlaceholderConfigurer(); return new PropertySourcesPlaceholderConfigurer();
} }
@Override // @Override
public void addInterceptors(InterceptorRegistry registry) { // public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthorizationHandler(securityConfig.getUserInfoUrl(), securityConfig.getOriginServer(), securityConfig.getPostsAllowed())) // registry.addInterceptor(new AuthorizationHandler(securityConfig.getUserInfoUrl(), securityConfig.getOriginServer(), securityConfig.getPostsAllowed()))
.addPathPatterns("/**"); // .addPathPatterns("/**");
//
} // }
} }

View File

@ -1,40 +1,40 @@
package eu.dnetlib.uoaadmintools.configuration.properties; //package eu.dnetlib.uoaadmintools.configuration.properties;
//
import org.springframework.boot.context.properties.ConfigurationProperties; //import org.springframework.boot.context.properties.ConfigurationProperties;
//
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
//
@ConfigurationProperties("admintool.security") //@ConfigurationProperties("admintool.security")
public class SecurityConfig { //public class SecurityConfig {
//
private String userInfoUrl; // private String userInfoUrl;
private String originServer; // private String originServer;
private List<String> postsAllowed = new ArrayList<>(); // private List<String> postsAllowed = new ArrayList<>();
//
public void setUserInfoUrl(String userInfoUrl) { // public void setUserInfoUrl(String userInfoUrl) {
this.userInfoUrl = userInfoUrl; // this.userInfoUrl = userInfoUrl;
} // }
//
public void setOriginServer(String originServer) { // public void setOriginServer(String originServer) {
this.originServer = originServer; // this.originServer = originServer;
} // }
//
//
public void setPostsAllowed(List<String> posts) { // public void setPostsAllowed(List<String> posts) {
this.postsAllowed = posts; // this.postsAllowed = posts;
} // }
//
public String getUserInfoUrl() { // public String getUserInfoUrl() {
return userInfoUrl; // return userInfoUrl;
} // }
//
public String getOriginServer() { // public String getOriginServer() {
return originServer; // return originServer;
} // }
//
public List<String> getPostsAllowed() { // public List<String> getPostsAllowed() {
return postsAllowed; // return postsAllowed;
} // }
//
} //}

View File

@ -7,12 +7,17 @@ import eu.dnetlib.uoaadmintools.services.StatisticsService;
import eu.dnetlib.uoaadmintools.services.SubscriberService; import eu.dnetlib.uoaadmintools.services.SubscriberService;
import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.*; 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 eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.*; import java.util.*;
import org.springframework.security.access.prepost.PreAuthorize;
@RestController @RestController
@RequestMapping("/community") @RequestMapping("/community")
@ -20,6 +25,9 @@ import java.util.*;
public class CommunityController { public class CommunityController {
private final Logger log = Logger.getLogger(this.getClass()); private final Logger log = Logger.getLogger(this.getClass());
@Autowired
private RolesUtils rolesUtils;
@Autowired @Autowired
private LayoutService layoutService; private LayoutService layoutService;
@ -45,9 +53,14 @@ public class CommunityController {
return portalService.getAllPortalsFullByType("community"); return portalService.getAllPortalsFullByType("community");
} }
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/update", method = RequestMethod.POST) @RequestMapping(value = "/update", method = RequestMethod.POST)
public PortalResponse updateCommunity(@RequestBody Portal portal) { 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 old_pid = portalService.getPortalById(portal.getId()).getPid();
String new_pid = portal.getPid(); String new_pid = portal.getPid();
@ -64,9 +77,14 @@ public class CommunityController {
return portalResponse; return portalResponse;
} }
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/save", method = RequestMethod.POST) @RequestMapping(value = "/save", method = RequestMethod.POST)
public PortalResponse insertCommunity(@RequestBody Portal portal) { 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); PortalResponse portalResponse = portalService.insertPortal(portal);
statisticsService.createPortalStatistics(portal.getPid()); statisticsService.createPortalStatistics(portal.getPid());
@ -75,11 +93,22 @@ public class CommunityController {
return portalResponse; return portalResponse;
} }
// cannot handle MismatchingContent @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/delete", method = RequestMethod.POST) @RequestMapping(value = "/delete", method = RequestMethod.POST)
public Boolean deleteCommunities(@RequestBody List<String> portals) { public Boolean deleteCommunities(@RequestBody List<String> portals) {
List<String> roles = rolesUtils.getRoles();
for (String id: portals) { 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); String pid = portalService.deletePortal(id);
statisticsService.deleteByPid(pid); statisticsService.deleteByPid(pid);
@ -93,14 +122,36 @@ public class CommunityController {
@RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET) @RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET)
public Layout getLayoutForCommunity(@PathVariable(value = "pid") String pid) { 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); return layoutService.findByPid(pid);
} }
// @PreAuthorize("hasAnyAuthority(" + @PreAuthorize("hasAnyAuthority(" +
// "@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN, " + "@AuthorizationService.PORTAL_ADMIN, " +
// "@AuthorizationService.curator(#portalType), @AuthorizationService.manager(#portalType, #pid))") "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))")
@RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST) @RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST)
public Layout updateLayoutForCommunity(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) { 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); return layoutService.save(layout);
} }
} }

View File

@ -4,8 +4,11 @@ import eu.dnetlib.uoaadmintools.entities.Layout;
import eu.dnetlib.uoaadmintools.services.LayoutService; import eu.dnetlib.uoaadmintools.services.LayoutService;
import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.*; 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 eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -14,6 +17,7 @@ import java.util.*;
@RestController @RestController
@RequestMapping("/connect") @RequestMapping("/connect")
@CrossOrigin(origins = "*") @CrossOrigin(origins = "*")
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
public class ConnectController { public class ConnectController {
private final Logger log = Logger.getLogger(this.getClass()); private final Logger log = Logger.getLogger(this.getClass());
@ -23,9 +27,13 @@ public class ConnectController {
@Autowired @Autowired
private PortalService portalService; private PortalService portalService;
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/update", method = RequestMethod.POST) @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); PortalResponse portalResponse = portalService.updatePortal(portal);
String old_pid = portalResponse.getPid(); String old_pid = portalResponse.getPid();
@ -37,18 +45,30 @@ public class ConnectController {
return portalResponse; return portalResponse;
} }
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/save", method = RequestMethod.POST) @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); PortalResponse portalResponse = portalService.insertPortal(portal);
return portalResponse; return portalResponse;
} }
// cannot handle MismatchingContent
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/delete", method = RequestMethod.POST) @RequestMapping(value = "/delete", method = RequestMethod.POST)
public Boolean deleteCommunities(@RequestBody List<String> portals) { public Boolean deleteConnect(@RequestBody List<String> portals) {
for (String id: 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); String pid = portalService.deletePortal(id);
layoutService.deleteByPid(pid); layoutService.deleteByPid(pid);
} }
@ -56,17 +76,15 @@ public class ConnectController {
return true; return true;
} }
@RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET) // @RequestMapping(value = "/{pid}/layout", method = RequestMethod.GET)
public Layout getLayoutForCommunity(@PathVariable(value = "pid") String pid) { // public Layout getLayoutForConnect(@PathVariable(value = "pid") String pid) {
return layoutService.findByPid(pid); // return layoutService.findByPid(pid);
} // }
//
// @PreAuthorize("hasAnyAuthority(" + // @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
// "@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN, " + // @RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST)
// "@AuthorizationService.curator(#portalType), @AuthorizationService.manager(#portalType, #pid))") // public Layout updateLayoutForConnect(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) {
@RequestMapping(value = "/{pid}/layout", method = RequestMethod.POST) // return layoutService.save(layout);
public Layout updateLayoutForCommunity(@PathVariable(value = "pid") String pid, @RequestBody Layout layout) { // }
return layoutService.save(layout);
}
} }

View File

@ -3,8 +3,10 @@ package eu.dnetlib.uoaadmintools.controllers;
import eu.dnetlib.uoaadmintools.dao.CuratorDAO; import eu.dnetlib.uoaadmintools.dao.CuratorDAO;
import eu.dnetlib.uoaadmintools.entities.curator.Curator; import eu.dnetlib.uoaadmintools.entities.curator.Curator;
import eu.dnetlib.uoaadmintools.entities.curator.CuratorResponse; import eu.dnetlib.uoaadmintools.entities.curator.CuratorResponse;
import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -19,6 +21,8 @@ public class CuratorController {
@Autowired @Autowired
private CuratorDAO curatorDAO; private CuratorDAO curatorDAO;
@Autowired
private RolesUtils rolesUtils;
/** /**
* Return a list with curator. If list of emails does not existed return all curators, else return * 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 * @param id
* @return * @return
*/ */
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/curator/{id}", method = RequestMethod.GET) @RequestMapping(value = "/curator/{id}", method = RequestMethod.GET)
public Curator getCuratorById(@PathVariable String id) { public Curator getCuratorById(@PathVariable String id) {
return curatorDAO.findById(id); return curatorDAO.findById(id);
@ -62,8 +67,11 @@ public class CuratorController {
* @param curator * @param curator
* @return * @return
*/ */
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/curator", method = RequestMethod.POST) @RequestMapping(value = "/curator", method = RequestMethod.POST)
public Curator insertCurator(@RequestBody Curator curator) { public Curator insertCurator(@RequestBody Curator curator) {
String aaiId = rolesUtils.getAaiId();
curator.setId(aaiId);
return curatorDAO.save(curator); return curatorDAO.save(curator);
} }
@ -73,6 +81,7 @@ public class CuratorController {
* *
* @param emails * @param emails
*/ */
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/curator", method = RequestMethod.DELETE) @RequestMapping(value = "/curator", method = RequestMethod.DELETE)
public void deleteCurators(@RequestBody(required = false) Optional<List<String>> emails) { public void deleteCurators(@RequestBody(required = false) Optional<List<String>> emails) {
if(emails.isPresent()) { if(emails.isPresent()) {

View File

@ -2,8 +2,11 @@ package eu.dnetlib.uoaadmintools.controllers;
import eu.dnetlib.uoaadmintoolslibrary.entities.Portal; import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.*; 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 eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -12,32 +15,46 @@ import java.util.*;
@RestController @RestController
@RequestMapping("/explore") @RequestMapping("/explore")
@CrossOrigin(origins = "*") @CrossOrigin(origins = "*")
//@PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)") @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
public class ExploreController { public class ExploreController {
private final Logger log = Logger.getLogger(this.getClass()); private final Logger log = Logger.getLogger(this.getClass());
@Autowired @Autowired
private PortalService portalService; private PortalService portalService;
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/update", method = RequestMethod.POST) @RequestMapping(value = "/update", method = RequestMethod.POST)
public PortalResponse updateExplore(@RequestBody Portal portal) { 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); PortalResponse portalResponse = portalService.updatePortal(portal);
return portalResponse; return portalResponse;
} }
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/save", method = RequestMethod.POST) @RequestMapping(value = "/save", method = RequestMethod.POST)
public PortalResponse insertExplore(@RequestBody Portal portal) { 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); PortalResponse portalResponse = portalService.insertPortal(portal);
return portalResponse; return portalResponse;
} }
// cannot handle MismatchingContent // cannot handle MismatchingContent
// @PreAuthorize("hasAnyAuthority(@AuthorizationService.SUPER_ADMIN, @AuthorizationService.PORTAL_ADMIN)")
@RequestMapping(value = "/delete", method = RequestMethod.POST) @RequestMapping(value = "/delete", method = RequestMethod.POST)
public Boolean deleteExplore(@RequestBody List<String> portals) throws Exception { public Boolean deleteExplore(@RequestBody List<String> portals) throws Exception {
for (String id : portals) { 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); portalService.deletePortal(id);
} }

View File

@ -2,10 +2,15 @@ package eu.dnetlib.uoaadmintools.controllers;
import eu.dnetlib.uoaadmintools.dao.NotificationsDAO; import eu.dnetlib.uoaadmintools.dao.NotificationsDAO;
import eu.dnetlib.uoaadmintools.entities.Notifications; 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.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO; 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.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -22,36 +27,92 @@ public class NotificationsController {
private NotificationsDAO notificationsDAO; private NotificationsDAO notificationsDAO;
@Autowired @Autowired
private PortalDAO portalDAO; 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<Notifications> getNotifications(@PathVariable(value = "pid") String pid ) throws ContentNotFoundException { public List<Notifications> getNotifications(@PathVariable(value = "pid") String pid ) throws ContentNotFoundException {
if(portalDAO.findByPid(pid) == null){ Portal portal = portalDAO.findByPid(pid);
throw new ContentNotFoundException("Portal not found"); 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> notifications = notificationsDAO.findByPortalPid(pid); List<Notifications> notifications = notificationsDAO.findByPortalPid(pid);
if(notifications == null || notifications.size() == 0){ 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; 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) @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); Notifications notifications = notificationsDAO.findByManagerEmailAndPortalPid(email,pid);
if(notifications!= null){ if(notifications!= null){
notificationsDAO.delete(notifications.getId()); notificationsDAO.delete(notifications.getId());
}else{ }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) @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.POST)
public Notifications saveEntity(@PathVariable(value = "pid") String pid, @RequestBody Notifications notifications) throws ContentNotFoundException { public Notifications saveNotification(@PathVariable(value = "pid") String pid, @RequestBody Notifications notifications) throws ContentNotFoundException {
if(portalDAO.findByPid(pid) == null){ Portal portal = portalDAO.findByPid(pid);
throw new ContentNotFoundException("Portal not found"); 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); Notifications saved = notificationsDAO.findByManagerEmailAndPortalPid(notifications.getManagerEmail(),pid);
log.debug(saved); log.debug(saved);
if(saved!= null){ if(saved!= null){
@ -62,10 +123,10 @@ public class NotificationsController {
log.debug(notifications); log.debug(notifications);
Notifications savedNotifications = notificationsDAO.save(notifications); Notifications savedNotifications = notificationsDAO.save(notifications);
return savedNotifications; return savedNotifications;
}else{ // } else{
log.error("No user e-mail specified"); // log.error("Save notifications: No user e-mail specified");
return null; // return null;
} // }
} }

View File

@ -6,8 +6,8 @@ import eu.dnetlib.uoaadmintools.dao.SubscriberDAO;
import eu.dnetlib.uoaadmintools.entities.subscriber.PortalSubscribers; import eu.dnetlib.uoaadmintools.entities.subscriber.PortalSubscribers;
import eu.dnetlib.uoaadmintools.entities.subscriber.Subscriber; import eu.dnetlib.uoaadmintools.entities.subscriber.Subscriber;
import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException; import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils; //import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils;
import eu.dnetlib.uoaadmintools.handlers.utils.UserInfo; //import eu.dnetlib.uoaadmintools.handlers.utils.UserInfo;
import eu.dnetlib.uoaadmintoolslibrary.responses.SingleValueWrapperResponse; import eu.dnetlib.uoaadmintoolslibrary.responses.SingleValueWrapperResponse;
import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO; import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;

View File

@ -14,6 +14,8 @@ public class Notifications {
Boolean notifyForNewSubscribers = true; Boolean notifyForNewSubscribers = true;
String managerEmail; String managerEmail;
String portalPid; String portalPid;
String aaiId;
public Notifications(){ public Notifications(){
} }
@ -62,6 +64,14 @@ public class Notifications {
this.portalPid = portalPid; this.portalPid = portalPid;
} }
public String getAaiId() {
return aaiId;
}
public void setAaiId(String aaiId) {
this.aaiId = aaiId;
}
@Override @Override
public String toString() { public String toString() {
return "Notifications{" + return "Notifications{" +

View File

@ -1,71 +1,71 @@
package eu.dnetlib.uoaadmintools.handlers; //package eu.dnetlib.uoaadmintools.handlers;
//
import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils; //import eu.dnetlib.uoaadmintools.handlers.utils.AuthorizationUtils;
import org.apache.log4j.Logger; //import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value; //import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; //import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
//
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
import java.util.List; //import java.util.List;
//
/** ///**
* Created by argirok on 23/2/2018. // * Created by argirok on 23/2/2018.
*/ // */
public class AuthorizationHandler extends HandlerInterceptorAdapter { //public class AuthorizationHandler extends HandlerInterceptorAdapter {
private final Logger log = Logger.getLogger(this.getClass()); // private final Logger log = Logger.getLogger(this.getClass());
private AuthorizationUtils helper = new AuthorizationUtils(); // private AuthorizationUtils helper = new AuthorizationUtils();
private List<String> allowedPostRequests; // private List<String> allowedPostRequests;
//
public AuthorizationHandler(String userInfoUrl, String originServer, List<String> allowedPostRequests){ // public AuthorizationHandler(String userInfoUrl, String originServer, List<String> allowedPostRequests){
helper.setOriginServer(originServer); // helper.setOriginServer(originServer);
helper.setUserInfoUrl(userInfoUrl); // helper.setUserInfoUrl(userInfoUrl);
this.allowedPostRequests = allowedPostRequests; // 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;
}
// @Override // @Override
// public void postHandle( // public boolean preHandle(
// HttpServletRequest request, // HttpServletRequest request,
// HttpServletResponse response, // HttpServletResponse response,
// Object handler, // Object handler) throws Exception {
// ModelAndView modelAndView) throws Exception { //// log.debug("request method " + request.getRemoteHost());
// log.info("I am here - postHandle "); //// 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( //// @Override
// HttpServletRequest request, //// public void postHandle(
// HttpServletResponse response, //// HttpServletRequest request,
// Object handler, Exception ex) { //// HttpServletResponse response,
// log.info("I am here - afterCompletion "); //// 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 ");
//// }
//
//}

View File

@ -1,215 +1,97 @@
package eu.dnetlib.uoaadmintools.handlers.utils; //package eu.dnetlib.uoaadmintools.handlers.utils;
//
import org.apache.log4j.Logger; //import org.apache.log4j.Logger;
//
import javax.servlet.http.Cookie; //import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader; //import java.io.BufferedReader;
import java.io.InputStreamReader; //import java.io.InputStreamReader;
import java.io.StringReader; //import java.io.StringReader;
import java.net.HttpURLConnection; //import java.net.HttpURLConnection;
import java.net.URL; //import java.net.URL;
import java.util.Enumeration; //import java.util.Enumeration;
//
import com.google.gson.Gson; //import com.google.gson.Gson;
//
/** ///**
* Created by argirok on 27/2/2018. // * Created by argirok on 27/2/2018.
*/ // */
public class AuthorizationUtils { //public class AuthorizationUtils {
private final Logger log = Logger.getLogger(this.getClass()); // private final Logger log = Logger.getLogger(this.getClass());
private String userInfoUrl = null; // private String userInfoUrl = null;
// private String communityAPI =""; //// private String communityAPI ="";
// List<String> adminRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Portal Administrator")); //// List<String> adminRoles = new ArrayList<String>(Arrays.asList("Super Administrator", "Portal Administrator"));
private String originServer= null; // private String originServer= null;
public Boolean checkCookies(HttpServletRequest request){ // public Boolean checkCookies(HttpServletRequest request){
Boolean valid = true; // Boolean valid = true;
String cookieValue = this.getCookie(request,"AccessToken"); // String cookieValue = this.getCookie(request,"AccessToken");
if(cookieValue == null || cookieValue.isEmpty()){ // if(cookieValue == null || cookieValue.isEmpty()){
log.info("no cookie available "); // log.info("no cookie available ");
valid = false; // valid = false;
}else { // }else {
String headerValue = this.getHeadersInfo(request, "x-xsrf-token"); // String headerValue = this.getHeadersInfo(request, "x-xsrf-token");
if(headerValue == null || headerValue.isEmpty()){ // if(headerValue == null || headerValue.isEmpty()){
log.info("no header available "); // log.info("no header available ");
valid = false; // valid = false;
}else{ // }else{
if(!cookieValue.equals(headerValue)){ // if(!cookieValue.equals(headerValue)){
log.info("no proper header or cookie "); // log.info("no proper header or cookie ");
valid = false; // valid = false;
}else if(!hasValidOrigin(this.getHeadersInfo(request, "origin"))){ // }else if(!hasValidOrigin(this.getHeadersInfo(request, "origin"))){
log.info("no proper origin "); // log.info("no proper origin ");
valid = false; // 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<String> givenRoles, List<String> 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 valid;
// return false;
//
// } // }
// 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 ) { // return null;
// // }
// for (int i = 0; i < communityInfo.getManagers().size(); i++) { // private String getHeadersInfo(HttpServletRequest request, String name) {
// String manager = communityInfo.getManagers().get(i);
// log.debug("Community manager: "+manager);
// //
// 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) { // public boolean hasValidOrigin(String origin) {
// String url = userInfoUrl + community; // 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; // URL obj = null;
// String responseStr = null; // String responseStr=null;
// log.debug("Community info url is " + url); //// log.debug("User info url is "+url);
// //
// try { // try {
// obj = new URL(url); // obj = new URL(url);
// HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// log.debug("User info response code is: " + con.getResponseCode());
// if (con.getResponseCode() != 200) { // if (con.getResponseCode() != 200) {
// log.debug("User info response code is: " + con.getResponseCode());
// return null; // return null;
// } // }
// BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); // BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
@ -220,15 +102,15 @@ public class AuthorizationUtils {
// } // }
// in.close(); // in.close();
// responseStr = response.toString(); // responseStr = response.toString();
// } catch (Exception e) { // }catch(Exception e){
// log.error("An error occured while trying to fetch user info ", e); // log.error("An error occured while trying to fetch user info ",e);
// return null; // 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){ // if (json == null){
// return null; // return null;
// } // }
@ -236,18 +118,136 @@ public class AuthorizationUtils {
// BufferedReader br = new BufferedReader(new StringReader(json)); // BufferedReader br = new BufferedReader(new StringReader(json));
// //convert the json string back to object // //convert the json string back to object
// Gson gson = new Gson(); // Gson gson = new Gson();
// CommunityInfo communityInfo = null; // UserInfo userInfo = null;
// try { // try {
// communityInfo = gson.fromJson(br, CommunityInfo.class); // userInfo = gson.fromJson(br, UserInfo.class);
// }catch(Exception e){ // }catch(Exception e){
// log.debug("Error in parsing json response. Given json is : "+json, e); // log.debug("Error in parsing json response. Given json is : "+json, e);
// return null; // 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 userInfo;
// return communityInfo;
// } // }
} // 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<String> givenRoles, List<String> 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;
//// }
//}

View File

@ -1,81 +1,81 @@
package eu.dnetlib.uoaadmintools.handlers.utils; //package eu.dnetlib.uoaadmintools.handlers.utils;
//
import com.google.gson.Gson; //import com.google.gson.Gson;
import org.apache.log4j.Logger; //import org.apache.log4j.Logger;
//
import java.io.BufferedReader; //import java.io.BufferedReader;
import java.io.InputStreamReader; //import java.io.InputStreamReader;
import java.io.StringReader; //import java.io.StringReader;
import java.net.HttpURLConnection; //import java.net.HttpURLConnection;
import java.net.URL; //import java.net.URL;
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
//
/** ///**
* Created by argirok on 27/2/2018. // * Created by argirok on 27/2/2018.
*/ // */
public class CommunityInfo { //public class CommunityInfo {
//
List<String> managers = new ArrayList<String>(); // List<String> managers = new ArrayList<String>();
private final Logger log = Logger.getLogger(this.getClass()); // private final Logger log = Logger.getLogger(this.getClass());
//
public List<String> getManagers() { // public List<String> getManagers() {
return managers; // return managers;
} // }
//
public void setManagers(List<String> managers) { // public void setManagers(List<String> managers) {
this.managers = managers; // this.managers = managers;
} // }
//
private CommunityInfo getCommunityInfo(String communityAPI, String community) { // private CommunityInfo getCommunityInfo(String communityAPI, String community) {
String url = communityAPI + community; // String url = communityAPI + community;
URL obj = null; // URL obj = null;
String responseStr = null; // String responseStr = null;
log.debug("Community info url is " + url); // log.debug("Community info url is " + url);
//
try { // try {
obj = new URL(url); // obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // HttpURLConnection con = (HttpURLConnection) obj.openConnection();
log.debug("User info response code is: " + con.getResponseCode()); // log.debug("User info response code is: " + con.getResponseCode());
if (con.getResponseCode() != 200) { // if (con.getResponseCode() != 200) {
return null; // return null;
} // }
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); // BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer(); // StringBuffer response = new StringBuffer();
String inputLine; // String inputLine;
while ((inputLine = in.readLine()) != null) { // while ((inputLine = in.readLine()) != null) {
response.append(inputLine).append("\n"); // response.append(inputLine).append("\n");
} // }
in.close(); // in.close();
responseStr = response.toString(); // responseStr = response.toString();
} catch (Exception e) { // } catch (Exception e) {
log.error("An error occured while trying to fetch user info ", e); // log.error("An error occured while trying to fetch user info ", e);
return null; // return null;
} // }
return json2CommunityInfo(community); // return json2CommunityInfo(community);
} // }
private CommunityInfo json2CommunityInfo(String json){ // private CommunityInfo json2CommunityInfo(String json){
//
log.debug("Try to create CommunityInfo class from json: "+json); // log.debug("Try to create CommunityInfo class from json: "+json);
if (json == null){ // if (json == null){
return null; // return null;
} // }
//
BufferedReader br = new BufferedReader(new StringReader(json)); // BufferedReader br = new BufferedReader(new StringReader(json));
//convert the json string back to object // //convert the json string back to object
Gson gson = new Gson(); // Gson gson = new Gson();
CommunityInfo communityInfo = null; // CommunityInfo communityInfo = null;
try { // try {
communityInfo = gson.fromJson(br, CommunityInfo.class); // communityInfo = gson.fromJson(br, CommunityInfo.class);
}catch(Exception e){ // }catch(Exception e){
log.debug("Error in parsing json response. Given json is : "+json, e); // log.debug("Error in parsing json response. Given json is : "+json, e);
return null; // return null;
} // }
//
log.debug("Original response.........: "+communityInfo.toString()); // log.debug("Original response.........: "+communityInfo.toString());
//
//
//
return communityInfo; // return communityInfo;
} // }
} //}

View File

@ -1,46 +1,46 @@
package eu.dnetlib.uoaadmintools.handlers.utils; //package eu.dnetlib.uoaadmintools.handlers.utils;
//
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
//
/** ///**
* Created by argirok on 23/6/2017. // * Created by argirok on 23/6/2017.
*/ // */
public class UserInfo { //public class UserInfo {
String name; // String name;
String email; // String email;
List<String> edu_person_entitlements = new ArrayList<String>(); // List<String> edu_person_entitlements = new ArrayList<String>();
//
@Override // @Override
public String toString() { // public String toString() {
return "UserInfo{" + // return "UserInfo{" +
"name='" + name + '\'' + // "name='" + name + '\'' +
", email='" + email + '\'' + // ", email='" + email + '\'' +
", edu_person_entitlements=" + edu_person_entitlements + // ", edu_person_entitlements=" + edu_person_entitlements +
'}'; // '}';
} // }
//
public String getName() { // public String getName() {
return name; // return name;
} // }
//
public void setName(String name) { // public void setName(String name) {
this.name = name; // this.name = name;
} // }
//
public String getEmail() { // public String getEmail() {
return email; // return email;
} // }
//
public void setEmail(String email) { // public void setEmail(String email) {
this.email = email; // this.email = email;
} // }
//
public List<String> getEdu_person_entitlements() { // public List<String> getEdu_person_entitlements() {
return edu_person_entitlements; // return edu_person_entitlements;
} // }
//
public void setEdu_person_entitlements(List<String> edu_person_entitlements) { // public void setEdu_person_entitlements(List<String> edu_person_entitlements) {
this.edu_person_entitlements = edu_person_entitlements; // this.edu_person_entitlements = edu_person_entitlements;
} // }
} //}