diff --git a/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java b/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java index 42087b1a9..5e5dab495 100644 --- a/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java +++ b/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java @@ -18,10 +18,10 @@ import java.util.List; public class EuDatApplication extends SpringBootServletInitializer { private static final Logger logger = LoggerFactory.getLogger(EuDatApplication.class); - /*@Override + @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(EuDatApplication.class); - }*/ + } public static void main(String[] args) { SpringApplication.run(EuDatApplication.class, args); diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Admin.java b/dmp-backend/src/main/java/eu/eudat/controllers/Admin.java index b1a50e373..fc1975f82 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Admin.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Admin.java @@ -5,7 +5,10 @@ import java.util.UUID; import eu.eudat.dao.entities.*; import eu.eudat.managers.DashBoardManager; import eu.eudat.models.dashboard.DashBoardStatistics; +import eu.eudat.models.security.Principal; +import eu.eudat.security.claims.ClaimedAuthorities; import eu.eudat.services.ApiContext; +import eu.eudat.types.Authorities; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; @@ -23,55 +26,57 @@ import eu.eudat.models.admin.composite.DatasetProfile; import javax.transaction.Transactional; import javax.validation.Valid; +import static eu.eudat.types.Authorities.ADMIN; + @RestController @CrossOrigin -public class Admin extends BaseController{ +public class Admin extends BaseController { - @Autowired - public Admin(ApiContext apiContext) { - super(apiContext); - } + @Autowired + public Admin(ApiContext apiContext) { + super(apiContext); + } - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/admin/addDmp" },consumes = "application/json", produces="application/json") - public ResponseEntity addDmp(@Valid @RequestBody DatasetProfile profile){ - try{ - eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile); - this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); - return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId()); - }catch(Exception ex){ - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\""+ex.getMessage()+"\"}"); - } - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/admin/addDmp/{id}" },consumes = "application/json", produces="application/json") - public ResponseEntity updateDmp(@PathVariable String id,@RequestBody DatasetProfile profile){ - try{ - eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile); + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/admin/addDmp"}, consumes = "application/json", produces = "application/json") + public ResponseEntity addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + try { + eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile); + this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); + return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId()); + } catch (Exception ex) { + ex.printStackTrace(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\"" + ex.getMessage() + "\"}"); + } + } - eu.eudat.entities.DatasetProfile datasetprofile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); - datasetprofile.setDefinition(modelDefinition.getDefinition()); - this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile); - - return ResponseEntity.status(HttpStatus.OK).body(null); - }catch(Exception ex){ - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\""+ex.getMessage()+"\"}"); - } - } - - @RequestMapping(method = RequestMethod.GET, value = { "/admin/get/{id}" }, produces="application/json") - public ResponseEntity get(@PathVariable String id){ - try{ - eu.eudat.entities.DatasetProfile profile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); - eu.eudat.models.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile); - datasetprofile.setLabel(profile.getLabel()); - return ResponseEntity.status(HttpStatus.OK).body(datasetprofile); - }catch(Exception ex){ - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\""+ex.getMessage()+"\"}"); - } - } + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/admin/addDmp/{id}"}, consumes = "application/json", produces = "application/json") + public ResponseEntity updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + try { + eu.eudat.entities.DatasetProfile modelDefinition = AdminManager.generateViewStyleDefinition(profile); + + eu.eudat.entities.DatasetProfile datasetprofile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + datasetprofile.setDefinition(modelDefinition.getDefinition()); + this.getApiContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile); + + return ResponseEntity.status(HttpStatus.OK).body(null); + } catch (Exception ex) { + ex.printStackTrace(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\"" + ex.getMessage() + "\"}"); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/admin/get/{id}"}, produces = "application/json") + public ResponseEntity get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + try { + eu.eudat.entities.DatasetProfile profile = this.getApiContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + eu.eudat.models.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile); + datasetprofile.setLabel(profile.getLabel()); + return ResponseEntity.status(HttpStatus.OK).body(datasetprofile); + } catch (Exception ex) { + ex.printStackTrace(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"reason\":\"" + ex.getMessage() + "\"}"); + } + } } diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Login.java b/dmp-backend/src/main/java/eu/eudat/controllers/Login.java index 6749cf691..c311d4b27 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Login.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Login.java @@ -1,6 +1,7 @@ package eu.eudat.controllers; import eu.eudat.exceptions.UnauthorisedException; +import eu.eudat.managers.UserManager; import eu.eudat.models.login.Credentials; import eu.eudat.models.helpers.responses.ResponseItem; import eu.eudat.models.login.LoginInfo; @@ -39,21 +40,36 @@ public class Login { } @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/externallogin" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> googleLogin(@RequestBody LoginInfo credentials) { + @RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> externallogin(@RequestBody LoginInfo credentials) { try { return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); - }catch (UnauthorisedException ex){ + } catch (UnauthorisedException ex) { throw ex; - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage())); } } - @RequestMapping(method = RequestMethod.GET, value = { "/twitterRequestToken" }, produces="application/json") - public @ResponseBody ResponseEntity> twitterRequestToken() { + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/nativelogin"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> nativelogin(@RequestBody Credentials credentials) { + try { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(UserManager.authenticate(this.authenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (UnauthorisedException ex) { + throw ex; + } catch (Exception ex) { + ex.printStackTrace(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json") + public @ResponseBody + ResponseEntity> twitterRequestToken() { try { return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.twitterTokenValidator.getRequestToken()).status(ApiMessageCode.NO_MESSAGE)); } catch (Exception ex) { @@ -62,8 +78,9 @@ public class Login { } } - @RequestMapping(method = RequestMethod.POST, value = { "/me" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> authMe(Principal principal) { + @RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> authMe(Principal principal) { try { return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.authenticationService.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE)); @@ -73,8 +90,9 @@ public class Login { } } - @RequestMapping(method = RequestMethod.POST, value = { "/logout" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> logout(Principal principal) { + @RequestMapping(method = RequestMethod.POST, value = {"/logout"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> logout(Principal principal) { try { this.authenticationService.Logout(principal.getToken()); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java b/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java index 916724d74..1378c6169 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java @@ -11,6 +11,7 @@ import eu.eudat.models.helpers.responses.*; import eu.eudat.models.project.ProjectCriteriaRequest; import eu.eudat.models.project.ProjectListingModel; import eu.eudat.models.security.Principal; +import eu.eudat.security.claims.ClaimedAuthorities; import eu.eudat.services.ApiContext; import eu.eudat.types.ApiMessageCode; import org.springframework.beans.factory.annotation.Autowired; @@ -33,6 +34,9 @@ import eu.eudat.models.project.ProjectTableRequest; import eu.eudat.proxy.config.exceptions.HugeResultSet; import eu.eudat.proxy.config.exceptions.NoURLFound; +import static eu.eudat.types.Authorities.ADMIN; +import static eu.eudat.types.Authorities.USER; + @RestController @CrossOrigin @@ -44,7 +48,8 @@ public class Projects extends BaseController { } @RequestMapping(method = RequestMethod.POST, value = {"/projects/getPaged"}, consumes = "application/json", produces = "application/json") - public @ResponseBody ResponseEntity>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) { + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody ProjectTableRequest projectTableRequest, Principal principal) { try { DataTableData dataTable = new ProjectManager().getPaged(this.getApiContext().getDatabaseRepository().getProjectDao(), projectTableRequest); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); @@ -56,7 +61,8 @@ public class Projects extends BaseController { } @RequestMapping(method = RequestMethod.GET, value = {"/projects/getSingle/{id}"}, produces = "application/json") - public @ResponseBody ResponseEntity> getSingle(@PathVariable String id, Principal principal) { + public @ResponseBody + ResponseEntity> getSingle(@PathVariable String id, Principal principal) { try { eu.eudat.models.project.Project project = new ProjectManager().getSingle(this.getApiContext().getDatabaseRepository().getProjectDao(), id); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(project).status(ApiMessageCode.NO_MESSAGE)); @@ -69,7 +75,8 @@ public class Projects extends BaseController { @Transactional @RequestMapping(method = RequestMethod.POST, value = {"/projects/createOrUpdate"}, consumes = "application/json", produces = "application/json") - public @ResponseBody ResponseEntity> addProject(@Valid @RequestBody eu.eudat.models.project.Project project, Principal principal) { + public @ResponseBody + ResponseEntity> addProject(@Valid @RequestBody eu.eudat.models.project.Project project, Principal principal) { try { ProjectManager.createOrUpdate(this.getApiContext().getDatabaseRepository().getProjectDao(), this.getApiContext().getDatabaseRepository().getUserInfoDao(), project, principal); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); @@ -81,7 +88,8 @@ public class Projects extends BaseController { @Transactional @RequestMapping(method = RequestMethod.DELETE, value = {"/projects/inactivate/{id}"}, consumes = "application/json", produces = "application/json") - public @ResponseBody ResponseEntity> inactivate(@PathVariable String id, Principal principal) { + public @ResponseBody + ResponseEntity> inactivate(@PathVariable String id, Principal principal) { try { Project project = new ProjectManager().inactivate(this.getApiContext().getDatabaseRepository().getProjectDao(), id); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); @@ -92,7 +100,8 @@ public class Projects extends BaseController { @RequestMapping(method = RequestMethod.POST, value = {"/projects/getWithExternal"}, consumes = "application/json", produces = "application/json") - public @ResponseBody ResponseEntity>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) { + public @ResponseBody + ResponseEntity>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) { try { List dataTable = new ProjectManager().getCriteriaWithExternal(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher()); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); @@ -103,7 +112,8 @@ public class Projects extends BaseController { } @RequestMapping(method = RequestMethod.POST, value = {"/projects/get"}, consumes = "application/json", produces = "application/json") - public @ResponseBody ResponseEntity>> get(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) { + public @ResponseBody + ResponseEntity>> get(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) { try { List dataTable = new ProjectManager().getCriteria(this.getApiContext().getDatabaseRepository().getProjectDao(), projectCriteria, this.getApiContext().getRemoteFetcher()); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); @@ -114,7 +124,8 @@ public class Projects extends BaseController { } @RequestMapping(method = RequestMethod.GET, value = {"/external/projects"}, produces = "application/json") - public @ResponseBody ResponseEntity> listExternalProjects(@RequestParam(value = "query", required = false) String query, Principal principal) { + public @ResponseBody + ResponseEntity> listExternalProjects(@RequestParam(value = "query", required = false) String query, Principal principal) { try { List> remoteRepos = this.getApiContext().getRemoteFetcher().getProjects(query); ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos); diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Users.java b/dmp-backend/src/main/java/eu/eudat/controllers/Users.java index 01fd9c921..462912402 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Users.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Users.java @@ -1,22 +1,64 @@ package eu.eudat.controllers; +import eu.eudat.managers.ProjectManager; +import eu.eudat.managers.UserManager; +import eu.eudat.models.helpers.common.DataTableData; +import eu.eudat.models.helpers.responses.ResponseItem; +import eu.eudat.models.project.ProjectListingModel; +import eu.eudat.models.project.ProjectTableRequest; +import eu.eudat.models.security.Principal; +import eu.eudat.models.userinfo.UserInfoTableRequestItem; +import eu.eudat.models.userinfo.UserListingModel; +import eu.eudat.security.claims.ClaimedAuthorities; import eu.eudat.services.ApiContext; +import eu.eudat.types.ApiMessageCode; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +import static eu.eudat.types.Authorities.ADMIN; +import static eu.eudat.types.Authorities.USER; @RestController @CrossOrigin -public class Users extends BaseController{ +public class Users extends BaseController { - @Autowired - public Users(ApiContext apiContext) { - super(apiContext); - } + @Autowired + public Users(ApiContext apiContext) { + super(apiContext); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/users/getPaged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + try { + DataTableData dataTable = UserManager.getPaged(this.getApiContext().getDatabaseRepository().getUserInfoDao(), userInfoTableRequestItem); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } catch (Exception ex) { + ex.printStackTrace(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem>().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage())); + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/users/editRoles"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> editRoles(@Valid @RequestBody UserListingModel userListingModel, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + try { + UserManager.editRoles(this.getApiContext(), userListingModel); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } catch (Exception ex) { + ex.printStackTrace(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.DEFAULT_ERROR_MESSAGE).message(ex.getMessage())); + } + } +} - } - diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/UserRoleDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserRoleDao.java new file mode 100644 index 000000000..deaa2d428 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserRoleDao.java @@ -0,0 +1,16 @@ +package eu.eudat.dao.entities; + +import eu.eudat.dao.DatabaseAccessLayer; +import eu.eudat.entities.UserInfo; +import eu.eudat.entities.UserRole; + +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 1/30/2018. + */ +public interface UserRoleDao extends DatabaseAccessLayer { + + List getUserRoles(UserInfo userInfo); +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/UserRoleDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserRoleDaoImpl.java new file mode 100644 index 000000000..7aaf231fb --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserRoleDaoImpl.java @@ -0,0 +1,39 @@ +package eu.eudat.dao.entities; + +import eu.eudat.dao.DatabaseAccess; +import eu.eudat.dao.DatabaseAccessLayer; +import eu.eudat.dao.databaselayer.service.DatabaseService; +import eu.eudat.entities.UserInfo; +import eu.eudat.entities.UserRole; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 1/30/2018. + */ +@Component("userRoleDao") +public class UserRoleDaoImpl extends DatabaseAccess implements UserRoleDao{ + + @Autowired + public UserRoleDaoImpl(DatabaseService databaseService) { + this.setDatabaseService(databaseService); + } + + @Override + public UserRole createOrUpdate(UserRole item) { + return this.getDatabaseService().createOrUpdate(item,UserRole.class); + } + + @Override + public UserRole find(UUID id) { + return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("id"),id)).getSingleOrDefault(); + } + + @Override + public List getUserRoles(UserInfo userInfo) { + return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("userInfo"),userInfo)).toList(); + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java index 2281e284f..9646ee96c 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java @@ -1,12 +1,16 @@ package eu.eudat.dao.entities.security; +import eu.eudat.dao.DatabaseAccessLayer; import eu.eudat.entities.Credential; +import eu.eudat.entities.Dataset; +import eu.eudat.models.login.Credentials; + +import java.util.UUID; /** * Created by ikalyvas on 12/15/2017. */ -public interface CredentialDao { - - Credential createOrUpdate(Credential item); +public interface CredentialDao extends DatabaseAccessLayer { + Credential getLoggedInCredentials(Credentials credentials); } diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java index 23b59e477..87d6e64ea 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java @@ -4,9 +4,13 @@ import eu.eudat.dao.DatabaseAccess; import eu.eudat.dao.databaselayer.service.DatabaseService; import eu.eudat.entities.Credential; import eu.eudat.entities.UserInfo; +import eu.eudat.models.login.Credentials; +import eu.eudat.security.validators.TokenValidatorFactoryImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.UUID; + /** * Created by ikalyvas on 12/15/2017. */ @@ -20,6 +24,21 @@ public class CredentialDaoImpl extends DatabaseAccess implements Cre @Override public Credential createOrUpdate(Credential item) { - return this.getDatabaseService().createOrUpdate(item,Credential.class); + return this.getDatabaseService().createOrUpdate(item, Credential.class); + } + + @Override + public Credential find(UUID id) { + return this.getDatabaseService().getQueryable(Credential.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault(); + } + + @Override + public Credential getLoggedInCredentials(Credentials credentials) { + return this.getDatabaseService().getQueryable(Credential.class).where(((builder, root) -> + builder.and( + builder.equal(root.get("publicValue"), credentials.getUsername()), + builder.equal(root.get("secret"), credentials.getSecret()), + builder.equal(root.get("provider"), TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue()) + ))).getSingleOrDefault(); } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Credential.java b/dmp-backend/src/main/java/eu/eudat/entities/Credential.java index e9e4255de..d1e69902b 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Credential.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Credential.java @@ -14,6 +14,8 @@ import java.util.UUID; public class Credential implements DataEntity { @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") private UUID id; diff --git a/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java b/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java index 3355dd617..2912b55b2 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java @@ -63,6 +63,9 @@ public class UserInfo implements DataEntity{ @OneToMany(mappedBy="userInfo",fetch = FetchType.LAZY) Set credentials = new HashSet<>(); + + @OneToMany(mappedBy="userInfo",fetch = FetchType.LAZY) + Set userRoles = new HashSet<>(); public Set getDmps() { return dmps; @@ -152,6 +155,14 @@ public class UserInfo implements DataEntity{ this.credentials = credentials; } + public Set getUserRoles() { + return userRoles; + } + + public void setUserRoles(Set userRoles) { + this.userRoles = userRoles; + } + @Override public void update(UserInfo entity) { this.name = entity.getName(); diff --git a/dmp-backend/src/main/java/eu/eudat/entities/UserRole.java b/dmp-backend/src/main/java/eu/eudat/entities/UserRole.java new file mode 100644 index 000000000..2f35d899d --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/entities/UserRole.java @@ -0,0 +1,62 @@ +package eu.eudat.entities; + +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 1/30/2018. + */ +@Entity +@Table(name = "\"UserRole\"") +public class UserRole implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Role\"", nullable = false) + private int role; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"UserId\"", nullable = false) + private UserInfo userInfo; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public int getRole() { + return role; + } + + public void setRole(int role) { + this.role = role; + } + + public UserInfo getUserInfo() { + return userInfo; + } + + public void setUserInfo(UserInfo userInfo) { + this.userInfo = userInfo; + } + + @Override + public void update(UserRole entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java b/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java index 28ff46a27..b36622892 100644 --- a/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java +++ b/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java @@ -2,16 +2,19 @@ package eu.eudat.handlers; import eu.eudat.exceptions.UnauthorisedException; import eu.eudat.models.security.Principal; +import eu.eudat.security.claims.ClaimedAuthorities; import eu.eudat.services.AuthenticationService; -import org.springframework.beans.factory.annotation.Autowired; +import eu.eudat.types.Authorities; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; -import java.util.Date; -import java.util.UUID; +import java.lang.annotation.Annotation; +import java.util.*; + +import static eu.eudat.types.Authorities.USER; /** * Created by ikalyvas on 12/15/2017. @@ -28,6 +31,8 @@ public final class PrincipalArgumentResolver implements HandlerMethodArgumentRes @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { String token = nativeWebRequest.getHeader("AuthToken"); + Optional claimsAnnotation = Arrays.stream(methodParameter.getParameterAnnotations()).filter(annotation -> annotation.annotationType().equals(ClaimedAuthorities.class)).findAny(); + List claimList = claimsAnnotation.map(annotation -> Arrays.asList(((ClaimedAuthorities) annotation).claims())).orElse(Authorities.all()); if (token == null) throw new UnauthorisedException("Authentication Information Is Missing"); UUID authToken; try { @@ -38,6 +43,7 @@ public final class PrincipalArgumentResolver implements HandlerMethodArgumentRes Principal principal = this.authenticationService.Touch(authToken); if (principal == null) throw new UnauthorisedException("Authentication Information Missing"); + if (!principal.isAuthorized(claimList)) throw new UnauthorisedException("You are not Authorized For this Action"); return principal; } diff --git a/dmp-backend/src/main/java/eu/eudat/managers/UserManager.java b/dmp-backend/src/main/java/eu/eudat/managers/UserManager.java index 79177509a..30a90a3f7 100644 --- a/dmp-backend/src/main/java/eu/eudat/managers/UserManager.java +++ b/dmp-backend/src/main/java/eu/eudat/managers/UserManager.java @@ -1,10 +1,27 @@ package eu.eudat.managers; +import eu.eudat.dao.entities.UserInfoDao; +import eu.eudat.dao.entities.UserRoleDao; +import eu.eudat.entities.Credential; +import eu.eudat.entities.UserRole; +import eu.eudat.exceptions.UnauthorisedException; +import eu.eudat.models.helpers.common.DataTableData; +import eu.eudat.models.login.Credentials; +import eu.eudat.models.security.Principal; +import eu.eudat.models.userinfo.UserInfo; +import eu.eudat.models.userinfo.UserInfoTableRequestItem; +import eu.eudat.models.userinfo.UserListingModel; +import eu.eudat.queryable.QueryableList; +import eu.eudat.services.ApiContext; +import eu.eudat.services.AuthenticationService; +import eu.eudat.utilities.builders.DomainModelConverter; import org.w3c.dom.Document; import org.w3c.dom.Element; import eu.eudat.utilities.builders.XmlBuilder; +import java.util.List; + public class UserManager { public static eu.eudat.models.user.composite.DatasetProfile generateDatasetProfileModel(eu.eudat.entities.DatasetProfile profile){ Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition()); @@ -16,4 +33,32 @@ public class UserManager { return datasetprofile; } + + public static DataTableData getPaged(UserInfoDao userInfoDao , UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { + QueryableList users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria()); + QueryableList pagedUsers = PaginationManager.applyPaging(users,userInfoTableRequestItem); + List modelUsers = new DomainModelConverter().fromDataModel(pagedUsers.toList(),UserListingModel.class); + DataTableData dataTableData = new DataTableData<>(); + dataTableData.setData(modelUsers); + dataTableData.setTotalCount(users.count()); + return dataTableData; + } + + public static void editRoles(ApiContext apiContext, UserListingModel user){ + eu.eudat.entities.UserInfo userInfo = apiContext.getDatabaseRepository().getUserInfoDao().find(user.getId()); + userInfo.getUserRoles().removeAll(userInfo.getUserRoles()); + userInfo = apiContext.getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo); + for(Integer role : user.getAppRoles()){ + UserRole userRole = new UserRole(); + userRole.setRole(role); + userRole.setUserInfo(userInfo); + apiContext.getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole); + } + } + + public static Principal authenticate(AuthenticationService authenticationService, Credentials credentials){ + Principal principal = authenticationService.Touch(credentials); + if(principal == null) throw new UnauthorisedException("Could not Sign In User"); + return principal; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java b/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java index f1d6509ed..299a01e67 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java +++ b/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java @@ -1,8 +1,11 @@ package eu.eudat.models.security; -import java.util.Date; -import java.util.Set; -import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonIgnore; +import eu.eudat.exceptions.UnauthorisedException; +import eu.eudat.types.Authorities; + +import java.util.*; +import java.util.stream.Collectors; /** * Created by ikalyvas on 12/15/2017. @@ -12,7 +15,7 @@ public class Principal { private UUID token; private String name; private Date expiresAt; - private Set roles; + private Set authorities; public UUID getId() { return id; @@ -46,11 +49,21 @@ public class Principal { this.expiresAt = expiresAt; } - public Set getRoles() { - return roles; + public Set getAuthorities() { + return authorities.stream().map(authz -> authz.getValue()).collect(Collectors.toSet()); } - public void setRoles(Set roles) { - this.roles = roles; + @JsonIgnore + public Set getAuthz() { + return this.authorities; + } + + public void setAuthorities(Set authorities) { + this.authorities = authorities; + } + + public boolean isAuthorized(List requiredAuthorities) { + if (!Collections.disjoint(this.authorities, requiredAuthorities) || requiredAuthorities.size() == 0) return true; + else return false; } } diff --git a/dmp-backend/src/main/java/eu/eudat/models/userinfo/UserInfoTableRequestItem.java b/dmp-backend/src/main/java/eu/eudat/models/userinfo/UserInfoTableRequestItem.java new file mode 100644 index 000000000..daecbf449 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/userinfo/UserInfoTableRequestItem.java @@ -0,0 +1,10 @@ +package eu.eudat.models.userinfo; + +import eu.eudat.models.criteria.UserInfoCriteria; +import eu.eudat.models.helpers.requests.TableRequest; + +/** + * Created by ikalyvas on 1/31/2018. + */ +public class UserInfoTableRequestItem extends TableRequest { +} diff --git a/dmp-backend/src/main/java/eu/eudat/models/userinfo/UserListingModel.java b/dmp-backend/src/main/java/eu/eudat/models/userinfo/UserListingModel.java new file mode 100644 index 000000000..89e8b8928 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/userinfo/UserListingModel.java @@ -0,0 +1,128 @@ +package eu.eudat.models.userinfo; + +import eu.eudat.entities.*; +import eu.eudat.entities.UserInfo; +import eu.eudat.models.DataModel; + +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * Created by ikalyvas on 1/31/2018. + */ +public class UserListingModel implements DataModel { + + private UUID id; + + private String email; + + private Short usertype; + + private Boolean verified_email; + + private String name; + + private Date created; + + private Date lastloggedin; + + private String additionalinfo; + + private List appRoles; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Short getUsertype() { + return usertype; + } + + public void setUsertype(Short usertype) { + this.usertype = usertype; + } + + public Boolean getVerified_email() { + return verified_email; + } + + public void setVerified_email(Boolean verified_email) { + this.verified_email = verified_email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getLastloggedin() { + return lastloggedin; + } + + public void setLastloggedin(Date lastloggedin) { + this.lastloggedin = lastloggedin; + } + + public String getAdditionalinfo() { + return additionalinfo; + } + + public void setAdditionalinfo(String additionalinfo) { + this.additionalinfo = additionalinfo; + } + + public List getAppRoles() { + return appRoles; + } + + public void setAppRoles(List appRoles) { + this.appRoles = appRoles; + } + + @Override + public void fromDataModel(UserInfo entity) throws InstantiationException, IllegalAccessException { + this.email = entity.getEmail(); + this.usertype = entity.getUsertype(); + this.verified_email = entity.getVerified_email(); + this.name = entity.getName(); + this.created = entity.getCreated(); + this.lastloggedin = entity.getLastloggedin(); + this.additionalinfo = entity.getAdditionalinfo(); + this.appRoles = entity.getUserRoles().stream().map(item -> item.getRole()).collect(Collectors.toList()); + } + + @Override + public UserInfo toDataModel() throws Exception { + return null; + } + + @Override + public String getHint() { + return null; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/security/claims/ClaimedAuthorities.java b/dmp-backend/src/main/java/eu/eudat/security/claims/ClaimedAuthorities.java new file mode 100644 index 000000000..de7ba6c66 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/security/claims/ClaimedAuthorities.java @@ -0,0 +1,20 @@ +package eu.eudat.security.claims; + +import eu.eudat.types.Authorities; +import org.springframework.social.facebook.api.User; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static eu.eudat.types.Authorities.USER; + +/** + * Created by ikalyvas on 1/30/2018. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface ClaimedAuthorities { + Authorities[] claims() default {USER}; +} diff --git a/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidatorFactoryImpl.java b/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidatorFactoryImpl.java index 1a5fb0878..502d96dd6 100644 --- a/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidatorFactoryImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidatorFactoryImpl.java @@ -13,7 +13,7 @@ import org.springframework.stereotype.Service; @Service("tokenValidatorFactory") public class TokenValidatorFactoryImpl implements TokenValidatorFactory{ public enum LoginProvider { - GOOGLE((short) 1), FACEBOOK((short) 2), TWITTER((short) 3), LINKEDIN((short) 4); + GOOGLE((short) 1), FACEBOOK((short) 2), TWITTER((short) 3), LINKEDIN((short) 4),NATIVELOGIN((short) 5); private short value; @@ -35,6 +35,8 @@ public class TokenValidatorFactoryImpl implements TokenValidatorFactory{ return TWITTER; case 4: return LINKEDIN; + case 5: + return NATIVELOGIN; default: throw new RuntimeException("Unsupported LoginProvider"); } diff --git a/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java b/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java index c770918d0..996a2f759 100644 --- a/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java +++ b/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java @@ -4,13 +4,18 @@ import eu.eudat.dao.entities.UserInfoDao; import eu.eudat.dao.entities.security.UserTokenDao; import eu.eudat.entities.Credential; import eu.eudat.entities.UserInfo; +import eu.eudat.entities.UserRole; import eu.eudat.entities.UserToken; import eu.eudat.models.criteria.UserInfoCriteria; +import eu.eudat.models.login.Credentials; import eu.eudat.models.loginprovider.LoginProviderUser; import eu.eudat.models.security.Principal; import eu.eudat.security.validators.TokenValidatorFactoryImpl; +import eu.eudat.types.Authorities; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import javax.xml.ws.ServiceMode; import java.util.*; @@ -21,14 +26,15 @@ import java.util.*; @Service("authenticationService ") public class AuthenticationService { private ApiContext apiContext; + private Environment environment; @Autowired - public AuthenticationService(ApiContext apiContext) { + public AuthenticationService(ApiContext apiContext, Environment environment) { + this.environment = environment; this.apiContext = apiContext; } - public Principal Touch(UUID token) - { + public Principal Touch(UUID token) { UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token); if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null; @@ -37,20 +43,16 @@ public class AuthenticationService { return principal; } - public void Logout(UUID token) - { + public void Logout(UUID token) { UserToken tokenEntry = this.apiContext.getDatabaseRepository().getUserTokenDao().find(token); this.apiContext.getDatabaseRepository().getUserTokenDao().delete(tokenEntry); } - private Principal Touch(UserToken token) - { + private Principal Touch(UserToken token) { if (token == null || token.getExpiresAt().before(new Date())) return null; UserInfo user = this.apiContext.getDatabaseRepository().getUserInfoDao().find(token.getUser().getId()); - if (user == null /*|| user.Status != ActivityStatus.Active*/) return null; - - //List appRoles = this._unitOfWork.UserRoles.GetAll().Where(x => x.UserId == token.UserId /*&& x.Status == ActivityStatus.Active*/).ToList(); + if (user == null) return null; Principal principal = new Principal(); principal.setId(user.getId()); @@ -58,23 +60,38 @@ public class AuthenticationService { principal.setExpiresAt(token.getExpiresAt()); principal.setName(user.getName()); - /*foreach (UserRole item in appRoles) - { - if (principal.AppRoles == null) principal.AppRoles = new HashSet(); - principal.AppRoles.Add(item.Role); + List userRoles = this.apiContext.getDatabaseRepository().getUserRoleDao().getUserRoles(user); + for (UserRole item : userRoles) { + if (principal.getAuthz() == null) principal.setAuthorities(new HashSet()); + principal.getAuthz().add(Authorities.fromInteger(item.getRole())); } - - if (this._config.Refresh) token.ExpiresAt = DateTime.UtcNow.AddMinutes(this._config.Lifetime); - */ return principal; } - public Principal Touch(LoginProviderUser profile){ + public Principal Touch(Credentials credentials) { + Credential credential = this.apiContext.getDatabaseRepository().getCredentialDao().getLoggedInCredentials(credentials); + + if (credential == null && credentials.getUsername().equals(environment.getProperty("autouser.root.username"))) credential = this.autoCreateUser(credentials.getUsername(),credentials.getSecret()); + + if(credential == null) return null; + + UserToken userToken = new UserToken(); + userToken.setUser(credential.getUserInfo()); + userToken.setIssuedAt(new Date()); + userToken.setToken(UUID.randomUUID()); + userToken.setExpiresAt(addADay(new Date())); + userToken = apiContext.getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken); + + return this.Touch(userToken); + + } + + public Principal Touch(LoginProviderUser profile) { UserInfoCriteria criteria = new UserInfoCriteria(); criteria.setEmail(profile.getEmail()); List users = apiContext.getDatabaseRepository().getUserInfoDao().getWithCriteria(criteria).toList(); UserInfo userInfo = null; - if(users.size()>0)userInfo = users.get(0); + if (users.size() > 0) userInfo = users.get(0); final Credential credential = new Credential(); credential.setId(UUID.randomUUID()); credential.setCreationTime(new Date()); @@ -82,9 +99,9 @@ public class AuthenticationService { credential.setLastUpdateTime(new Date()); credential.setProvider((int) profile.getProvider().getValue()); credential.setSecret(profile.getSecret()); - if(userInfo == null) { + if (userInfo == null) { userInfo = new UserInfo(); - userInfo.setName((String)profile.getName()); + userInfo.setName((String) profile.getName()); userInfo.setVerified_email(profile.getIsVerified()); userInfo.setEmail(profile.getEmail()); userInfo.setCreated(new Date()); @@ -95,15 +112,18 @@ public class AuthenticationService { credential.setPublicValue(userInfo.getName()); credential.setUserInfo(userInfo); apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential); - } - else { + + UserRole role = new UserRole(); + role.setRole(Authorities.USER.getValue()); + role.setUserInfo(userInfo); + + } else { userInfo.setLastloggedin(new Date()); Set credentials = userInfo.getCredentials(); - if(credentials.contains(credential)){ - Credential oldCredential = credentials.stream().filter(item->credential.getProvider().equals(item.getProvider())).findFirst().get(); + if (credentials.contains(credential)) { + Credential oldCredential = credentials.stream().filter(item -> credential.getProvider().equals(item.getProvider())).findFirst().get(); credential.setId(oldCredential.getId()); - } - else{ + } else { credential.setUserInfo(userInfo); credential.setId(UUID.randomUUID()); credential.setPublicValue(userInfo.getName()); @@ -122,7 +142,7 @@ public class AuthenticationService { return Touch(userToken.getToken()); } - private Date addADay(Date date){ + private Date addADay(Date date) { Date dt = new Date(); Calendar c = Calendar.getInstance(); c.setTime(dt); @@ -130,4 +150,34 @@ public class AuthenticationService { dt = c.getTime(); return dt; } + + + @Transactional + private Credential autoCreateUser(String username,String password){ + if(!environment.getProperty("autouser.root.username").equals(username) || !environment.getProperty("autouser.root.password").equals(password)) return null; + + UserInfo userInfo = new UserInfo(); + userInfo.setName(username); + userInfo.setEmail(environment.getProperty("autouser.root.email")); + userInfo.setCreated(new Date()); + userInfo.setLastloggedin(new Date()); + userInfo.setAuthorization_level((short)1); + userInfo.setUsertype((short)1); + userInfo = this.apiContext.getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo); + + UserRole role = new UserRole(); + role.setRole(Authorities.ADMIN.getValue()); + role.setUserInfo(userInfo); + this.apiContext.getDatabaseRepository().getUserRoleDao().createOrUpdate(role); + + Credential credential = new Credential(); + credential.setUserInfo(userInfo); + credential.setPublicValue(username); + credential.setSecret(password); + credential.setProvider((int)TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue()); + credential.setCreationTime(new Date()); + credential.setLastUpdateTime(new Date()); + credential.setStatus(0); + return this.apiContext.getDatabaseRepository().getCredentialDao().createOrUpdate(credential); + } } diff --git a/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepository.java b/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepository.java index cc8eaf538..4f796c068 100644 --- a/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepository.java +++ b/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepository.java @@ -18,6 +18,7 @@ public interface DatabaseRepository { ResearcherDao getResearcherDao(); ServiceDao getServiceDao(); UserInfoDao getUserInfoDao(); + UserRoleDao getUserRoleDao(); InvitationDao getInvitationDao(); CredentialDao getCredentialDao(); UserTokenDao getUserTokenDao(); diff --git a/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepositoryImpl.java b/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepositoryImpl.java index 5f82b2d66..21af3271e 100644 --- a/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepositoryImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/services/DatabaseRepositoryImpl.java @@ -6,6 +6,8 @@ import eu.eudat.dao.entities.security.UserTokenDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.persistence.EntityManager; + /** * Created by ikalyvas on 1/4/2018. */ @@ -26,6 +28,9 @@ public class DatabaseRepositoryImpl implements DatabaseRepository{ private CredentialDao credentialDao; private UserTokenDao userTokenDao; private ExternalDatasetDao externalDatasetDao; + private UserRoleDao userRoleDao; + + private EntityManager entityManager; @Autowired private void setDataRepositoryDao(DataRepositoryDao dataRepositoryDao) { @@ -166,4 +171,19 @@ public class DatabaseRepositoryImpl implements DatabaseRepository{ public void setExternalDatasetDao(ExternalDatasetDao externalDatasetDao) { this.externalDatasetDao = externalDatasetDao; } + + @Override + public UserRoleDao getUserRoleDao() { + return userRoleDao; + } + + @Autowired + public void setUserRoleDao(UserRoleDao userRoleDao) { + this.userRoleDao = userRoleDao; + } + + @Autowired + public void setEntityManager(EntityManager entityManager) { + this.entityManager = entityManager; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/types/Authorities.java b/dmp-backend/src/main/java/eu/eudat/types/Authorities.java new file mode 100644 index 000000000..6fb07fdc7 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/types/Authorities.java @@ -0,0 +1,38 @@ +package eu.eudat.types; + +import java.util.Arrays; +import java.util.List; + +/** + * Created by ikalyvas on 1/30/2018. + */ +public enum Authorities { + USER(0), MANAGER(1), ADMIN(2); + + private Integer value; + + private Authorities(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static Authorities fromInteger(Integer value) { + switch (value) { + case 0: + return USER; + case 1: + return MANAGER; + case 2: + return ADMIN; + default: + throw new RuntimeException("Unsupported Authority Type"); + } + } + + public static List all(){ + return Arrays.asList(USER,ADMIN,MANAGER); + } +} diff --git a/dmp-backend/src/main/resources/application.properties b/dmp-backend/src/main/resources/application.properties index 3511a3759..592f11ea9 100644 --- a/dmp-backend/src/main/resources/application.properties +++ b/dmp-backend/src/main/resources/application.properties @@ -62,4 +62,7 @@ twitter.login.redirect_uri=http://dl043.madgik.di.uoa.gr:8080/login/twitter #persistence.hibernate.connectionpool.c3p0.test_connection_on_checkin = true #persistence.hibernate.connectionpool.c3p0.test_connection_on_checkout = false #persistence.hibernate.connectionpool.c3p0.preferred_test_query = select 1 -########################Persistence/Hibernate/Connection pool#################### \ No newline at end of file +########################Persistence/Hibernate/Connection pool#################### +autouser.root.email = root@dmp.com +autouser.root.password = root +autouser.root.username = root \ No newline at end of file diff --git a/dmp-frontend/src/app/models/login/Principal.ts b/dmp-frontend/src/app/models/login/Principal.ts index 6d5049447..08b7e963b 100644 --- a/dmp-frontend/src/app/models/login/Principal.ts +++ b/dmp-frontend/src/app/models/login/Principal.ts @@ -13,7 +13,7 @@ export class Principal implements Serializable { this.token = item.token; this.name = item.name; this.expiresAt = item.expiresAt; - this.appRoles = item.appRoles; + this.appRoles = item.authorities; return this; } } diff --git a/dmp-frontend/src/app/services/auth/auth.service.ts b/dmp-frontend/src/app/services/auth/auth.service.ts index be6a91dd8..340c8a989 100644 --- a/dmp-frontend/src/app/services/auth/auth.service.ts +++ b/dmp-frontend/src/app/services/auth/auth.service.ts @@ -100,9 +100,8 @@ export class AuthService { let headers = this.headers; headers = headers.set('AuthToken', principal.token) return this.http.post(url, null, { headers: headers }) - .map((r: Response) => { - const princ = this.current(JsonSerializer.fromJSONObject(r.json(), Principal)); - //this.loginContextSubject.next(true); + .map((res: any) => { + const princ = this.current(JsonSerializer.fromJSONObject(res.payload, Principal)); return princ; }) .catch((error: any) => { diff --git a/dmp-frontend/src/app/unauthorized/unauthorized.component.ts b/dmp-frontend/src/app/unauthorized/unauthorized.component.ts index 4e7bb7d09..f8c067519 100644 --- a/dmp-frontend/src/app/unauthorized/unauthorized.component.ts +++ b/dmp-frontend/src/app/unauthorized/unauthorized.component.ts @@ -25,6 +25,7 @@ export class UnauthorizedComponent { this.authService.me().subscribe( principal => { if (!principal) this.router.navigate(['/login'], { queryParams: { returnUrl: returnUrl } }); + else this.router.navigate(["/"]) }, err => console.error('An error occurred', err)); }